L
LLLOS.ai
Learn
L

Chapter 3 — Arrays

Class 10 · Computer Applications

Overview

This unit introduces arrays, a key data structure used in programming to hold collections of values of the same type in contiguous memory. The unit begins with the idea of an array, how it is represented in memory, and the rules for declaring and initialising arrays. It develops skills to traverse arrays, access elements by index, and perform basic operations such as insertion and deletion. Students learn commonly used search methods — linear and binary search — and simple sorting algorithms: selection, bubble and insertion sorts. The unit then moves on to two-dimensional arrays (matrices) and basic matrix operations: addition, transpose and the conceptual idea of multiplication. String handling using character arrays is covered, and common array problem-solving techniques like two-pointer, sliding window and prefix sums are introduced. Practical programming exercises help build confidence in implementing solutions and testing edge cases. Understanding arrays is essential because they form the foundation for more advanced structures and algorithms used in real-world tasks such as data storage, processing tabular data, image representation and performance-critical programs.

Learning Objectives

  • Define arrays and explain their purpose and properties.
  • Declare and initialise one-dimensional and two-dimensional arrays in code.
  • Access and modify array elements using indices and loops correctly.
  • Traverse arrays to compute aggregates like sum, maximum and count of items.
  • Perform insertion and deletion operations on arrays and explain their costs.
  • Implement linear and binary search and choose the correct one for a situation.
  • Sort arrays using selection, bubble and insertion sorts and explain their complexity.
  • Apply array techniques such as two-pointer, sliding window and prefix sums to solve problems.

Topics in this chapter

19 topics · tap a topic title to jump straight to it.

💻1

Introduction to Arrays

What is an array?
An array is a structured collection of elements, where each element is of the same data type and is stored in adjacent memory locations. An array gives one name to a group of related values so that we can operate on that group using index numbers. The key idea is that each element can be reached directly by using an index, so arrays provide fast random access to data.

Why arrays matter
Arrays are used whenever we have many items of the same kind: lists of student marks, daily temperatures, characters of a word, or elements of a matrix. Most algorithms that manipulate collections—sorting, searching, merging—are defined on arrays or similar structures. Learning arrays prepares you for more advanced data structures like lists, stacks, queues and for understanding algorithm complexity.

Basic characteristics
Every array has an element type, a fixed or chosen size at creation, and ordered positions starting at a base index. Many programming languages use zero-based indexing, where the first element is at index 0. Arrays store elements in contiguous memory, which helps performance because consecutive elements are near each other in memory.

Advantages and limitations
Arrays provide constant-time access to any position (O(1)), are simple to understand and have low memory overhead for fixed-size collections. However, their size may be fixed (static arrays) so they cannot grow easily without creating a larger array and copying elements. Inserting or deleting elements in the middle requires shifting many elements, making such operations O(n) in time for typical arrays.

Everyday examples
Think of an array as a row of lockers labelled 0,1,2,... where each locker holds one item. To get the item in locker 5 you go straight to locker 5 rather than checking lockers 0–4 first. This direct access is what makes arrays especially useful for many programming tasks.

How this unit uses arrays
Throughout the unit you will declare and initialise arrays, traverse them with loops, perform additions and deletions, apply searches and sorts, handle two-dimensional arrays for matrices, and develop problem-solving techniques that use arrays effectively. These skills will be practised through short programs and examples typical for Class 10 level.

📌 Examples
  • Store marks for 30 students in int marks[30] and access the 10th student's marks using marks[9] (zero-based indexing).
  • Represent the seven days of the week as a string array days[7] where days[0] = "Sunday" and so on.
🧮 Formulas
  1. Address of A[i] = base_address + (i * size_of(element))
  2. Array index range (zero-based) = 0 to n-1 for an array of size n
📊 Visual ideas
Draw a row of contiguous boxes labelled A[0], A[1], ..., A[n-1] with addresses increasing left to right.
Sketch a pointer to the base address with arrows to successive elements showing contiguous layout.
⚖️2

Declaration and Initialisation

Declaring arrays
To use an array in a program you must declare it first. Declaration tells the compiler or interpreter that you need space for a fixed number of elements of a specific type. For example, int arr[5]; declares an integer array that can hold five integers. The declaration gives the array a name and a capacity; later you use that name with indices to refer to the elements.

Static and dynamic aspects
In many languages arrays are static in size: once declared, the number of elements does not change. Some modern languages or libraries offer dynamic arrays (lists) that grow or shrink automatically. For Class 10, focus on static arrays and understand how to create a larger array and copy elements when more space is needed.

Initialisation at declaration
You can assign values to elements immediately when you declare an array. For example, int a[5] = {2,4,6,8,10}; fills the array with five values. If you supply fewer initial values than the declared size, the remaining elements may default to zero or an empty value depending on the language; always check the language rules.

Step-by-step initialisation in code
You can also initialise arrays later using loops. For example, to set arr[i] = i*2 for each index you write a for-loop that visits each index and stores the calculated value. This method is useful when values follow a pattern or depend on input from the user.

Initialising two-dimensional arrays
For matrices you provide row-wise initialisation such as int mat[2][3] = {{1,2,3},{4,5,6}}; or use nested loops to fill rows and columns. Nested loops allow computed initial values and make it easy to read values row by row from user input or a file.

Common mistakes and good practices
Do not declare an array too small for the data you will store; this leads to overflow and errors. Always initialise arrays before reading their values to avoid using garbage values in calculations. Use named constants for sizes (for example MAX_STUDENTS) instead of magic numbers in code, and comment whether indexing is zero-based or one-based to avoid off-by-one errors.

Capacity vs logical size
Understand the difference between the physical capacity (declared size) and logical size (number of elements actually used). After inserting or deleting elements keep track of the logical size in a variable; this prevents processing uninitialised or unused cells.

📌 Examples
  • Declare and initialise: int arr[5] = {1, 2, 3, 4, 5};
  • Using a loop: for(i=0;i<5;i++) arr[i] = i * i; // stores squares 0,1,4,9,16
🧮 Formulas
  1. Number of elements = declared size n
  2. Valid index range (zero-based) = 0, 1, ..., n-1
📊 Visual ideas
Sketch an array of boxes indexed 0 to 4 with initial values placed in each box.
Nested-box drawing showing rows and columns for a 2x3 matrix being initialised row by row.
💻3

One-Dimensional Array Traversal

Traversal defined
Traversal of an array means visiting each element one by one to perform a task such as reading, printing, summing or comparing values. Traversal is the basis for many array algorithms. For a one-dimensional array a single loop is sufficient to reach all elements in order.

Loop choices
You can use different types of loops: a for-loop is the most common because it provides a clear starting index, ending condition and increment step. A while-loop or do-while loop can also be used when the number of iterations depends on a condition other than a fixed size. The general structure is: start from the first valid index and move to the last valid index while performing the desired operation on arr[i].

