Simple Array Sum in C Programming
ADVERTISEMENTS
Simple array sum in c programming.
In this article, you will learn how to make a simple array sum in c programming.
Example
array = [2, 3, 4]
sum = 2 + 3 + 4
It will return sum = 9
You should have knowledge of the following topics in c programming to understand this program:
- C
main()
function - C
printf()
function - C
while
loop - C
for
loop
Source Code
// Simple Array Sum in C Programming
#include <stdio.h>
int main() {
int s;
printf("Enter size of the array:!\n");
scanf("%d", &s);
int arr[s], i = 0, sum = 0;
printf("\nEnter the elements of the array:\n");
while (i < s) {
scanf("%d", &arr[i]);
sum += arr[i];
i++;
}
printf("\nSum = %d", sum);
return 0;
}
Output
Enter size of the array:!
6
Enter the elements of the array:
1 2 3 4 10 11
Sum = 31
Explanation
In this given program, we have taken the size of the array 6
from the console input and then entered the 6 elements one by one 1, 2, 3, 4, 10, 11
. Then we make iteration over on these elements and every element is added with the sum variable.
Then sum variable return the 31
output of the final program.
Simple Array Sum in C using For loop
// Simple Array Sum in C using For loop
#include <stdio.h>
int main() {
int s;
printf("Enter size of the array:!\n");
scanf("%d", &s);
int arr[s], sum = 0;
printf("\nEnter the elements of the array:\n");
for (int i=0; i<s; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("\nSum = %d", sum);
return 0;
}