SrcForge

Lesson 13

Arrays - Part 2

This guide builds practical skills with arrays through progressively challenging code examples, from storing and printing elements to finding the largest value, calculating averages, and reversing arrays, followed by common mistakes and tips to avoid them.

C Track

Save progress as you learn.

44 lessons

Lesson content

Arrays in C Programming: A Complete Beginner to Advanced Guide (Part 2)

In this part, we'll build practical skills with Arrays in C Programming through progressively challenging examples. Every line of code includes a comment so you can understand exactly what each statement does.

Code Examples

Example 1: Beginner – Store and Print Array Elements

This example demonstrates how to declare, initialize, and print the elements of an array.

#include <stdio.h>                     // Includes the standard input/output library

int main()                             // Program execution starts here
{
    int numbers[5] = {10, 20, 30, 40, 50}; // Declare and initialize an array

    for (int i = 0; i < 5; i++)        // Loop through all array elements
    {
        printf("%d ", numbers[i]);     // Print the current array element
    }

    printf("\n");                      // Print a newline

    return 0;                          // Indicate successful program execution
}

Output: 10 20 30 40 50

Explanation

  • An array named numbers stores five integers.
  • The for loop starts from index 0.
  • Each iteration prints one element until the last index (4) is reached.

Example 2: Intermediate – Read Values from the User

This example shows how to take input from the user and store it in an array.

#include <stdio.h>                              // Standard input/output library

int main()                                      // Main function
{
    int marks[5];                               // Declare an array for 5 marks

    printf("Enter 5 marks:\n");                 // Ask the user for input

    for (int i = 0; i < 5; i++)                 // Loop to read values
    {
        scanf("%d", &marks[i]);                 // Store each value in the array
    }

    printf("\nEntered Marks:\n");               // Display heading

    for (int i = 0; i < 5; i++)                 // Loop to print values
    {
        printf("%d\n", marks[i]);               // Print each mark
    }

    return 0;                                   // Exit successfully
}

Sample Output: Enter 5 marks: 80 90 75 88 92 / Entered Marks: 80 90 75 88 92

Explanation

  • The first loop stores user input.
  • The second loop displays all stored values.
  • Arrays work well with loops because the index changes automatically.

Example 3: Intermediate – Find the Largest Element

Finding the maximum value is a common interview and programming task.

#include <stdio.h>                              // Include standard I/O library

int main()                                      // Main function
{
    int numbers[5] = {45, 12, 98, 34, 67};      // Initialize the array

    int largest = numbers[0];                   // Assume the first element is the largest

    for (int i = 1; i < 5; i++)                 // Start checking from the second element
    {
        if (numbers[i] > largest)               // Compare current element
        {
            largest = numbers[i];               // Update largest value
        }
    }

    printf("Largest = %d\n", largest);          // Print the result

    return 0;                                   // Exit program
}

Output: Largest = 98

Explanation

  • Assume the first element is the largest.
  • Compare every remaining element.
  • Update the largest value whenever a bigger number is found.

Example 4: Advanced – Calculate Average of Student Marks

This example combines arrays with arithmetic operations.

#include <stdio.h>                              // Include standard I/O library

int main()                                      // Main function
{
    int marks[5] = {80, 85, 90, 75, 95};        // Student marks

    int sum = 0;                                // Variable to store total

    float average;                              // Variable to store average

    for (int i = 0; i < 5; i++)                 // Traverse the array
    {
        sum += marks[i];                        // Add current mark to total
    }

    average = (float)sum / 5;                   // Calculate average

    printf("Total = %d\n", sum);                // Display total

    printf("Average = %.2f\n", average);        // Display average

    return 0;                                   // Exit successfully
}

Output: Total = 425 / Average = 85.00

Explanation

  • The loop computes the total marks.
  • The total is divided by the number of students.
  • (float) ensures floating-point division.

Example 5: Advanced – Reverse an Array

Reversing an array is a classic programming problem.

#include <stdio.h>                               // Include standard I/O library

int main()                                       // Main function
{
    int numbers[5] = {1, 2, 3, 4, 5};            // Initialize the array

    printf("Reversed Array:\n");                 // Display heading

    for (int i = 4; i >= 0; i--)                 // Traverse from last element
    {
        printf("%d ", numbers[i]);               // Print elements in reverse order
    }

    printf("\n");                                // Print a newline

    return 0;                                    // Exit successfully
}

Output: Reversed Array: 5 4 3 2 1

Explanation

Instead of moving the elements, this example simply prints them from the last index to the first.

Common Mistakes and Pitfalls

Beginners often make similar mistakes when working with arrays. Understanding these pitfalls will help you write safer and more reliable programs.

1. Accessing an Invalid Index

Wrong:

int numbers[5];

numbers[5] = 100;

Correct:

int numbers[5];

numbers[4] = 100;
WrongCorrect
Uses index 5Uses index 4 (last valid index)
Causes undefined behaviorSafe and valid

2. Forgetting That Index Starts at Zero

Wrong (expecting the first element):

printf("%d", numbers[1]);

Correct:

printf("%d", numbers[0]);
WrongCorrect
Assumes first index is 1First index is always 0

3. Declaring an Array That Is Too Small

Wrong:

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

Correct:

int marks[4] = {10, 20, 30, 40};
WrongCorrect
Too many initializersArray size matches initializer count

4. Using an Uninitialized Array

Wrong:

int numbers[5];

printf("%d", numbers[0]);

Correct:

int numbers[5] = {0};

printf("%d", numbers[0]);
WrongCorrect
Reads garbage valuesStarts with known values

5. Hardcoding the Array Size Everywhere

Wrong:

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

If the array size changes, you must update every loop manually.

Better:

int size = sizeof(numbers) / sizeof(numbers[0]);

for (int i = 0; i < size; i++)

This automatically calculates the number of elements in the array.

Tips to Avoid Mistakes

  • Always remember that array indexing starts at 0.
  • Never access elements beyond the last valid index.
  • Initialize arrays before using them.
  • Use loops to process arrays instead of writing repetitive code.
  • Calculate the array size using sizeof() when possible to make your code easier to maintain.