Common traversal tasks
Traversal is used for: computing the sum and average of elements, finding the maximum and minimum values, counting elements that meet a condition (for example, count of even numbers), printing elements, and copying array contents. Each of these tasks requires accessing every element at least once in general, so traversal cost is O(n) time where n is the number of elements.

Direction of traversal
Usually you traverse from left to right (index 0 to n-1). Sometimes you traverse from right to left (n-1 down to 0), for example when you wish to remove elements while visiting them so that shifting logic does not corrupt upcoming indices, or to reverse the array in-place using swaps from both ends.

In-place updates
Traversal can be used to modify elements without extra space. For example, to double all values do arr[i] = arr[i] * 2 inside the traversal loop. Because the same array is updated, extra memory use is O(1).

Using traversal for aggregation
To compute the sum set sum = 0 first, then in the loop add arr[i] to sum. To compute maximum set max = arr[0] and update if arr[i] > max during traversal. Always consider edge cases: empty arrays (n=0) require special handling before accessing arr[0] for initial values.

Performance and practice
Traversal visiting each element once costs linear time O(n). Practice writing clean loops with correct loop bounds and clear variable names for index and size to avoid off-by-one and other indexing errors. Adding comments and small test traces for sample arrays helps catch mistakes early when learning.

📌 Examples
  • Compute sum: sum=0; for(i=0;i<n;i++) sum += arr[i];
  • Find max: max = arr[0]; for(i=1;i<n;i++) if(arr[i]>max) max=arr[i];
🧮 Formulas
  1. Sum = Σ arr[i] for i = 0 to n-1
  2. Average = Sum / n (when n > 0)
📊 Visual ideas
Draw a row of boxes labelled A[0]..A[n-1] with an arrow showing the loop visiting each element left to right.
Illustration of reverse traversal with arrows from A[n-1] down to A[0].
🧫4

Accessing Array Elements and Indexing

Indexing basics
Accessing an array element means selecting it by its index. The typical syntax is array[index]. The index tells the program how many steps from the base address to move to reach the required element. In most programming languages the first index is 0, so the last index of an array with n elements is n-1.

Index expressions
You may use arithmetic inside the index, for example array[i+1], array[2*j], or array[i-1]. These expressions evaluate to integer indices; ensure the final index value lies within the valid range before accessing the array. Using computed indices allows flexible access patterns: skipping elements, accessing pairs, or computing positions dynamically in loops.

Bounds and errors
One of the most frequent errors is accessing outside the valid index range. Accessing array[n] or array[-1] is invalid for zero-based arrays. Many high-level languages check bounds and raise an error; low-level languages may not check and can exhibit undefined behaviour. Always validate any index that comes from user input or computation before using it to access the array.

