Write a Program in C to Read 10 Numbers From the Keyboard and Find Their Sum and Average
The solution in C:
#include<stdio.h>
void main()
{
int i,n,sum=0 ;double aver=0;
printf("enter the number:");
scanf("%d",&n);
for(i=1;i<=10;i++){
sum=sum+i;
aver=sum/(double)10;
}
printf("The sum of 10 no is :%d\n",sum);
printf("The Average is :%lf",aver);
return 0;
}
This code is a simple C program that calculates the sum and average of the first 10 natural numbers. Let’s go through the code step by step:
- The code begins with the inclusion of the standard input/output library,
stdio.h, which provides functions for input and output operations. - The
main()function is the entry point of the program. - Inside the
main()function, several variables are declared:iis an integer variable used as a counter for the loop.nis an integer variable that will store the user input.sumis an integer variable initialized to 0. It will store the sum of the numbers.averis a double variable initialized to 0. It will store the average of the numbers.
- The program then prompts the user to enter a number using
printf(). The message displayed is “enter the number:”. - The input number is read using
scanf()and stored in the variablen. - A
forloop is used to iterate from 1 to 10. The loop variableiis initialized to 1, and the loop continues as long asiis less than or equal to 10. After each iteration,iis incremented by 1. - Inside the loop, the variable
sumis updated by adding the current value ofito it. - The variable
averis calculated by dividing the current value ofsumby 10. To ensure that the division is performed with decimal precision,(double)is used to cast the denominator to a double. - After the loop completes, the program prints the sum using
printf(). The message displayed is “The sum of 10 no is: %d\n”, where%dis a placeholder for the integer value ofsum. - Similarly, the program prints the average using
printf(). The message displayed is “The Average is: %lf”, where%lfis a placeholder for the double value ofaver. - Finally, the
return 0statement is used to indicate the successful execution of the program and terminate themain()function.
In summary, this code calculates the sum and average of the first 10 natural numbers and prints the result.
For Loop in C Programming Example





