๐Ÿ“Š 10. Arrays

10.1 What Is an Array?

An array is a fixed-size collection of elements of the same data type, stored in consecutive memory locations and accessed using one array name plus an index.

Array
  โ”‚
  โ”œโ”€โ”€ One name
  โ”œโ”€โ”€ Same data type
  โ”œโ”€โ”€ Multiple elements
  โ”œโ”€โ”€ Consecutive memory locations
  โ””โ”€โ”€ Index starts at 0
Core idea: An array lets us represent many related values with one name and process them efficiently with loops.

10.2 Why Do We Need Arrays?

Suppose a program must store 100 marks. Creating mark1, mark2, ..., mark100 makes the program difficult to write and maintain. An array gives us one organized collection.

int marks[100];
  • One variable name represents many values.
  • Loops can process all elements systematically.
  • Searching, sorting, counting and aggregation become natural.
  • Arrays are the foundation for strings, matrices and many data structures.

10.3 Array Index โ€” The Most Important Rule

C uses zero-based indexing. For an array containing n elements, valid indexes are 0 through n - 1.

int marks[5];

Index:    0     1     2     3     4
          โ†“     โ†“     โ†“     โ†“     โ†“
Value:   80    75    90    65    88

First index = 0
Last index  = 5 - 1 = 4
Common confusion: marks[5] declares five elements, but marks[5] is not a valid element access. The valid last element is marks[4].

10.4 Array Declaration

The basic declaration form is:

data_type array_name[size];

Example:

int marks[5];
float prices[10];
char letters[26];

The size tells the compiler how many elements the array can contain.

10.5 Array Initialization

An array can be initialized when it is declared.

int marks[5] = {80, 75, 90, 65, 88};
Index 0
80
Index 1
75
Index 2
90
Index 3
65
Index 4
88

10.6 Size Can Be Inferred During Initialization

When an initializer is provided, C can determine the number of elements if the size is omitted.

int numbers[] = {10, 20, 30, 40};

Here the array contains four elements. A useful way to obtain the element count in the same scope is:

size_t n = sizeof numbers / sizeof numbers[0];
Important: This sizeof technique works for an actual array in the scope where it exists. It does not generally give the element count after the array has decayed to a pointer in a function parameter.

10.7 Partial Initialization

If fewer initializers are supplied than the array size, the remaining elements are initialized to zero.

int a[5] = {10, 20};
Index:   0    1    2    3    4
Value:  10   20    0    0    0

10.8 Accessing an Array Element

Use the subscript operator [] to access one element.

int marks[3] = {70, 80, 90};

printf("%d", marks[1]);   // 80

The expression marks[1] refers to the element at index 1.

10.9 Modifying an Array Element

Array elements behave like individual variables and can be assigned new values.

marks[1] = 85;

Only the element at index 1 changes; the other elements remain unchanged.

10.10 Reading Array Elements

Loops are normally used to read many elements.

int a[5];

for (int i = 0; i < 5; i++)
{
    scanf("%d", &a[i]);
}
Why a loop? The index changes from 0 to 4, so one statement pattern can handle every element.

10.11 Printing Array Elements

for (int i = 0; i < 5; i++)
{
    printf("%d ", a[i]);
}

The same traversal pattern can be used for reading, printing, updating, counting and searching.

10.12 Array Traversal

Traversal means visiting array elements one by one, usually from the first index to the last.

i = 0
  โ†“
process a[0]
  โ†“
i = 1
  โ†“
process a[1]
  โ†“
...
  โ†“
i = n - 1
  โ†“
process a[n - 1]
  โ†“
stop

The standard pattern is:

for (int i = 0; i < n; i++)
{
    // process a[i]
}

10.13 Sum of Array Elements

Use an accumulator that starts at zero.

int sum = 0;

for (int i = 0; i < n; i++)
{
    sum += a[i];
}
Pattern: sum = sum + current_element

10.14 Average of Array Elements

