Average of two numbers in C
In this post, you will learn how to find the average of two numbers using the C programming language. There are different ways to find the average of numbers. Here, we have mentioned most of them.
The average of a set of numbers is simply the sum of the numbers divided by the total number of values in the set.
average = sum of all values / number of values
C program to find average of two numbers using user inputs
In the given C program, we ask the user to provide two numbers. Then, we calculate the sum and average of those numbers.
#include <stdio.h>
int main()
{
int num1, num2;
float result;
printf("Enter the first number: ");
scanf("%d",&num1);
printf("Enter the second number: ");
scanf("%d",&num2);
int sum = num1 + num2;
result = sum/2; //(float)sum/2;
printf("The Sum of %d and %d : %d\n", num1, num2, sum);
printf("The Average of %d and %d : %.2f\n", num1, num2, result);
return 0;
}
Output of the above code:
Enter the first number: 81
Enter the second number: 89
The Sum of 81 and 89 : 170
The Average of 81 and 89 : 85.00
C program to find average of two numbers using function
In the given C program, we create a user-defined function, calculate the sum and average of those numbers.
#include <stdio.h>
float averageOfNumbers(int a, int b)
{
return (float)(a + b)/2;
}
int main()
{
int num1, num2;
printf("Enter the first number: ");
scanf("%d",&num1);
printf("Enter the second number: ");
scanf("%d",&num2);
float average = averageOfNumbers(num1, num2);
printf("The average of %d and %d : %.2f\n", num1, num2, average);
return 0;
}
Output of the above code:
Enter the first number: 78
Enter the second number: 90
The average of 78 and 90 : 84.00
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative