C program to find the sum and average of n numbers; Through this tutorial, we will learn how to find sum and average of n numbers in the c program with the help for loop and while loop.
Algorithm and Program to Find Sum and Average of N Numbers in C
Let’s use the following algorithm and program to find sum and average of n numbers using while loop and for loop in c:
- Algorithm to Find Sum and Average of N Numbers
- C Program to Find Sum and Average of N Numbers using For Loop
- C Program to Find Sum and Average of N Numbers using While Loop
Algorithm to Find Sum and Average of N Numbers
Use the following algorithm to write a program to find the sum and average of n numbers; as follows:
- Step 1: Start Program.
- Step 2: Read the term of n numbers from the user.
- Step 3: Then read one by one numbers and calculate sum and average of n numbers using for loop or while loop.
- Step 4: Print sum and average n number.
- Step 5: Stop Program.
C Program to Find Sum and Average of N Numbers using For Loop
#include <stdio.h>
int main()
{
int num, sum = 0, n;
float avg;
printf("Please Enter term of n number:-");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
printf("Number %d = ", i);
scanf("%d", &num);
sum = sum + num;
}
avg = sum / n;
printf("\nThe Sum of n Numbers = %d", sum);
printf("\nThe Average of n Numbers = %.2f\n", avg);
}
The output of the above c program; as follows:
Please Enter term of n number:-5 Number 1 = 1 Number 2 = 2 Number 3 = 3 Number 4 = 4 Number 5 = 5 The Sum of n Numbers = 15 The Average of n Numbers = 3.00
C Program to Find Sum and Average of N Numbers using While Loop
#include <stdio.h>
int main()
{
int num, i, sum = 0, n;
float avg;
printf("Please enter term of n numbers :- ");
scanf("%d", &n);
i = 1;
while(i <= n)
{
printf("Number %d = ", i);
scanf("%d", &num);
sum = sum + num;
i++;
}
avg = (float)sum / n;
printf("\nThe Sum of n Numbers = %d", sum);
printf("\nThe Average of n Numbers = %.2f\n", avg);
}
The output of the above c program; as follows:
Please enter term of n numbers :- 5 Number 1 = 1 Number 2 = 2 Number 3 = 3 Number 4 = 4 Number 5 = 5 The Sum of n Numbers = 15 The Average of n Numbers = 3.00