First calculate the sum, then divide by the number of elements. Use floating-point division when a fractional result is required.

double average = (double)sum / n;
Placement point: sum / n performs integer division if both operands are integers. Casting one operand to double preserves the fractional part.

10.15 Finding the Maximum Element

A safe general approach is to initialize the maximum from the first element rather than assuming zero.

int max = a[0];

for (int i = 1; i < n; i++)
{
    if (a[i] > max)
        max = a[i];
}
Why not max = 0? An array such as {-8, -3, -10} has a maximum of -3, not zero.

10.16 Finding the Minimum Element

int min = a[0];

for (int i = 1; i < n; i++)
{
    if (a[i] < min)
        min = a[i];
}

The same scan pattern works for both maximum and minimum; only the comparison changes.

10.17 Counting Even and Odd Elements

int even = 0, odd = 0;

for (int i = 0; i < n; i++)
{
    if (a[i] % 2 == 0)
        even++;
    else
        odd++;
}

This is a useful example of combining arrays, traversal and decision making.

10.18 Searching an Array

Searching means checking whether a required value occurs in the array.

int key = 30;
int found = 0;

for (int i = 0; i < n; i++)
{
    if (a[i] == key)
    {
        found = 1;
        break;
    }
}

For an unsorted array, a simple scan is called linear search.

10.19 Linear Search

key = 25

a[0] == 25 ? โ†’ No
a[1] == 25 ? โ†’ No
a[2] == 25 ? โ†’ Yes
                   โ†“
                Found at index 2

Worst-case time complexity is O(n), because the algorithm may inspect every element.

10.20 Finding the Position of an Element

Because C arrays use indexes, the position can be represented directly by the index.

int position = -1;

for (int i = 0; i < n; i++)
{
    if (a[i] == key)
    {
        position = i;
        break;
    }
}
Convention: Using -1 for โ€œnot foundโ€ is useful because valid array indexes are non-negative.

10.21 Reversing an Array

One simple method is to use two indexes: one from the beginning and one from the end.

int left = 0, right = n - 1;

while (left < right)
{
    int temp = a[left];
    a[left] = a[right];
    a[right] = temp;

    left++;
    right--;
}
Before:  10  20  30  40  50
          โ†‘               โ†‘
        left            right

After:   50  40  30  20  10

10.22 Copying One Array to Another

Arrays cannot be copied with a simple assignment such as b = a;. Copy the elements individually.

for (int i = 0; i < n; i++)
{
    b[i] = a[i];
}
Important: b = a; is not a valid way to copy ordinary C arrays. This is different from copying a scalar variable.

10.23 Counting Positive, Negative and Zero

int positive = 0, negative = 0, zero = 0;

for (int i = 0; i < n; i++)
{
    if (a[i] > 0)
        positive++;
    else if (a[i] < 0)
        negative++;
    else
        zero++;
}

10.24 Second Largest Element โ€” Think About the Requirement

โ€œSecond largestโ€ can mean second distinct largest or simply the second value after sorting. These are different requirements.

For the distinct version, a robust algorithm must track whether a valid second value has actually been found. Do not blindly initialize the second-largest value to zero.

Placement lesson: Before coding an array problem, clarify whether duplicates count, whether the input can be empty, and whether the result is guaranteed to exist.

10.25 Finding Duplicate Elements

A straightforward beginner approach compares each element with later elements.

for (int i = 0; i < n; i++)
{
    for (int j = i + 1; j < n; j++)
    {
        if (a[i] == a[j])
        {
            printf("%d ", a[i]);
        }
    }
}

This nested-loop approach is easy to understand but can take O(nยฒ) time.

10.26 Finding Unique Elements

One common meaning of โ€œuniqueโ€ is a value that appears exactly once. That requires counting occurrences rather than merely checking whether a value differs from its neighbor.

for (int i = 0; i < n; i++)
{
    int count = 0;

    for (int j = 0; j < n; j++)
    {
        if (a[i] == a[j])
            count++;
    }

    if (count == 1)
        printf("%d ", a[i]);
}

