Solved Examples · Example 17
Q.Write a C program to accept four numbers and compute their sum and average.
The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
#include<stdio.h>
void main()
{
int num1, num2, num3, num4, sum;
float averag;
printf("Enter Four Numbers\n");
scanf("%d%d%d%d", &num1, &num2, &num3, &num4);
sum=num1+num2+num3+num4;
averag=sum/4.0;
printf("sum=%d\n average=%f\n", sum, averag)
}
Sample output printed in the textbook:
Enter Four Numbers
18 22 14 26
Sum = 80
Average = 20.000000
#include<stdio.h>
void main()
{
int num1, num2, num3, num4, sum;
float averag;
printf("Enter Four Numbers\n");
scanf("%d%d%d%d", &num1, &num2, &num3, &num4);
sum=num1+num2+num3+num4;
averag=sum/4.0;
printf("sum=%d\n average=%f\n", sum, averag)
}
Enter Four Numbers
18 22 14 26
Sum = 80
Average = 20.000000
Karnataka PUCTextbookLongImportance★★★★★est
55% · 84/154 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →[!TLDR]
Read four integers, add them, and print the sum (80) and the floating-point average (20.000000).
Averaging shows why the type of a division matters in C. The four values are stored in int variables and their total, sum, is also an int. If the average were written as sum/4 the result would be truncated to an integer; writing sum/4.0 forces the division to be done in floating point, so the exact average is kept. The average variable is therefore declared float and printed with the %f specifier, while the integer sum is printed with %d. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.