How to write a C Program to find the Sum of all Elements in an Array using For Loop, While Loop, Functions with example.
C Program to find Sum of all Elements in an Array using for loop
This C program allows the user to enter the Size and number of rows for One Dimensional Array. Next, we are using the For Loop to iterate the elements and perform addition.
#include<stdio.h> int main() { int Size, i, a[10]; int Addition = 0; // You have specify the array size printf("\n Please Enter the Size\n"); scanf("%d", &Size); printf("\nPlease Enter the Elements\n"); //Start at 0, it will save user enter values into array a for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } // Loop Over, and add every item to Addition for(i = 0; i < Size; i ++) { Addition = Addition + a[i]; } printf("Sum = %d ", Addition); return 0; }
The sum of array items using a for loop output
Please Enter the Size
4
Please Enter the Elements
10
20
30
40
Sum = 100
We already explained the program flow in Perform Arithmetic Operations on One Dimensional article. So, I suggest you refer to the same in C Programming for better understanding.
C Program to find the Sum of all Elements in an Array using While Loop
This program is the same as above, but this time we used While Loop to perform the One Dimensional Array addition.
#include<stdio.h> int main() { int i, Size, a[10]; int j = 0, Addition = 0; printf("Please Enter the Size of an Array: "); scanf("%d", &Size); printf("\nPlease Enter Array Elements\n"); for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } while(j < Size ) { Addition = Addition + a[j]; j++; } printf("Sum of All Elements in an Array = %d ", Addition); return 0; }
Please Enter the Size of an Array: 7
Please Enter Array Elements
10
20
30
40
50
60
90
Sum of All Elements in an Array = 300
C Program to find the Sum of all Elements in an Array using Functions
This example is the same as the first example, but this time we used Functions to perform addition
#include<stdio.h> int SumofNumbers(int a[], int Size); int main() { int i, Size, a[10]; int Addition; printf("Please Enter the Size of an Array: "); scanf("%d", &Size); printf("\nPlease Enter Array Elements\n"); for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } Addition = SumofNumbers(a, Size); printf("Sum of All Elements in an Array = %d ", Addition); return 0; } int SumofNumbers(int a[], int Size) { int Addition = 0; int i; for(i = 0; i < Size; i++) { Addition = Addition + a[i]; } return Addition; }