10.27 Frequency of an Element

Frequency means the number of times a particular value occurs.

int key = 5;
int count = 0;

for (int i = 0; i < n; i++)
{
    if (a[i] == key)
        count++;
}
Frequency(key) = number of indexes i for which a[i] == key

10.28 Finding Largest and Smallest Together

Maximum and minimum can be found in one traversal, so the array does not need to be scanned twice.

int min = a[0];
int max = a[0];

for (int i = 1; i < n; i++)
{
    if (a[i] < min) min = a[i];
    if (a[i] > max) max = a[i];
}

This remains O(n) time and uses constant extra space.

10.29 Swapping Two Array Elements

To exchange two values, use a temporary variable.

int temp = a[i];
a[i] = a[j];
a[j] = temp;

This small pattern appears repeatedly in reversing and sorting algorithms.

10.30 In-Place Array Operations

An in-place operation modifies the original array instead of creating another array of the same size. Reversal using two pointers is an example.

In-place
Usually O(1) extra array storage
Copy-based
Uses additional storage

10.31 Introduction to Sorting

Sorting means arranging values in a chosen order, such as ascending or descending order.

Before:  40  10  30  20
After:   10  20  30  40

Sorting is important because many later algorithms become easier after data is ordered.

10.32 Bubble Sort

Bubble sort repeatedly compares adjacent elements and swaps them when they are in the wrong order.

40  10  30  20
โ”‚   โ”‚
compare โ†’ swap
โ†“
10  40  30  20
    โ”‚   โ”‚
    compare โ†’ swap
โ†“
10  30  40  20
        โ”‚   โ”‚
        compare โ†’ swap
โ†“
10  30  20  40

Largest value has moved toward the end.
for (int pass = 0; pass < n - 1; pass++)
{
    for (int j = 0; j < n - 1 - pass; j++)
    {
        if (a[j] > a[j + 1])
        {
            int temp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = temp;
        }
    }
}
Complexity: Basic bubble sort is O(nยฒ) in average and worst cases. An optimized version can stop early when a pass makes no swaps.

10.33 One-Dimensional vs Two-Dimensional Arrays

A one-dimensional array represents a sequence. A two-dimensional array can represent rows and columns, such as a matrix or table.

1D:  [10] [20] [30] [40]

2D:
      col 0  col 1  col 2
row 0   1      2      3
row 1   4      5      6

10.34 Declaring a Two-Dimensional Array

int matrix[2][3];

This declares 2 rows and 3 columns, for a total of 6 int elements.

Access uses two indexes:

matrix[0][1] = 25;

The first index selects the row; the second selects the column.

10.35 Initializing and Reading a Matrix

int matrix[2][3] =
{
    {1, 2, 3},
    {4, 5, 6}
};

To read values, use nested loops:

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        scanf("%d", &matrix[i][j]);
    }
}

10.36 Printing a Matrix

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        printf("%d ", matrix[i][j]);
    }

    printf("\n");
}
Think in two dimensions: the outer loop moves through rows; the inner loop moves through columns of the current row.

10.37 Matrix Addition

Two matrices can be added when they have the same dimensions.

C[i][j] = A[i][j] + B[i][j]
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        C[i][j] = A[i][j] + B[i][j];
    }
}

10.38 Main Diagonal Elements

For a square matrix, the main diagonal contains elements where the row and column indexes are equal.

for (int i = 0; i < n; i++)
{
    printf("%d ", matrix[i][i]);
}
1  2  3
4  5  6
7  8  9

Main diagonal:
1  .  .
.  5  .
.  .  9

Condition: row == column

10.39 Row Sum and Column Sum

For a row sum, keep the row fixed and change the column. For a column sum, keep the column fixed and change the row.

// Row sum
for (int i = 0; i < rows; i++)
{
    int sum = 0;

    for (int j = 0; j < cols; j++)
        sum += matrix[i][j];

    printf("%d\n", sum);
}