Practical usage
Array elements behave like ordinary variables: you can read array[i], assign array[i] = value, and use array[i] in expressions. For example, total = array[0] + array[1] + array[2] adds the first three elements. Use descriptive names and constants for array size: for example, define MAX = 100 and loop for(i=0;i

Multi-dimensional indexing
For two-dimensional arrays use two indices array[i][j] where i is usually the row and j the column. Make sure to follow the same indexing convention and check both row and column bounds before access. When calculating addresses manually, use the row-major formula base + ((i * num_columns) + j) * element_size to understand how indices map to memory offsets.

Off-by-one pitfalls
Many bugs come from loops that run one iteration too many or too few. Carefully set loop start and end conditions. For zero-based arrays iterate with i=0; i

Testing and debugging
Trace code with small arrays and print index values during execution to verify they remain within expected ranges. Use assertions like assert(0 <= i && i < n) where possible to catch errors early during development.

📌 Examples
  • Access third element: value = array[2];
  • Set the last element: array[n-1] = 0 for an array of size n.
🧮 Formulas
  1. Valid indices (zero-based): 0 <= i <= n-1
  2. Last index = n-1
📊 Visual ideas
Row of boxes with index labels and an arrow showing array[i] selection.
Grid showing array[i][j] selection in a 2-D array with row and column indices.
💻5

Insertion and Deletion in One-Dimensional Arrays

Insertion concept
Insertion means adding a new element at a selected position in the array. There are three common cases: inserting at the end, inserting at the beginning, and inserting in the middle. If the array has unused capacity at the end, insertion at the end is simple: place the new value at index equal to the current logical size and increment the size. Insertion elsewhere requires shifting elements to make room.

Detailed insertion steps
To insert at position pos in an array of logical size n (0 <= pos <= n): first check there is space (n < capacity). Then, starting from i = n-1 down to pos, move arr[i] to arr[i+1]. This shifts elements one step right. After shifting, set arr[pos] = new_value and increase the logical size n by 1. Inserting at pos=0 shifts all elements and is therefore the most expensive in terms of shifts; inserting at pos=n (end) needs no shifts.

Deletion concept
Deletion removes the element at position pos and moves later elements left to fill the gap. To delete at pos (0 <= pos <= n-1): for i from pos to n-2 set arr[i] = arr[i+1]. Finally decrement the logical size n by 1. Deleting the last element (pos = n-1) needs no shifting and is O(1) time.

Edge cases and checks
Always check that pos is within valid bounds before insertion or deletion. Handle empty arrays when deleting (n=0) by reporting an error. When inserting, ensure there is available capacity; if not, you may need to create a new larger array and copy elements into it, which costs O(n) time and space.

Time complexity and cost
Insertion or deletion at arbitrary positions may require shifting on average n/2 elements, therefore the time complexity is O(n). Insertion at the end when space exists is O(1). When many insertions and deletions are needed at arbitrary places, consider different data structures such as linked lists or dynamic arrays that manage resizing.

Implementing shifts carefully
When shifting elements for insertion do it from right to left to avoid overwriting elements you still need to move. For deletion shift left from pos to n-2. After deletion, optional cleanup sets the freed cell to a default value to avoid stale data, especially in environments where uninitialised use may cause errors.

Practical tips
Keep a variable for logical size and update it on every insertion and deletion. Use clear comments and consistent variable names. Test with small arrays and boundary positions (start, middle, end) to confirm correct shifting behaviour.

📌 Examples
  • Insert 25 at position 2 in [10,20,30,40] (capacity ≥5): shift 30->arr[3], 40->arr[4], set arr[2]=25 -> [10,20,25,30,40].
  • Delete element at position 1 in [5,8,12,15] -> shift 12->arr[1], 15->arr[2], new logical size 3 -> [5,12,15].
🧮 Formulas
  1. Shifts required for insertion at pos = size - pos
  2. Shifts required for deletion at pos = size - pos - 1
📊 Visual ideas
Before and after diagrams showing elements shifted right for insertion with arrows pointing to new positions.
Before and after diagrams showing elements shifted left for deletion with arrows indicating movement.
💻6

Linear Search

Definition and use
Linear search (also called sequential search) examines each element of the array one by one until it finds the target value or reaches the end of the array. It does not require the array to be sorted, so it is a general method that always works for any array, though it is not the fastest for large arrays.

Algorithm details
Start with index i = 0. Compare arr[i] with the target. If equal, return the index i. Otherwise increment i and repeat until i reaches n. If no element matches, report that the target is not found. A simple loop implements these steps. Optionally return the first matching index or all matching indices if duplicates may exist.

Performance and analysis
In the worst case, the search checks all n elements, so time complexity is O(n). On average when the target is present once, about n/2 comparisons are performed. The space complexity is O(1) because no extra storage is needed. Linear search is fine for small arrays or when data is unsorted and sorting cost cannot be justified.

Optimisations and variants
A sentinel technique can avoid a bounds check inside the loop: temporarily place the target at arr[n] (if space permits) and then search without testing for end of array; after finding the match check whether the found position is within original bounds. Another variant scans from both ends toward the centre to find a match faster when the expected position is unknown.

When to use linear search
Use it for small data, unsorted data, or when there are very few searches relative to updates. It is simple to implement and reliable. For many repeated searches on large datasets, sorting first and using binary search or using a hash-based structure is better.

Example behaviour
Searching for 7 in [3,7,1,9] compares 3 (not match), then 7 (match) and returns index 1. Searching for 4 in [2,6,8] will compare all elements and report not found after three checks.

Testing and correctness
Test linear search on empty arrays, arrays with one element, arrays with multiple occurrences of target, and arrays where the target is absent. Confirm the function returns a suitable sentinel (like -1) when not found and the first matching index if required by the problem statement.

📌 Examples
  • Search 7 in [3,7,1,9] -> compare 3 then 7 and return index 1.
  • Search 4 in [2,6,8] -> check all elements and report not found (e.g., return -1).
🧮 Formulas
  1. Worst-case comparisons = n
  2. Average comparisons ≈ (n+1)/2
📊 Visual ideas
Row of boxes showing pointer moving from left to right comparing each element sequentially.
Illustration of sentinel technique with target placed at arr[n] to avoid boundary checks.
💻7

Binary Search

Purpose and precondition
Binary search is an efficient method to locate a target value in a sorted array. The key precondition is that the array must be sorted (in ascending or descending order). Binary search works by repeatedly halving the search interval, discarding the half that cannot contain the target.

Algorithm steps
Set low = 0 and high = n-1. While low <= high compute mid = (low + high) / 2 (integer division). Compare arr[mid] with the target: if equal return mid; if arr[mid] < target (for ascending order) set low = mid + 1; otherwise set high = mid - 1. Repeat until low > high; then the target is not in the array. This halving makes binary search much faster than linear search for large n.

Complexity
Each comparison halves the search space, so the time complexity is O(log n). Space complexity is O(1) for the iterative version. A recursive implementation uses O(log n) stack space. Binary search is very efficient for repeated searches on sorted arrays or when searches are frequent relative to insertions or deletions.

Careful implementation details
A common implementation pitfall is computing mid as (low + high) / 2 which can overflow in some languages when low and high are large. To avoid overflow compute mid = low + (high - low) / 2. Also ensure that updates to low and high move the range and guarantee termination. For arrays sorted in descending order reverse the comparison logic accordingly.

Using binary search in practice
When data is static and many searches are required, sort once and use binary search for each query. For data with frequent updates consider balanced trees or hash structures. Binary search is also a building block in more advanced algorithms, for example finding boundaries or thresholds in monotonic sequences.

Example
To find 15 in sorted [3,7,10,15,20]: initial mid = 2 (value 10) which is less than 15 so search the right half (indices 3..4); mid becomes 3 and value 15 is found at index 3. For not found cases, binary search will narrow to low > high and return not found.

📌 Examples
  • Find 15 in [3,7,10,15,20]: mid checks 10 then 15 and returns index 3.
  • Find 8 in [1,2,4,6]: binary search narrows ranges and reports not found when low > high.
🧮 Formulas
  1. mid = (low + high) / 2 (integer division) or mid = low + (high - low) / 2 to avoid overflow
  2. Worst-case comparisons ≈ ⌊log2(n)⌋ + 1
📊 Visual ideas
Array with arrows showing low, mid, high and how the search interval is halved each step.
Sequence of intervals demonstrating narrowing from full array to a single element.
🗳️8

Selection Sort

Overview
Selection sort is a straightforward comparison-based sorting algorithm. It sorts an array by repeatedly finding the minimum (or maximum) element from the unsorted part and moving it to the front. Over iterations the sorted portion grows from one side while the unsorted portion shrinks.

Step-by-step method
Start with the whole array as unsorted. For each position i from 0 to n-2, find the smallest element in the unsorted range i..n-1. Swap that minimum element with the element at position i. After the first pass the smallest element is in position 0; after the second pass the second smallest is in position 1 and so on until the array is fully sorted.

Number of operations
Selection sort always performs the same number of comparisons, regardless of initial order: on the first pass it compares n-1 elements, on the second n-2 and so on. Total comparisons are n(n-1)/2 which is O(n^2). However number of swaps is at most n-1 because at most one swap happens per pass. This can be an advantage when swaps are costly relative to comparisons.

Stability and memory
Selection sort is not stable by default (equal elements may change relative order), but it sorts in-place using only constant extra space O(1). Because it uses simple loops and few writes it is easy to implement and reason about, which is good for class exercises.

When to use
Selection sort is suitable for small arrays and for situations where memory writes are expensive and must be minimised. For larger arrays prefer faster algorithms like quicksort or mergesort, which run in O(n log n) on average.

Example trace
Sort [29,10,14,37,13]: pass1 min 10 -> swap with 29 -> [10,29,14,37,13]; pass2 min 13 in remaining -> swap with 29 -> [10,13,14,37,29]; pass3 min 14 already in place -> [10,13,14,37,29]; pass4 min 29 swap with 37 -> [10,13,14,29,37].

Practice tips
Write the selection logic clearly: use an inner loop to find the index of the minimum, then perform a conditional swap only if the minimum index is different from i. This avoids unnecessary swaps in already-correct positions.

📌 Examples
  • Sort [29,10,14,37,13] -> successively select minima and swap to get [10,13,14,29,37].
  • Sort a short list of 5 items to demonstrate passes in class.
🧮 Formulas
  1. Comparisons in selection sort = n(n-1)/2
  2. Swaps ≤ n-1
📊 Visual ideas
Sequence of array states after each pass showing the sorted portion growing from left to right.
Illustration marking the minimum found in the unsorted part each pass and the swap with position i.
💻9

Bubble Sort

Principle
Bubble sort repeatedly passes through the array, comparing adjacent elements and swapping them if they are in the wrong order. Each pass causes the largest unsorted element to move (or "bubble") to its correct position at the end of the unsorted section. Repeating passes eventually sorts the whole array.

Algorithm outline
For i from 0 to n-2 perform a pass: for j from 0 to n-2-i if arr[j] > arr[j+1] then swap arr[j] and arr[j+1]. After the first pass the largest element is at index n-1; after the second pass the second largest moves to n-2, and so on. The inner loop shortens by i each time because the last i elements are already in place.

Optimisation
A useful optimisation is to check whether any swaps occurred during a pass. If no swaps happened, the array is already sorted and you can exit early. This reduces the best-case time complexity to O(n) when the array is already sorted, while the general and worst-case remain O(n^2).

Stability and simplicity
Bubble sort is stable: equal elements retain their relative order because swaps only occur when the left element is greater than the right. It uses constant extra space O(1) and is easy to implement and visualise, making it a good teaching tool for nested loops and swaps.

Performance trade-offs
Bubble sort performs poorly on large arrays compared to more advanced sorts because of its O(n^2) behaviour in average and worst cases. However its simplicity and the early-exit optimisation make it acceptable for small arrays or nearly-sorted data.

Teaching example
Sort [4,3,2,1] with bubble sort: pass1 swaps produce [3,2,1,4], pass2 -> [2,1,3,4], pass3 -> [1,2,3,4]. With the swap-check optimisation a sorted array would be detected in the first pass and the algorithm would stop early.

Implementation note
Take care with loop bounds so j+1 never exceeds n-1. Use clear variable names and consider printing the array after each pass while learning to see the bubble effect.

📌 Examples
  • Sort [4,3,2,1]: after passes the array becomes [3,2,1,4], then [2,1,3,4], then [1,2,3,4].
  • Detect already sorted [1,2,3] by finding no swaps in the first pass and stopping.
🧮 Formulas
  1. Worst-case comparisons ≈ n(n-1)/2
  2. Best-case (with swap check) = n-1 comparisons
📊 Visual ideas
Illustrate adjacent swaps across passes with arrows showing larger elements moving to the right per pass.
Plot of pass number vs portion sorted, demonstrating sorted tail growing from right.
💻10

Insertion Sort

Idea
Insertion sort builds a sorted portion at the beginning of the array. Starting from the second element, each element (called the key) is compared with elements in the sorted portion and inserted into its correct position by shifting larger elements to the right. Insertion sort is efficient for small or nearly-sorted arrays.

Steps
Start with i = 1 to n-1. Set key = arr[i] and j = i-1. While j >= 0 and arr[j] > key shift arr[j] to arr[j+1] and decrement j. After the loop place key at arr[j+1]. Repeat for each element until the array is sorted. The inner while loop moves elements to make room for the key.

Complexity
Worst-case time is O(n^2), occurring for reverse-sorted input where many shifts are needed. Best-case time is O(n) when the array is already sorted, because the inner loop does no shifting. Insertion sort is stable and works in-place using O(1) extra space.

Where it shines
Insertion sort is very efficient for small arrays or for arrays that are nearly sorted, where it can be faster than other O(n log n) algorithms because of low overhead. It is often used as the final stage of hybrid sorting algorithms for small subarrays.

Visualising insertion
Imagine sorting a hand of playing cards: you take each card and insert it into the correct position among the cards already in your hand. You shift larger cards to the right to make space. This analogy helps understand the shifting behaviour of insertion sort.

Practical advice
When implementing, ensure the inner loop moves elements to the right starting from i-1 down to 0 to avoid overwriting. Test on sorted, reversed and random arrays to observe different performance patterns. Use insertion sort when n is small or when subarrays are expected to be almost sorted.

📌 Examples
  • Insert 3 into [1,2,4,5] by shifting 4 and 5 to get [1,2,3,4,5].
  • Sort [5,2,4,6,1,3] by repeated insertion producing sorted prefix growth over passes.
🧮 Formulas
  1. Worst-case comparisons ≈ n(n-1)/2
  2. Best-case comparisons ≈ n-1
📊 Visual ideas
Sequence of array states showing sorted portion on the left growing and key insertion each pass.
Illustration of shifts to the right to create space for the key element.
💻11

Two-Dimensional Arrays (Matrices)

Definition and structure
A two-dimensional array (commonly called a matrix) is a collection of elements arranged in rows and columns. Each element is identified by two indices: usually the first for the row and the second for the column, for example A[i][j]. Two-dimensional arrays are used to represent tables, grids, images (pixel arrays), and mathematical matrices.

Declaration and layout
You declare a matrix by specifying the number of rows and columns, for example int mat[3][4] declares a matrix with 3 rows and 4 columns. Internally, most languages store matrices in row-major order: elements of the same row appear consecutively in memory. Some languages use column-major order; check language documentation. Knowing layout is important for performance when traversing large matrices because accessing consecutive memory is faster.

Initialisation
Two-dimensional arrays can be initialised with nested braces, such as int m[2][3] = {{1,2,3},{4,5,6}}; or by using nested loops that set each mat[i][j] to a value computed from i and j or read from input. Use nested loops with the outer loop iterating over rows and inner loop over columns to visit all elements in a structured way.

Traversal techniques
Traverse row-wise: for i from 0 to rows-1 and for j from 0 to cols-1 process mat[i][j]. Column-wise traversal swaps the role of loops and may be less cache-friendly in row-major languages. Some problems require diagonal traversals or visiting neighbours; in those cases add bounds checks to avoid accessing outside the matrix.

Common operations
Typical matrix operations include computing row sums, column sums, finding max/min values, transposing the matrix, adding two matrices and multiplying matrices (concept described separately). For row or column sums, maintain an accumulator and update it in the inner loop or with a separate nested loop for each row/column.

Edge cases and bounds
Always verify indices: valid row indices are 0 to m-1 and column indices are 0 to n-1. When reading or printing ensure loops cover the exact declared sizes. For jagged arrays (rows with different lengths) handle each row separately with its length. Test matrices with one row or one column to ensure code handles narrow matrices correctly.

Applications and practice
Matrices are used in mathematics for linear algebra, in computer graphics for transformations, in image processing to store pixel grids, and in representing game boards. Practice writing nested loops to implement matrix addition, transpose and simple manipulations to build solid understanding.

📌 Examples
  • Declare int mat[3][3] and initialise to represent a 3x3 matrix of numbers.
  • Compute sum of each row using nested loops: for each row set sum=0 then for each column add mat[i][j].
🧮 Formulas
  1. Total elements in matrix = rows * columns = m * n
  2. Element access: valid indices 0 <= i <= m-1, 0 <= j <= n-1
📊 Visual ideas
Grid of boxes with row indices 0..m-1 and column indices 0..n-1 with an element A[i][j] highlighted.
Diagram showing row-major layout mapping rows into contiguous memory blocks.
12

Matrix Addition and Transpose

Matrix addition
Matrix addition combines two matrices of the same size by adding corresponding elements. If A and B are both m×n, their sum C is also m×n with C[i][j] = A[i][j] + B[i][j]. The operation is performed element-wise using nested loops over rows and columns. Before adding, always verify that both matrices have identical row and column counts; otherwise addition is undefined.

Transpose
The transpose of a matrix A, written A^T, is obtained by swapping rows and columns: the element at row i and column j in A becomes the element at row j and column i in A^T. If A is m×n then A^T is n×m. For square matrices (n×n), transpose reflects along the main diagonal and can be performed in-place by swapping pairs A[i][j] and A[j][i] for i < j.

Implementing addition
To add two matrices use nested loops: for i from 0 to m-1 and for j from 0 to n-1 set C[i][j] = A[i][j] + B[i][j]. Initialise C with the desired dimensions and fill it by the inner loop computations. The operation requires visiting every element once, so the time complexity is O(mn).

Implementing transpose
For non-square matrices create a new matrix B sized n×m and set B[j][i] = A[i][j] in nested loops. For square matrices you can swap A[i][j] and A[j][i] for all i < j which keeps the operation in-place and saves memory. Remember to avoid redundant swaps that would undo previous changes; use i < j to limit swaps to one per pair.

Applications
Matrix addition is used in numerical computations and combining results from separate data sources. Transpose is used in linear algebra, converting between row and column representations, and preparing matrices for multiplication or certain algorithms where column access is needed.

Complexity and checks
Both addition and transpose visit each element once and thus cost O(mn) time. Always check dimensions and test with small matrices, including rectangular and square cases, to ensure correctness and handle edge cases like empty matrices.

📌 Examples
  • Add A = [[1,2],[3,4]] and B = [[5,6],[7,8]] to get [[6,8],[10,12]].
  • Transpose A = [[1,2,3],[4,5,6]] to get [[1,4],[2,5],[3,6]].
🧮 Formulas
  1. Matrix addition: C[i][j] = A[i][j] + B[i][j]
  2. Transpose: (A^T)[j][i] = A[i][j]
📊 Visual ideas
Two matrices side by side with arrows showing element-wise addition mapping to result matrix.
Matrix with highlighted element A[1][2] and arrow to position in transpose A^T[2][1].
✖️13

Matrix Multiplication (Conceptual)

When multiplication is defined
Matrix multiplication combines two matrices A and B to produce a new matrix C when the number of columns of A equals the number of rows of B. If A is m×p and B is p×n, the resulting matrix C will have dimensions m×n. Each element of the result is computed from a row of A and a column of B.

Computation rule
Element C[i][j] is the dot product of row i of A and column j of B: C[i][j] = Σ_{k=0 to p-1} A[i][k] * B[k][j]. Implementation uses three nested loops: outer over i (rows of A), middle over j (columns of B), and inner over k to accumulate the products. Initialise C[i][j] to zero before accumulating the sum for each pair (i,j).

Time complexity
Standard matrix multiplication requires O(m * p * n) arithmetic operations. For square matrices of size n this is O(n^3). Because this is expensive for large n, more advanced algorithms exist which reduce complexity, but they are beyond the scope of Class 10. Understanding the triple loop implementation is sufficient for typical exercises.

Practical tips
Always check dimensions before multiplying: if A has columns p and B has rows p multiplication is valid. Use correct loop order and initialise the result elements to zero. When coding, pay attention to indexing and keep track of loop variables. For readability name loops meaningfully like for row i, for column j, for k in range(p).

Applications
Matrix multiplication is fundamental in computer graphics transformations, combining linear maps, solving systems of linear equations and representing transitions in algorithms. It underlies many practical computations and is therefore an important concept to grasp.

Examples and verification
Use small examples to verify understanding: multiply A = [[1,2],[3,4]] and B = [[5,6],[7,8]] to compute C[0][0] = 1*5 + 2*7 = 19, etc. Verify dimensions and compare manual computation with program output to catch errors in loop bounds or indices.

📌 Examples
  • Multiply A = [[1,2],[3,4]] and B = [[5,6],[7,8]] to get C where C[0][0] = 1*5 + 2*7 = 19, etc.
  • If A is 2x3 and B is 3x2 the result is 2x2 calculated via dot products of rows of A with columns of B.
🧮 Formulas
  1. \[C[i][j] = Σ_{k=0 to p-1} A[i][k] * B[k][j]\]
  2. Dimensions: (m×p) × (p×n) -> (m×n)
📊 Visual ideas
Diagram showing row i of A and column j of B with arrows indicating pairwise multiplications summed to form C[i][j].
Grid illustrating dimensions of A, B and resulting C with labelled i, j and k indices.
💻14

Arrays of Characters and Strings

Character arrays
An array of characters stores a sequence of characters in contiguous memory. In many programming languages a string is represented as a character array terminated by a special character. When you treat strings as arrays you can access or modify individual characters by their index, enabling operations like reversal, character replacement and searching for characters.

String operations
Common operations include finding string length by counting characters until the termination marker, concatenating two strings by appending characters from the second string to the end of the first (careful to keep space for a termination marker), comparing two strings lexicographically by comparing characters one by one, and extracting substrings by copying a range of characters into a new array.

Indexing and bounds
When working with character arrays always ensure there is enough space for all characters plus any termination marker used by the language. Accessing beyond the valid range can lead to wrong results or runtime errors. When performing concatenation or copying, compute or check lengths first so you do not overwrite memory outside the array.

In-place transformations
Some operations can be done in-place for efficiency. For example, reversing a string is done by swapping characters at positions i and n-1-i for i from 0 to n/2 - 1. In-place modifications are memory-efficient but care must be taken to use correct loop limits and to handle odd-length strings where the middle character remains unchanged.

Immutability and performance
Modern high-level languages often treat strings as immutable, meaning concatenation creates a new string rather than modifying existing memory. This has performance implications when concatenating repeatedly. Knowing that a string is implemented as a character array helps you understand why repeated concatenation may be costly and why building strings using a buffer or list of characters is sometimes preferred.

Practical examples
Count vowels by traversing the character array and checking each character, find the first occurrence of a character using linear search on the characters, and produce a substring by copying characters between indices. These tasks reinforce array traversal and index management skills.

📌 Examples
  • Reverse 'MATH' by swapping characters: swap positions 0 and 3, 1 and 2 to obtain 'HTAM'.
  • Concatenate 'HEL' and 'LO' into a new array to create 'HELLO' by copying characters sequentially.
🧮 Formulas
  1. Length = number of characters before termination marker
  2. Valid character indices: 0 to length-1
📊 Visual ideas
Row of character boxes showing indices and a termination marker at the end.
Illustration of swapping characters at positions i and n-1-i during reversal.
💻15

Common Array Problems and Techniques

Typical problem types
Many programming problems involve arrays: finding pairs that add to a target, removing duplicates, rotating or shifting arrays, merging sorted arrays, finding the maximum-sum subarray of fixed size, and detecting patterns within arrays. Solving these problems reliably uses a set of common techniques that reduce time and space cost.

Two-pointer technique
This method uses two indices (pointers) that move through the array in a coordinated way. For example, to find a pair that sums to a target in a sorted array, set left at 0 and right at n-1, compute current_sum = arr[left] + arr[right]. If current_sum equals target return the pair; if it is less increase left; if greater decrease right. This technique runs in O(n) time for that problem.

Sliding window
Sliding window maintains a window of consecutive elements. For fixed window size k compute the sum of the first k elements, then slide the window right by removing the leftmost element and adding the new rightmost element: new_sum = old_sum - arr[i] + arr[i+k]. This gives O(n) time for problems like maximum sum of k consecutive elements. For variable-size windows use two pointers that expand and shrink the window based on conditions.

Prefix sums
Compute an array of prefix sums where prefix[i] = arr[0] + ... + arr[i]. Then the sum of any subarray arr[l..r] is prefix[r] - prefix[l-1] (with care for l=0). Prefix sums speed up repeated range-sum queries after O(n) precomputation.

Merging sorted arrays
Merge two sorted arrays by using two pointers i and j starting at their beginnings, repeatedly picking the smaller element to append to the result and advancing that pointer. This yields an O(n1 + n2) time merge and is the same approach used in merge sort.

Removing duplicates
For a sorted array remove duplicates in-place by using a write pointer. Traverse with a read pointer; when you find a value different from the last written value copy it to write position and increment write. At the end the write pointer gives the new logical size with unique elements up to that index.

Practical strategy
Analyze constraints: if the array is sorted use two-pointer or binary search; if not consider sorting first if multiple queries make it worthwhile. Think about space: can you do the task in-place or need extra arrays? Practice designing solutions on paper for small examples before coding.

📌 Examples
  • Merge [1,3,5] and [2,4,6] with two pointers to obtain [1,2,3,4,5,6].
  • Find maximum sum of subarray of length k using sliding window: update sum by subtracting arr[i] and adding arr[i+k].
🧮 Formulas
  1. PrefixSum[i] = Σ arr[0..i]
  2. Window-sum update: new_sum = old_sum - arr[i] + arr[i+k]
📊 Visual ideas
Two-pointer diagram showing pointers at starts of two arrays and moving to build merged array.
Sliding window boxes indicating the window moving right step by step with sums updated.
16

Memory Representation and Address Calculation

Contiguous allocation
Arrays are stored in contiguous memory locations so the address of each element can be calculated from the base address. This layout allows direct access to any element using arithmetic on indices without iterating through previous elements. The formula for one-dimensional arrays demonstrates why random access is O(1).

Address calculation formula
For a zero-based one-dimensional array with base_address and element_size (in bytes), the address of element A[i] is base_address + i * element_size. For two-dimensional arrays stored in row-major order with num_columns columns, the address of A[i][j] is base_address + ((i * num_columns) + j) * element_size. These formulas explain how indices map to memory offsets.

Why it matters
Understanding address calculation helps explain performance differences: accessing consecutive elements walks through adjacent memory addresses which is cache-friendly and usually faster. Random jumps that access widely separated elements can be slower due to cache misses.

Bounds and safety
If an index goes out of range the calculated address may point to unrelated memory. High-level languages typically detect this and raise an error; low-level languages may not, leading to undefined behaviour and potential security vulnerabilities. Therefore always perform bounds checks when indices depend on user input or computations.

Pointers and element size
When arrays contain complex elements (structures or records) the element_size equals the size of the structure. Pointer arithmetic advances by element_size so incrementing a pointer to an array moves to the next logical element rather than one byte. This abstraction simplifies navigation but the underlying address calculation still uses sizes.

Practical calculations
Practice computing addresses with simple numbers: if base_address is 1000 and element_size is 4 bytes then address of A[3] is 1000 + 3*4 = 1012. For a 3x4 matrix with element_size 4 bytes address of A[2][1] is base + ((2*4)+1)*4 = base + (9*4) = base + 36. Doing such examples helps solidify the mapping between indices and memory.

Implications for algorithms
Because arrays provide O(1) access, many algorithms rely on direct indexing to be efficient. However, when frequent insertions and deletions are needed, the cost of shifting elements may make other structures preferable. Knowing these trade-offs informs algorithm and data structure choices.

📌 Examples
  • Address of A[3] for base 1000 and element size 4 bytes = 1000 + 3*4 = 1012.
  • Address of A[2][1] in a 3x4 matrix (4 columns) with element size 4 bytes = base + ((2*4)+1)*4.
🧮 Formulas
  1. Address(A[i]) = base + i * element_size
  2. Address(A[i][j]) = base + ((i * num_columns) + j) * element_size
📊 Visual ideas
Memory diagram showing base address and successive element addresses with computed offsets.
Grid of matrix mapping row-major positions to contiguous memory blocks with offsets labelled.
💻17

Errors and Debugging with Arrays

Common errors
Working with arrays often leads to several recurring mistakes: index out-of-bounds access, off-by-one errors in loop limits, forgetting to update logical size after insertion or deletion, using uninitialised elements, and mixing up row and column indices in two-dimensional arrays. Recognising these patterns helps you debug quickly and avoid repeating mistakes.

Tracing and manual testing
One of the best debugging techniques is to trace the code with a small example array. Write down the values of index variables and the array contents at each significant step. Manual tracing reveals how indices change and where a wrong loop bound or direction causes errors. While tracing, pay attention to the logical size variable and how it changes after insertions or deletions.

Print statements and logging
Insert simple print statements to show index values and array snapshots at different points in the program. Print before and after major operations like shifts or swaps. This lightweight logging helps locate the step where the array contents diverge from expected values. In classroom practice, printing intermediate arrays for one or two iterations is an effective teaching tool.

Assertions and defensive checks
Add explicit checks to verify assumptions: for example check that 0 <= i && i < size before accessing array[i]. Validate user inputs that act as indices and check capacity before insertion. Such assertions stop the program with a clear message rather than letting it continue with incorrect memory access.

Common fixes
Off-by-one bugs often come from using <= instead of < or from mismatching zero-based vs one-based conventions. Fix by carefully writing the loop start and end conditions and by testing with the smallest and largest valid indices. When shifting elements for insertion perform shifts from right to left to avoid overwriting source values; for deletion shift left from pos to size-2. Initialise arrays and accumulators to sensible defaults to avoid garbage values in calculations.

Using debugging tools
Modern development environments provide debuggers that let you step through execution, inspect variables, and set breakpoints. Use these tools to watch how indices and element values change. When a bug is found, step back to the last known-good state and test variations to understand the cause. Learning to use a debugger saves time compared to trial-and-error fixes.

Testing strategies
Design tests that include boundary cases: empty arrays, single-element arrays, arrays full to capacity, arrays with duplicates, already-sorted and reverse-sorted arrays. Also test error conditions such as invalid indices. Systematic testing helps find corner-case bugs that simple random tests might miss.

Good coding practices
Use clear variable names like size, capacity, readIndex and writeIndex. Define constants for maximum sizes and comment the indexing convention used. Keep functions small and focused so each piece can be tested separately. These habits reduce bugs and make debugging easier when issues occur.

📌 Examples
  • Off-by-one: looping for i = 0 to <= n instead of i < n causes out-of-range access at i = n; correct to i < n.
  • Uninitialised value used in sum leads to wrong total; initialise sum = 0 and ensure array elements are set before use.
📊 Visual ideas
Flow showing an index check before accessing array[i], and a branch to error handling if out-of-bounds.
Timeline of values printed during a trace run to illustrate how indices and array contents change.
📊18

Arrays vs Other Data Structures

Key comparisons
Arrays provide direct access to elements by index in constant time O(1). However, they have fixed capacity (in static arrays) and inserting or deleting in the middle requires shifting elements, costing O(n) time. Linked lists provide O(1) insertion and deletion when you have a pointer to the position, but accessing the k-th element takes O(k) time because you must traverse from the head.

When arrays are best
Use arrays when you need fast random access and when the number of elements is known or changes rarely. Arrays are memory-efficient for fixed-size data and take advantage of locality of reference, which improves cache performance. They are ideal for storing tables, matrices, and for algorithms that require indexing such as binary search.

When other structures are better
For frequent insertions and deletions in the middle of a collection, linked lists or balanced trees are more efficient. Dynamic arrays (array lists) combine some advantages: they behave like arrays but manage resizing transparently, offering amortised O(1) time for end insertions while keeping random access O(1). Hash tables provide near O(1) average-time lookup and are useful when order is not important.

Hybrid and language-provided types
Many languages provide built-in dynamic array types (called lists, vectors or arraylists) which internally use arrays and handle resizing by allocating a larger array and copying elements. Choose the structure based on expected operations: frequent random access suggests arrays or dynamic arrays; frequent ordered insertions suggest linked lists or trees; frequent membership tests suggest hash-based dictionaries or sets.

Cost and trade-offs
Consider both time and space. Arrays use contiguous memory which can be more compact; linked lists use extra memory per node for pointers. Also consider stability and implementation complexity. Arrays are simpler and sufficient for many tasks; learning other structures helps you choose the right tool when arrays are not ideal.

Summary guidance
Decide by asking: Do I need fast random access? Do I expect many inserts/deletes? Is the size fixed or dynamic? The answers guide whether an array, dynamic array, linked list, or other structure is the correct choice for the problem at hand.

📌 Examples
  • Use a static array of size 365 to store daily temperatures for a year when the number of entries is known in advance.
  • Use a dynamic array (list) to store student records when new students arrive and the total grows over time.
📊 Visual ideas
Table comparing time complexities: access O(1) for arrays vs O(n) for linked lists; insertion O(n) for arrays vs O(1) for lists (given pointer).
Diagram showing memory layout difference: contiguous blocks for arrays vs nodes linked by pointers for linked lists.
💻19

Practical Programming Exercises with Arrays

Purpose of exercises
Practical exercises convert the theory of arrays into reliable code. They teach accurate index management, loop design, handling edge cases and testing. Exercises should cover declaring arrays, reading data, traversing, searching, sorting, inserting and deleting, and working with two-dimensional arrays. Doing small programs reinforces the understanding of array bounds and logical size management.

Exercise types and stepwise approach
Begin with simple tasks and progress to slightly larger ones. Example tasks: read n numbers and print them in reverse, compute sum and average, find maximum and minimum with indices, remove duplicates from a sorted array, merge two sorted arrays, and transpose a matrix. For each problem first outline the input and output, decide whether you will modify the array in-place or use an extra array, then write pseudocode using loops and index variables before coding.

Designing safe code
Always check for boundary conditions: n could be 0 or 1, arrays might already be sorted or full. Use a variable for logical size and update it after insertion or deletion. Initialse accumulators before use, and where required check capacity before inserting to avoid overflow. Comment the indexing convention (zero-based) at the start of the program so readers do not confuse loop bounds.

Testing strategy
Test with small hand-crafted examples first and print intermediate results to verify behaviour. Include tests for edge cases: empty inputs, single-element arrays, arrays with repeated elements, already-sorted arrays and reverse-sorted arrays. After initial tests, try random inputs to increase confidence. When a bug appears trace execution with a small failing example to locate the incorrect index or loop condition.

Examples of practice programs
1) Reverse an array in place: use two indices i and j and swap arr[i] with arr[j] while i

