In this article, we will write a C program to find the average of 3 numbers. The program takes 3 integer values from the user as input, calculates their average, and prints the result on the output window.
Sample Example:
Enter three numbers: 10 20 30 Average of 10, 20 and 30 is: 20.000000 Enter three numbers: 5 10 7 Average of 5, 10 and 7 is: 7.333333
To calculate the average of N numbers, we have to first calculate their sum and then divide the sum with N. The average of the numbers can be an integer or a decimal point value.
In our example, the value of N is 3. So, to calculate the average of three numbers, we will first calculate their sum and then divide it by 3.
But wait, In C programming language, if you divide an integer value by another integer value for eg. 10/3 the result will also be an integer value. That is the result will be 3.0, not 3.33.
To avoid this problem, you can either typecast the result or divide the sum by a decimal point version of the number. For example, instead of dividing 10 by 3, we will divide it by 3.0 i.e. (10/3.0). This will give us a decimal point value as a result.
See implementation in the following program:
// C program to find the average // of three numbers #include <stdio.h> int main() { int num1, num2, num3; float avg; printf("Enter three numbers: "); scanf("%d %d %d", &num1, &num2, &num3); avg = (num1 + num2 + num3)/3.0; printf("Average of %d, %d and %d is: %f", num1, num2, num3, avg); return 0; }
Output:
Enter three numbers: 20 30 40 Average of 20, 30 and 40 is: 30.000000 Enter three numbers: 2 5 7 Average of 2, 5 and 7 is: 4.666667
Program Explanation:
- In this program, we first declared three variables:
num1
,num2
, andnum3
. These variables are of typeint
and will be used to store integer values entered by the user. - We also declared a variable named
avg
of typefloat
. This variable will store the calculated average of the three input numbers, and it’s a floating-point type to handle fractional results. - The program proceeds to ask the user for input. It displays the message “Enter three numbers: ” using the
printf
function to prompt the user. - The
scanf()
function is used to read three integer values from the user, and these values are stored in thenum1
,num2
, andnum3
variables respectively. - After reading the three input numbers, the program calculates the average.
- The formula used for the average calculation is:
avg = (num1 + num2 + num3) / 3.0;
- The
avg
variable now holds the average of the three input numbers. - Finally, the program uses the
printf()
function to display the calculated average along with the original values of num1, num2, and num3. - The format specifier
%f
is used to display the floating-point average value.
That’s all for this article. Thanks for reading!