Write a C Program to Find Average of Two Numbers with an example. The average of two numbers is the sum of the given two numbers divided by 2. For instance, if the given two integers are A and B, the formula to find the average is (A + B) / 2.
Example:
A = 10, B = 20
Average(A, B) = (10 + 20) / 2 = 15.
Here, we use the Addition Operator (+) to add two numbers, then the division (/) operator to divide the total by 2. Please refer to the Arithmetic Operators in C.
This C example allows to enter two Integers and calculates the sum and average of that numbers.
#include <stdio.h>
int main()
{
int number1, number2;
float res;
printf("Enter the First Number to find = ");
scanf("%d",&number1);
printf("Enter the Second Number to find = ");
scanf("%d",&number2);
int sm = number1 + number2;
res = sum/2; //(float)sum/2;
printf("The Sum of %d and %d = %d\n", number1, number2, sm);
printf("The Average of %d and %d = %.2f\n", number1, number2, res);
return 0;
}
Average of two numbers output
Enter the First Number to find Average = 20
Enter the Second Number to find Average = 60
The Sum of 20 and 60 = 80
The Average of 20 and 60 = 40.00
NOTE: When finding the average of two numbers, the result (res) variable must be a floating-point value. Next, we must typecast the result to float because in most cases, the average value contains decimal precision, and we must preserve it. For more lab programs, refer to the C programs page.
C Program to find the average using functions
In this program, we created a new function that calculates and returns the average of given two numbers.
#include <stdio.h>
float calcAverageofTwo(int a, int b)
{
return (float)(a + b)/2;
}
int main()
{
int number1, number2;
printf("Enter the First Number to find Average = ");
scanf("%d",&number1);
printf("Enter the Second Number to find Average = ");
scanf("%d",&number2);
float average = calcAverageofTwo(number1, number2);
printf("The Average of %d and %d = %.2f\n", number1, number2, average);
return 0;
}

Also Read