w3resource

C Exercises: Find the sum of all elements of an array

C Array: Exercise-3 with Solution

Write a program in C to find the sum of all elements of an array.

Pictorial Presentation:

C Exercises: Find the sum of all elements of an array

Sample Solution:

#include <stdio.h>

void main()
{
    int a[100];
    int i, n, sum=0;
	
	
       printf("\n\nFind sum of all elements of array:\n");
       printf("--------------------------------------\n");	

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);
   
       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
        {
	      printf("element - %d : ",i);
	      scanf("%d",&a[i]);
	    }

    for(i=0; i<n; i++)
    {
        sum += a[i];
    }

    printf("Sum of all elements stored in the array is : %d\n\n", sum);
}

Sample Output:

Find sum of all elements of array:                                                                            
--------------------------------------                                                                        
Input the number of elements to be stored in the array :3                                                     
Input 3 elements in the array :                                                                               
element - 0 : 2                                                                                               
element - 1 : 5                                                                                               
element - 2 : 8                                                                                               
Sum of all elements stored in the array is : 15 

Flowchart :

Flowchart: Find sum of all elements of array

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to read n number of values in an array and display it in reverse order.
Next: Write a program in C to copy the elements one array into another array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - What is the argument for printf that formats a long?

Put an l (lowercased letter L) directly before the specifier.

unsigned long n;
long m;

printf("%lu %ld", n, m);

Ref : https://bit.ly/3dIwfkP