GoogleTag

Google Search

[Programming] Question 2: Find the sum of all elements in an array in C?

Learn how to write a C program to calculate the sum of all elements in an array. This guide provides a clear explanation of how to initialize an array, iterate through its elements, and compute the total sum. Perfect for beginners looking to understand array manipulation and basic programming operations in C.

#include <stdio.h>

int main() {
	int arr[] = {1, 2, 3, 4, 5};
	int sum = 0;
	int i;

	for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
		sum += arr[i];
	}

	printf("Sum of array elements: %d\n", sum);

	return 0;
} 
Explanation:

Inside the main() function:

 - An integer array arr is declared and initialized with values.

- An integer variable sum is initialized to zero to store the sum of array elements.

- A for loop is used to iterate through each element of the array.

- Within the loop, each element of the array is added to the sum.

- Finally, the sum of array elements is printed to the console.

 

Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts