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:
- 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: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.
- 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
for
loop is used to iterate from 1 to 10. The loop variablei
is initialized to 1, and the loop continues as long asi
is less than or equal to 10. After each iteration,i
is incremented by 1. - Inside the loop, the variable
sum
is updated by adding the current value ofi
to it. - The variable
aver
is calculated by dividing the current value ofsum
by 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%d
is a placeholder for the integer value ofsum
. - 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 ofaver
. - Finally, the
return 0
statement 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.
Your article helped me a lot, is there any more related content? Thanks!
click here and Create Account get 10usd https://www.binance.com/activity/referral-entry/CPA/together-v4?hl=en&ref=CPA_00JRQQICQ6&utm_source=fee_page