Sum of Array Elements in C. In the world of programming especially for beginers, understanding how to manipulate arrays and perform operations on their elements is foundational. Among these operations calcualting the sum of all these elements within an array standout as a crucial task.
Table of Contents
Problem Statement: WAP that simply takes elements of the array from the user and finds of the sum of these elements.
How to Calculate Sum of Array Elements
To solve the problem as mentioned above-
- First, we are going to take elements of array input from the user.
- Will declare a variable sum.
- Iterate through the array and add all elements with the variable sum.
- Print the sum.
C Program for Sum of Array Element
#include <stdio.h>
void main()
{
int n;
printf("Enter the number of elements in array ");
scanf("%d", &n);
int array[n], sum;
// Taking input for the array
printf("Enter the elements of the first array \n");
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
// Adding elements
for (int i = 0; i < n; i++)
{
sum += array[i];
}
// Printing the sum of corresponding array
printf("Sum of Arrays elements = %d\n", sum);
}
Output
In the above C program –
- Program ask user to enter the number of elements in the array.
- Takes input for elemnt from the array for user.
- Calculated the sum by using the a loop.
- At the end print the result.
Happy Coding & Learning
2 thoughts on “Sum of Array Elements in C”