Program to calculate sum of array in C
This program should give an insight of how to parse (read) array. We shall use a loop and sum up all values of the array.
Algorithm
Let's first see what should be the step-by-step procedure of this program −
START Step 1 → Take an array A and define its values Step 2 → Loop for each value of A Step 3 → Add each element to 'sum' variable Step 4 → After the loop finishes, display 'sum' STOP
Pseudocode
Let's now see the pseudocode of this algorithm −
procedure sum_array(A)
Declare sum as integer
FOR EACH value in A DO
sum ← sum + A[n]
END FOR
Display sum
end procedure
Implementation
This pseudocode can now be implemented in the C program as follows −
#include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int sum, loop;
sum = 0;
for(loop = 9; loop >= 0; loop--) {
sum = sum + array[loop];
}
printf("Sum of array is %d.", sum);
return 0;
}
The output should look like this −
Sum of array is 45.
array_examples_in_c.htm
Advertisements