Addition of Array Elements


Explanation

An array can be used to store multiple values of the same data type. In this program, the user enters 5 numbers into an integer array. A second for loop is then used to calculate the sum of all array elements. Finally, the program displays the total of the entered numbers.

How It Works?

  • Step 1: Declare an integer array r[5] and the variables k and total.
  • Step 2: Initialize total with 0.
  • Step 3: Use the first for loop to accept five numbers from the user and store them in the array.
  • Step 4: Use the second for loop to access each array element.
  • Step 5: Add each array element to total.
  • Step 6: After the loop finishes, display the total of all array elements.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int r[5], k, total = 0;

    clrscr();

    for(k = 0; k <= 4; k++)
    {

        printf("Enter the Number : ");

        scanf("%d", &r[k]);

    }

    for(k = 0; k <= 4; k++)
    {

        total = total + r[k];

    }

    printf("\nTotal = %d", total);

    getch();

}

Output

Enter the Number : 10
Enter the Number : 20
Enter the Number : 15
Enter the Number : 25
Enter the Number : 30

Total = 100

Practice Exercises

Task 1: Write a C program to accept 6 numbers into an array and calculate the sum of all array elements using a for loop.

Goal: Learn how to store values in an array and use a for loop to calculate the total of all array elements.

💡 Hint: Declare an array of size 6 and a variable total initialized to 0. Use the first for loop to accept the numbers and the second for loop to add each array element to total.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int r[6], k, total = 0;

    clrscr();

    for(k = 0; k <= 5; k++)
    {

        printf("Enter the Number : ");

        scanf("%d", &r[k]);

    }

    for(k = 0; k <= 5; k++)
    {

        total = total + r[k];

    }

    printf("\nTotal = %d", total);

    getch();

}

Output
Enter the Number : 5
Enter the Number : 10
Enter the Number : 15
Enter the Number : 20
Enter the Number : 25
Enter the Number : 30

Total = 105
Explanation: The program declares an integer array of size 6. The first for loop accepts six numbers from the user and stores them in the array. The second for loop accesses each element and adds it to the variable total. After all elements have been processed, the program displays the sum of the array elements.