C program to find sum of array elements

C program to find sum of array elements. To find the sum, the program will use a for loop to retrieve each elements and sum them using expression below.

sum = sum+arr[index]; or sum = sum + arr[index]

Test case:

Input: int arr[5] = {2,4,6,8,9};

Output: Sum = 29

Input: int arr[5] = {2,-4,6,8,9};

Output: Sum = 21

C program to find sum of array elements

/*
* C program to find sum of array elements
*/

#include<stdio.h>
int main(){

	int sum =0;
	int len  = 0;
	int index =0;
	int arr[5] = {2,4,6,8,9};
	
	len = sizeof(arr)/sizeof(int);//total elements in array

	//Run the for loop from index = 0
	//to index <len; in given example len is 5
	//so loop will be from 0 to 4

	for(index = 0; index <len; ++index){		
		
		//Retrieve array elements and add

		// Below could be written as sum = sum + arr[index];
		sum += arr[index];
	}
	
	//print sum
	printf("Sum: %d ",sum);

	return 0;
}

Output:
Sum: 29

Related Posts