Exam preparation
Practice writing short programs that match ICSE question styles: clear input format, simple loops, precise output. Time your coding and test quickly. Save snippets for common tasks like reading arrays, printing arrays, swapping elements and copying arrays to reuse during exams.

📌 Examples
  • Reverse an array in place: swap arr[i] and arr[n-1-i] for i from 0 to n/2 - 1.
  • Remove duplicates from a sorted array in-place using a write pointer to collect unique values.
📊 Visual ideas
Flowchart-style boxes illustrating read input -> process with loop -> output results for a simple array program.
Diagram showing swaps used in reversing an array with indices i and n-1-i.

Key Concepts

Array
A collection of elements of the same type stored in contiguous memory and accessed by indices.
Index
An integer that identifies the position of an element in an array.
Zero-based indexing
An indexing convention where the first element of an array has index 0.
Bounds checking
Validation that an index lies within the valid range for an array to prevent errors.
Traversal
Visiting each element of an array, typically using a loop.
Insertion (in arrays)
Adding an element at a specified position, often requiring shifting of elements.
Deletion (in arrays)
Removing an element and shifting subsequent elements to fill the gap.
Linear search
A search method that checks elements sequentially until a match is found.
Binary search
An efficient search on a sorted array that repeatedly halves the search interval.
Selection sort
A sorting algorithm that repeatedly selects the minimum element and places it at the start.
Bubble sort
A sorting method that repeatedly swaps adjacent elements that are out of order.
Insertion sort
A sorting algorithm that inserts each element into its correct position within the sorted prefix.
Matrix
A two-dimensional array with rows and columns used to represent tabular data.
Transpose
An operation that flips a matrix over its main diagonal, swapping rows with columns.
Row-major order
A memory layout where consecutive elements of a row are stored in adjacent memory locations.
Prefix sum
An array where each element is the sum of all elements up to that index in the original array.
Sliding window
A technique that maintains a subset of consecutive elements while moving across the array.

