Ex: Write a C program to print sum of all array elements. How to write a C program which print sum of all array elements. C program to print sum of all array elements.
Input from user:
Enter how many elements you are going to enter: 5
Enter the elements:
10
20
30
40
50
Expected output:
Sum of all array elements= 150
1. Accept input number (limit of number of elements) store in variable say no .
2. Declare array of 100 size variable say a[100], declare variable i for a loop.
3. To store sum of all elements declare variable sum=0.
4. Accept elements from user and store this elements in array one by one using for loop:
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);
}
5. After that use one more for loop to store sum of all elements using:
for(i=0;i<no;i++)
{
sum=sum+a[i];
}
6. After that, outside the block of for loop print sum(it will print sum of all elements in array).
#include<stdio.h>
void main()
{
int a[100],i,no,sum=0;
printf("Enter how many elements you are going to enter: ");
scanf("%d",&no);
printf("Enter the elements:\n");
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<no;i++)
{
sum=sum+a[i];
}
printf("Sum of all elements=%d",sum);
}
Above program shows the following output:
Input from user:
Enter how many elements you are going to enter: 5
Enter the elements:
10
20
30
40
50
Expected output:
Sum of all array elements= 150
Step by step logic of the given program:
1. Accept input number (limit of number of elements) store in variable say no .
2. Declare array of 100 size variable say a[100], declare variable i for a loop.
3. To store sum of all elements declare variable sum=0.
4. Accept elements from user and store this elements in array one by one using for loop:
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);
}
5. After that use one more for loop to store sum of all elements using:
for(i=0;i<no;i++)
{
sum=sum+a[i];
}
6. After that, outside the block of for loop print sum(it will print sum of all elements in array).
C Program to print Sum of All Array Elements:
#include<stdio.h>
void main()
{
int a[100],i,no,sum=0;
printf("Enter how many elements you are going to enter: ");
scanf("%d",&no);
printf("Enter the elements:\n");
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<no;i++)
{
sum=sum+a[i];
}
printf("Sum of all elements=%d",sum);
}
Above program shows the following output:
No comments:
Post a Comment
If you have any doubts, please discuss here...👇