10.40 Array Problem-Solving Pattern

Most beginner and placement array problems can be organized around a small number of patterns.

Traversal
Visit every element
Accumulator
Sum / product / total
Tracker
Min / max / best value
Counter
Count elements satisfying a condition
Search
Find a value or position
Two pointers
Reverse / pair / partition
Nested loops
Compare pairs or process matrices
Sorting
Arrange values before further processing

10.41 Common Array Mistakes

  • Wrong last index: using a[n] instead of a[n - 1].
  • Out-of-bounds access: accessing an index outside the valid range causes undefined behavior.
  • Wrong loop condition: using i <= n when the array has n elements.
  • Uninitialized local array: local automatic arrays are not automatically filled with zero.
  • Wrong maximum initialization: starting with zero can fail for all-negative arrays.
  • Integer average: forgetting that integer division discards the fractional part.
  • Confusing size with last index: an array of size 5 has indexes 0โ€“4.
  • Assuming arrays can be assigned: copy elements explicitly when copying ordinary arrays.
  • Forgetting matrix dimensions: row and column limits must both be correct.
  • Using an array before knowing its required size: choose a suitable fixed size or later learn dynamic allocation.
CodeBhavya Rule: Whenever you write an array loop, say aloud: start index โ†’ stopping condition โ†’ last valid index. This prevents many off-by-one errors.

10.42 Quick Revision

๐Ÿ“Œ Array โ†’ Collection of same-type elements.

๐Ÿ“Œ Index starts at 0.

๐Ÿ“Œ Last index โ†’ n - 1.

๐Ÿ“Œ Traversal โ†’ Visit every element.

๐Ÿ“Œ Searching โ†’ Find an element.

๐Ÿ“Œ Sorting โ†’ Arrange elements.

๐Ÿ“Œ 2D array โ†’ Rows and columns.

๐Ÿ“Œ Arrays + Loops are fundamental to problem solving.
INTERACTIVE LEARNING

๐ŸŽฌ Arrays โ€” Traversal Visualization

Follow how a loop visits each array element from index 0 to index n - 1.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Arrays

Trace how a loop visits each array element and accumulates the running sum.

10.43 Quick MCQs

Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.

1. What is the index of the first element of a C array?
2. What is the last valid index of an array containing n elements?
3. Which loop is commonly used to traverse an array?
4. Which algorithm checks array elements one by one to find a target?
5. Which array representation is commonly used for rows and columns?
PRACTICE

10.44 ๐ŸŽฏ Practice Problems

Arrays become easy when you combine indexing with loops. Use ๐Ÿ’ป Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.

๐Ÿ“ˆ Arrays Practice Progress
Solved 0 / 20
Completed with Solution 0
Total Score 0 / 2000
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Read and Print N Array Elements

Problem 1: Read N integers into an array and print them in the same order.

Input: N followed by N integers.

Output: Print the array elements separated by spaces.

2. Sum of Array Elements

Problem 2: Read N integers and find their sum.

Input: N followed by N integers.

Output: Print the sum.

3. Average of Array Elements

Problem 3: Read N integers and find their average.

Input: N greater than 0 followed by N integers.

Output: Print the average rounded to two decimal places.

4. Maximum Element

Problem 4: Read N integers and find the maximum element.

Input: N greater than 0 followed by N integers.

Output: Print the maximum element.

5. Minimum Element

Problem 5: Read N integers and find the minimum element.

Input: N greater than 0 followed by N integers.

Output: Print the minimum element.

6. Count Even and Odd Elements

Problem 6: Count the even and odd values in an integer array.

Input: N followed by N integers.

Output: Print the even count and odd count.

7. Count Positive, Negative and Zero

Problem 7: Count positive, negative and zero elements in an integer array.

Input: N followed by N integers.

Output: Print positive, negative and zero counts.

8. Linear Search

Problem 8: Search for a target value using linear search.

Input: N, then N integers, then the target.

Output: Print "Found" if the target exists, otherwise print "Not Found".