Practice Questions

  1. Declare an integer array to hold marks of 40 students and initialise all marks to 0. / 40 छात्रों के अंक रखने के लिए एक पूर्णांक एरे घोषित कीजिए और सभी अंकों को 0 से आरंभ कीजिए।
    Show answer

    English answer: Declare an array with size 40 and set all elements to 0, for example: int marks[40]; for(i=0;i<40;i++) marks[i]=0; / हिंदी उत्तर: 40 आकार का एरे घोषित करें और प्रत्येक तत्व को 0 कर दें, उदाहरण: int marks[40]; for(i=0;i<40;i++) marks[i]=0;

  2. Write steps to insert an element at position pos in an array of current size n. / किसी एरे में वर्तमान आकार n के साथ स्थिति pos पर एक तत्व डालने के चरण लिखिए।
    Show answer

    English answer: 1) Check if n < capacity; 2) For i from n-1 down to pos do arr[i+1] = arr[i]; 3) Set arr[pos] = new_value; 4) Increment n. / हिंदी उत्तर: 1) जांचें कि n < क्षमता है; 2) i को n-1 से pos तक घटाते हुए arr[i+1] = arr[i] करें; 3) arr[pos] = नया_मान रखें; 4) n को बढ़ाएँ।

  3. What is the time complexity of linear search and binary search? Explain when to use each. / लीनियर सर्च और बायनरी सर्च की समय जटिलता क्या है? समझाइए कि कब किसका उपयोग करना चाहिए।
    Show answer

    English answer: Linear search time complexity is O(n); use it for unsorted arrays or small datasets. Binary search time complexity is O(log n); use it when the array is sorted. / हिंदी उत्तर: लीनियर सर्च की समय जटिलता O(n) है; इसका उपयोग असॉर्टेड एरे या छोटे डेटा पर करें। बायनरी सर्च की समय जटिलता O(log n) है; इसका उपयोग तब करें जब एरे सॉर्टेड हो।

  4. Given array [4,2,7,1,3], show steps of selection sort to sort in ascending order. / दिया गया एरे [4,2,7,1,3] चुनान विधि (selection sort) के चरण दिखाइए जिससे यह आरोही क्रम में सॉर्ट हो।
    Show answer

    English answer: Pass1: minimum 1 swap with 4 -> [1,2,7,4,3]; Pass2: min in rest is 2 already at pos1 -> [1,2,7,4,3]; Pass3: min is 3 swap with 7 -> [1,2,3,4,7]; Pass4: min is 4 already -> [1,2,3,4,7]. / हिंदी उत्तर: पास1: न्यूनतम 1 है, 4 के साथ स्वैप करें -> [1,2,7,4,3]; पास2: शेष में न्यूनतम 2 है (पहले स्थान पर) -> [1,2,7,4,3]; पास3: न्यूनतम 3 है, 7 के साथ स्वैप -> [1,2,3,4,7]; पास4: 4 पहले ही सही है -> [1,2,3,4,7]।

  5. How do you compute the transpose of a 2x3 matrix? Give an example. / किसी 2x3 मैट्रिक्स का ट्रांसपोज़ कैसे निकाला जाता है? एक उदाहरण दीजिए।
    Show answer

    English answer: Swap rows and columns to produce a 3x2 matrix. Example: A=[[1,2,3],[4,5,6]] -> A^T=[[1,4],[2,5],[3,6]]. / हिंदी उत्तर: पंक्तियों और स्तम्भों को बदलकर 3x2 मैट्रिक्स बनाते हैं। उदाहरण: A=[[1,2,3],[4,5,6]] -> A^T=[[1,4],[2,5],[3,6]]।

  6. Explain why insertion into the end of an array can be O(1) while insertion at the start is O(n). / समझाइए क्यों एरे के अंत में डालना O(1) हो सकता है जबकि शुरुआत में डालना O(n) होता है।
    Show answer

    English answer: Inserting at the end (if space exists) places the new element at index n without shifting others, so constant time O(1). Inserting at the start needs shifting all n elements one place right, costing O(n). / हिंदी उत्तर: अंत में डालने पर (स्थानीय क्षमता रहते) अन्य तत्वों को शिफ्ट नहीं करना पड़ता, इसलिए O(1) होता है। शुरुआत में डालने के लिए सभी n तत्वों को एक स्थान दाईं ओर शिफ्ट करना पड़ता है, इसलिए O(n) होता है।

  7. Write a short algorithm to merge two sorted arrays into a single sorted array. / दो सॉर्ट किए हुए एरे को एक सॉर्टेड एरे में मिलाने (merge) के लिए संक्षिप्त एल्गोरिथ्म लिखिए।
    Show answer

    English answer: Use two pointers i=0, j=0 and k=0 for result. While i< n1 and j< n2 compare A[i] and B[j], assign smaller to C[k] and increment corresponding pointer and k. After loop copy remaining elements from A or B. / हिंदी उत्तर: दो सूचक i=0, j=0 और परिणाम के लिए k=0 रखें। जब तक i<n1 और j<n2, A[i] और B[j] की तुलना कर छोटे को C[k] में रखें और उसके सूचक व k बढ़ाएँ। लूप के बाद शेष तत्व A या B से कॉपी कर दें।

  8. Find the sum and average of elements in array arr of size n. / आकार n के एरे arr के तत्वों का योग और औसत निकालिए।
    Show answer

    English answer: Initialise sum=0; for i from 0 to n-1 do sum += arr[i]; average = sum/n (ensure n>0). / हिंदी उत्तर: sum=0 से आरंभ करें; i = 0 से n-1 तक sum += arr[i] करते जाएँ; average = sum/n (सुनिश्चित करें कि n>0)।

  9. Give an example where binary search is not applicable and explain why. / ऐसा एक उदाहरण दीजिए जहाँ बायनरी सर्च लागू नहीं हो सकता और कारण समझाइए।
    Show answer

    English answer: Searching for 7 in unsorted [3,9,1,7] cannot reliably use binary search because the array is not sorted; binary search assumes order to eliminate halves. / हिंदी उत्तर: असॉर्टेड [3,9,1,7] में 7 खोजने के लिए बायनरी सर्च मान्य नहीं है क्योंकि एरे सॉर्टेड नहीं है; बायनरी सर्च आधे हिस्से छोड़ने के लिए क्रम पर निर्भर करता है।

Related Laws & Principles

Explore all

Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer.

Loading related laws…
Sourced from 0 content files · LLOS Learn · browse all chapters