C program to find the sum of array elements
|In this C Programming example, we will discuss the pseudocode and implement the program to find the sum of array elements and print the output on the console.
1. Sum of all elements in the array
To find the sum of array elements we need to iterate through all the values inside the array and keep on adding the current element to the sum and then print the total sum on the console.
Note: We need to take care of the data type if the sum is huge then it will be better if we thought about the data type beforehand.
Example Input: 10, 20, 30, 40, 50 Output: Sum of all the elements = 150
Helpful topics to understand this program better are-
2. C Program to find the sum of array elements
Let’s discuss the execution(kind of pseudocode) for the program to find the sum of array elements in C.
We need to iterate through the elements in the array and keep on adding the current element to the sum then loop through again until we reach the last element in the array.
Pseudocode: Start Initialize num, sum = 0, arr[] for i -> 0 to (num - 1) Add sum += arr[i] End
Let us now implement the above execution of the program to find the sum of array elements in C.
#include <stdio.h> #define MAX_SIZE 1000 int arr[MAX_SIZE]; int num, sum = 0; void calculateSumOfArray() { for (int i = 0; i < num; i++) { scanf("%d", &arr[i]); sum += arr[i]; } } int main() { printf("Enter size of the array: "); scanf("%d", &num); printf("Enter %d elements in the array: ", num); calculateSumOfArray(); printf("The Sum of all the elements in the array are = %d", sum); return 0; }
Output Enter size of the array: 5 Enter 5 elements in the array: 1 2 3 4 5 The Sum of all the elements in the array are = 15
Note: We can also use pointers and recursive function which works in a similar way to the above program. Try it out and share your solutions with everyone 🙂
3. Conclusion
In this C Programming example, we have discussed the pseudocode and implemented the C program to find the sum of array elements in C.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?