Write a program in C to read 10 numbers from the keyboard and find their sum and average

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:

  1. The code begins with the inclusion of the standard input/output library, stdio.h, which provides functions for input and output operations.
  2. The main() function is the entry point of the program.
  3. Inside the main() function, several variables are declared:
    • i is an integer variable used as a counter for the loop.
    • n is an integer variable that will store the user input.
    • sum is an integer variable initialized to 0. It will store the sum of the numbers.
    • aver is a double variable initialized to 0. It will store the average of the numbers.
  4. The program then prompts the user to enter a number using printf(). The message displayed is “enter the number:”.
  5. The input number is read using scanf() and stored in the variable n.
  6. A for loop is used to iterate from 1 to 10. The loop variable i is initialized to 1, and the loop continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1.
  7. Inside the loop, the variable sum is updated by adding the current value of i to it.
  8. The variable aver is calculated by dividing the current value of sum by 10. To ensure that the division is performed with decimal precision, (double) is used to cast the denominator to a double.
  9. After the loop completes, the program prints the sum using printf(). The message displayed is “The sum of 10 no is: %d\n”, where %d is a placeholder for the integer value of sum.
  10. Similarly, the program prints the average using printf(). The message displayed is “The Average is: %lf”, where %lf is a placeholder for the double value of aver.
  11. Finally, the return 0 statement is used to indicate the successful execution of the program and terminate the main() function.

In summary, this code calculates the sum and average of the first 10 natural numbers and prints the result.

Read more

For Loop in C Programming Example

2 thoughts on “Write a program in C to read 10 numbers from the keyboard and find their sum and average”

Leave a Comment