-->

C Programming Day 6: Arrays in C with Examples | Complete Guide

C Programming - Day 6



    Introduction

    Welcome to Day 6 of the C Programming Full Course.

    In Day 5, we learned about Loops in C, including for, while, and do-while. Loops allow us to repeat instructions efficiently.

    Now imagine you need to store the marks of 100 students.

    Without arrays, you might have to create:

    int mark1;
    int mark2;
    int mark3;
    int mark4;

    and continue until mark100.

    That would make the program difficult to write and maintain.

    Instead, C provides arrays.

    An array allows you to store multiple values of the same data type under one variable name.

    For example:

    int marks[100];

    This single declaration can store 100 integer values.

    In this lesson, you'll learn how arrays work, how to declare and initialize them, how to access array elements, and how to use loops to process array data.


    What is an Array in C?

    An array is a collection of elements of the same data type stored under a single variable name.

    For example:

    int numbers[5];

    This creates an integer array capable of storing five values.

    Conceptually:

    numbers
    
    Index:     0    1    2    3    4
               ↓    ↓    ↓    ↓    ↓
    Value:    10   20   30   40   50

    Each element has an index.

    The first element starts at index 0.

    Why Do We Need Arrays?

    Suppose you want to store five numbers.

    Without an array:

    int n1 = 10;
    int n2 = 20;
    int n3 = 30;
    int n4 = 40;
    int n5 = 50;

    With an array:

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

    The array approach is shorter and much easier to process with loops.

    For example:

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


    Features of Arrays in C

    Important characteristics of arrays include:

    • Multiple values can be stored under one variable name.
    • All elements have the same data type.
    • Array indexing starts at 0.
    • Elements are stored sequentially in memory.
    • Arrays can be processed efficiently using loops.
    • C supports one-dimensional and multidimensional arrays.


    Array Declaration

    The basic syntax is:

    data_type array_name[size];

    Example:

    int numbers[10];

    Other examples:

    float prices[20];
    
    char names[50];
    
    double measurements[100];


    Understanding Array Indexing

    Consider:

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

    The indexes are:

    Value:     10    20    30    40    50
               ↓     ↓     ↓     ↓     ↓
    Index:     0     1     2     3     4

    Therefore:

    numbers[0]

    returns 10.

    numbers[2]

    returns 30.

    numbers[4]

    returns 50.

    The last valid index is always:

    size - 1

    For an array of size 5, the last index is 4.


    Array Initialization

    There are several ways to initialize arrays.

    Method 1: Initialize During Declaration

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

    Method 2: Let C Determine the Size

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

    C determines the array size from the number of initializers.

    Method 3: Partial Initialization

    int numbers[5] = {10, 20};

    The remaining elements are initialized to zero.

    Conceptually:

    10 20 0 0 0


    Accessing Array Elements

    You can access an element using its index.

    #include <stdio.h>
    
    int main()
    {
        int numbers[5] = {10, 20, 30, 40, 50};
    
        printf("%d\n", numbers[0]);
        printf("%d\n", numbers[1]);
        printf("%d\n", numbers[4]);
    
        return 0;
    }

    Output:

    10
    20
    50

    Modifying Array Elements

    Array elements can be changed individually.

    #include <stdio.h>
    
    int main()
    {
        int numbers[5] = {10, 20, 30, 40, 50};
    
        numbers[2] = 100;
    
        printf("%d", numbers[2]);
    
        return 0;
    }

    Output:

    100

    The original value 30 has been replaced by 100.


    Taking Array Input from the User

    Loops make array input much easier.

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
    
        printf("Enter 5 numbers:\n");
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
        }
    
        return 0;
    }


    Displaying Array Elements

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
        }
    
        printf("Array elements:\n");
    
        for(i = 0; i < 5; i++)
        {
            printf("%d ", numbers[i]);
        }
    
        return 0;
    }

    Example output:

    Enter 5 numbers:
    10
    20
    30
    40
    50
    
    Array elements:
    10 20 30 40 50


    One-Dimensional Array in C

    A one-dimensional array, or 1D array, stores elements in a single sequence.

    Example:

    int marks[5];

    Visual representation:

    marks[0]  marks[1]  marks[2]  marks[3]  marks[4]
       ↓         ↓         ↓         ↓         ↓
      80        75        90        65        88

    1D arrays are commonly used for:

    • Student marks
    • Product prices
    • Employee salaries
    • Temperatures
    • Test scores
    • Lists of numbers

    Program 1: Sum of Array Elements

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
        int sum = 0;
    
        printf("Enter 5 numbers:\n");
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
            sum += numbers[i];
        }
    
        printf("Sum = %d", sum);
    
        return 0;
    }

    Program 2: Average of Array Elements

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
        int sum = 0;
        float average;
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
            sum += numbers[i];
        }
    
        average = (float)sum / 5;
    
        printf("Average = %.2f", average);
    
        return 0;
    }

    Program 3: Find the Largest Element

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
        int largest;
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
        }
    
        largest = numbers[0];
    
        for(i = 1; i < 5; i++)
        {
            if(numbers[i] > largest)
            {
                largest = numbers[i];
            }
        }
    
        printf("Largest = %d", largest);
    
        return 0;
    }

    Program 4: Find the Smallest Element

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i;
        int smallest;
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
        }
    
        smallest = numbers[0];
    
        for(i = 1; i < 5; i++)
        {
            if(numbers[i] < smallest)
            {
                smallest = numbers[i];
            }
        }
    
        printf("Smallest = %d", smallest);
    
        return 0;
    }


    Searching in an Array

    Searching means finding whether a particular value exists in an array.

    One simple method is linear search.

    Linear Search Example

    #include <stdio.h>
    
    int main()
    {
        int numbers[5] = {10, 20, 30, 40, 50};
        int search;
        int i;
        int found = 0;
    
        printf("Enter number to search: ");
        scanf("%d", &search);
    
        for(i = 0; i < 5; i++)
        {
            if(numbers[i] == search)
            {
                found = 1;
                break;
            }
        }
    
        if(found)
            printf("Number found.");
        else
            printf("Number not found.");
    
        return 0;
    }

    The program checks each element until it finds the requested value.


    Sorting an Array

    Sorting means arranging elements in a particular order.

    For example:

    Before:
    50 20 40 10 30
    
    After ascending sort:
    10 20 30 40 50

    A simple beginner-friendly technique is bubble sort.

    Bubble Sort Example

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
        int i, j, temp;
    
        printf("Enter 5 numbers:\n");
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &numbers[i]);
        }
    
        for(i = 0; i < 5 - 1; i++)
        {
            for(j = 0; j < 5 - i - 1; j++)
            {
                if(numbers[j] > numbers[j + 1])
                {
                    temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
    
        printf("Sorted array:\n");
    
        for(i = 0; i < 5; i++)
        {
            printf("%d ", numbers[i]);
        }
    
        return 0;
    }


    Two-Dimensional Arrays in C

    A two-dimensional array, or 2D array, stores data in rows and columns.

    It is particularly useful for representing tables and matrices.

    Syntax:

    data_type array_name[rows][columns];

    Example:

    int matrix[3][3];

    Conceptually:

            Column
           0   1   2
    
    Row 0  1   2   3
    Row 1  4   5   6
    Row 2  7   8   9

    You can access an element using:

    matrix[0][0]
    matrix[1][2]
    matrix[2][1]

    Initializing a 2D Array

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

    The structure is:

    1  2  3
    4  5  6

    Program 5: Display a 2D Array

    #include <stdio.h>
    
    int main()
    {
        int matrix[2][3] =
        {
            {1, 2, 3},
            {4, 5, 6}
        };
    
        int i, j;
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 3; j++)
            {
                printf("%d ", matrix[i][j]);
            }
    
            printf("\n");
        }
    
        return 0;
    }

    Output:

    1 2 3
    4 5 6

    This is where the nested loops from Day 5 become especially useful.

    Program 6: Matrix Input

    #include <stdio.h>
    
    int main()
    {
        int matrix[2][2];
        int i, j;
    
        printf("Enter matrix elements:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                scanf("%d", &matrix[i][j]);
            }
        }
    
        printf("Matrix:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                printf("%d ", matrix[i][j]);
            }
    
            printf("\n");
        }
    
        return 0;
    }

    Program 7: Matrix Addition

    Two matrices can be added when they have compatible dimensions.

    #include <stdio.h>
    
    int main()
    {
        int a[2][2];
        int b[2][2];
        int sum[2][2];
        int i, j;
    
        printf("Enter first matrix:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                scanf("%d", &a[i][j]);
            }
        }
    
        printf("Enter second matrix:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                scanf("%d", &b[i][j]);
            }
        }
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                sum[i][j] = a[i][j] + b[i][j];
            }
        }
    
        printf("Result:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 2; j++)
            {
                printf("%d ", sum[i][j]);
            }
    
            printf("\n");
        }
    
        return 0;
    }


    Character Arrays

    C does not have a separate built-in string data type. Strings are commonly represented using arrays of characters.

    Example:

    char name[20] = "Zareen";

    Conceptually:

    Z  a  r  e  e  n  \0

    The \0 character marks the end of a C string.

    We will study strings in much greater detail in a later lesson.


    Real-World Applications of Arrays

    Arrays are used extensively in real software applications.

    Student Management

    Student marks
    ↓
    Array
    ↓
    Calculate total
    ↓
    Calculate average
    ↓
    Determine grade

    E-Commerce

    Arrays can store:

    • Product prices
    • Product IDs
    • Quantities
    • Ratings

    Banking

    Arrays can be used to process:

    • Transaction amounts
    • Account-related data
    • Payment records

    Games

    Arrays can represent:

    • Player scores
    • Game boards
    • Inventory items
    • Levels

    Data Processing

    Arrays are fundamental for processing collections of numerical or structured data.


    Common Array Mistakes

    Mistake 1: Using an Invalid Index

    For:

    int numbers[5];

    valid indexes are:

    0
    1
    2
    3
    4

    This is invalid:

    numbers[5]

    Accessing outside the valid range can result in undefined behavior.

    Mistake 2: Forgetting That Indexing Starts at Zero

    Incorrect assumption:

    First element = index 1

    Correct:

    First element = index 0

    Mistake 3: Using the Wrong Loop Condition

    For an array of five elements:

    for(i = 0; i < 5; i++)

    is correct.

    This is incorrect:

    for(i = 0; i <= 5; i++)

    because it attempts to access index 5.

    Mistake 4: Mixing Data Types

    An integer array should contain integer values:

    int numbers[5];

    Use an appropriate array type for floating-point or character data.


    Array Size and Memory

    When you declare:

    int numbers[5];

    C reserves enough memory for five int elements.

    The exact number of bytes depends on the implementation's size of int.

    You can inspect the size using sizeof:

    #include <stdio.h>
    
    int main()
    {
        int numbers[5];
    
        printf("Array size = %zu bytes",
               sizeof(numbers));
    
        return 0;
    }

    For a local array, sizeof(numbers) gives the total size of the entire array in bytes.


    Best Practices for Arrays

    1. Use meaningful names

    Prefer:

    int studentMarks[50];

    over:

    int x[50];

    when the purpose is student marks.

    2. Keep indexes within bounds

    Always ensure your index stays between:

    0

    and:

    size - 1

    3. Use loops for repetitive operations

    Loops make array processing much more efficient.

    4. Initialize arrays when appropriate

    Initialization reduces the risk of using unintended values.

    5. Validate user input

    When accepting array sizes or values from users, validate the input where appropriate.


    Arrays and Loops: The Most Important Combination

    Arrays become especially powerful when combined with loops.

    Example:

    int numbers[5] = {10, 20, 30, 40, 50};
    
    for(int i = 0; i < 5; i++)
    {
        printf("%d ", numbers[i]);
    }

    Remember:

    Array = stores multiple values
    Loop = processes multiple values efficiently

    Together, they form the foundation for many data-processing programs.


    Interview Questions on Arrays in C

    1. What is an array in C?

    An array is a collection of elements of the same data type stored under one variable name.

    2. What is the first index of an array?

    The first index is 0.

    3. What is the last index of an array of size 10?

    The last valid index is 9.

    4. Can an array store different data types?

    A normal C array stores elements of the same declared data type.

    5. What is a 2D array?

    A two-dimensional array stores data in rows and columns.

    6. Why are loops commonly used with arrays?

    Loops allow programs to process multiple array elements efficiently.

    7. What happens if an array is accessed outside its bounds?

    The behavior is undefined. It can lead to incorrect results or other program problems.

    8. What is a character array?

    A character array is an array of char values. Character arrays are commonly used to represent strings in C.


    Practice Problems

    Beginner

    1. Declare an integer array of 10 elements.
    2. Store five numbers in an array and display them.
    3. Find the sum of all elements.
    4. Calculate the average of an array.
    5. Find the largest element.
    6. Find the smallest element.
    7. Count even and odd numbers.
    8. Count positive and negative numbers.

    Intermediate

    1. Search for an element using linear search.
    2. Reverse an array.
    3. Copy one array into another.
    4. Sort an array in ascending order.
    5. Sort an array in descending order.
    6. Find the second-largest element.
    7. Remove duplicate values.
    8. Count the frequency of each element.

    Advanced

    1. Add two matrices.
    2. Subtract two matrices.
    3. Multiply two matrices.
    4. Find the transpose of a matrix.
    5. Calculate the sum of each matrix row.
    6. Calculate the sum of each matrix column.
    7. Search for an element in a matrix.
    8. Build a simple student marks management program using arrays.

    Summary

    In C Programming Day 6, you learned about one of the most important data structures in C: arrays.

    You learned:

    • What an array is
    • Why arrays are useful
    • Array declaration
    • Array initialization
    • Array indexing
    • Accessing and modifying elements
    • Taking array input
    • Displaying array elements
    • One-dimensional arrays
    • Two-dimensional arrays
    • Searching
    • Sorting
    • Matrix operations
    • Character arrays
    • Array and loop integration
    • Common mistakes and best practices

    The combination of arrays and loops is extremely important. Once you understand these concepts, you'll be able to solve many more practical programming problems.

    In Day 7, we'll move into Strings in C, including character arrays, string input/output, string functions, and practical string-processing programs.

    Frequently Asked Questions (FAQ)

    What is an array in C?
    An array is a collection of elements of the same data type stored under a single variable name.
    Why does C array indexing start at 0?
    C uses zero-based indexing, so the first element is accessed with index 0.
    What is a 1D array?
    A 1D array stores elements in a single sequence. Example: int numbers[5];
    What is a 2D array?
    A 2D array stores data in rows and columns. Example: int matrix[3][3];
    Can arrays store strings?
    Character arrays are commonly used to store strings in C. char name[20] = "Jahid";
    Can an array size be changed after declaration?
    A normal fixed-size array's size cannot simply be changed after it has been declared. Dynamic memory allocation, which will be covered later, provides another way to manage resizable memory.
    Why are arrays important in programming?
    Arrays provide an efficient way to organize and process collections of related values.

    0/Post a Comment/Comments

    Thank You For Visit My Website.
    I Will Contact As Soon As Possible.