9. Position of an Element

Problem 9: Find the first position of a target value in an array.

Input: N, then N integers, then the target.

Output: Print the 1-based position, or -1 if the target is absent.

10. Reverse an Array

Problem 10: Read an array and print its elements in reverse order.

Input: N followed by N integers.

Output: Print the elements from last to first.

11. Copy One Array into Another

Problem 11: Copy all elements of one array into another and print the copied array.

Input: N followed by N integers.

Output: Print the copied elements.

12. Find Duplicate Elements

Problem 12: Print each value that appears more than once, exactly once.

Input: N followed by N integers.

Output: Print duplicate values in first-appearance order, or None if there are no duplicates.

13. Find Unique Elements

Problem 13: Print all values that occur exactly once in the array.

Input: N followed by N integers.

Output: Print unique values in original order, or None if no value is unique.

14. Frequency of a Given Element

Problem 14: Count how many times a target value occurs in an array.

Input: N, then N integers, then the target.

Output: Print the frequency.

15. Second Largest Distinct Element

Problem 15: Find the second largest distinct element in an integer array.

Input: N greater than 1 followed by N integers.

Output: Print the second largest distinct value, or None if it does not exist.

16. Sort Array in Ascending Order

Problem 16: Sort an integer array in ascending order.

Input: N followed by N integers.

Output: Print the sorted array.

17. Sort Array in Descending Order

Problem 17: Sort an integer array in descending order.

Input: N followed by N integers.

Output: Print the sorted array.

18. Sum of Each Matrix Row

Problem 18: Read a matrix and print the sum of every row.

Input: Rows R and columns C followed by R ร— C integers.

Output: Print one row sum per line.

19. Sum of Each Matrix Column

Problem 19: Read a matrix and print the sum of every column.

Input: Rows R and columns C followed by R ร— C integers.

Output: Print the column sums separated by spaces.

20. Main Diagonal of a Square Matrix

Problem 20: Read a square matrix and print its main diagonal elements.

Input: N followed by N ร— N integers.

Output: Print a[0][0], a[1][1], ... separated by spaces.

10.45 Key Takeaway

๐ŸŽฏ Remember the core array pattern:

Array โ†’ Loop โ†’ Process โ†’ Result

Once you understand this pattern, many array problems become much easier.

Arrays are the foundation for:

Searching โ†’ Sorting โ†’ Strings โ†’ Matrices โ†’ Data Structures โ†’ Algorithms
INTERVIEW PREPARATION

๐ŸŽค Arrays โ€” Interview Questions

1. Why do C arrays use zero-based indexing?
2. What happens if you access an array outside its valid index range?
3. What is array traversal?
4. What is the difference between arr[i] and &arr[i]?
5. How is a two-dimensional array typically stored in C?
6. Why is linear search called linear?
7. Why should maximum and minimum usually be initialized from arr[0]?
8. What is the difference between reversing an array while printing and reversing it in place?
PLACEMENT TIPS

๐Ÿ’ก Arrays โ€” Placement Tips

  • Always identify the valid index range first: 0 to n - 1.
  • For maximum/minimum problems, initialize from an actual array element rather than an arbitrary constant.
  • For search questions, decide whether the array is sorted before choosing between linear search and more advanced techniques.
  • For duplicate/frequency questions, carefully separate value, position, and frequency.
  • For matrix questions, track row index i and column index j separately.
  • When using nested loops, estimate the total number of comparisons because this determines time complexity.
EXTRA PRACTICE

โœ๏ธ Arrays โ€” Extra Practice Questions

  1. Move all zero values to the end of an array while preserving the order of non-zero values.
  2. Find the missing number from an array containing values from 1 to N with one value absent.
  3. Find the pair of elements whose sum is closest to a given target.
  4. Rotate an array left by one position and then by K positions.
  5. Find the transpose of a matrix.
  6. Check whether a square matrix is symmetric.
โ† Previous Topic: Loops Next Topic: Strings โ†’