In this tutorial we will write a c++ program to find the sum and average of three numbers.
C++ Program to find the average of 3 numbers
In this example, we are taking input from the user and calculating the average of entered numbers using “/” operator.
The reason why we are using double as data type because a user can enter any data type number such as int, float, long & double, since double can hold the values of all these data types, it is important to declare variables as double data type.
However if you are not taking input from user then you can declare the data type based on the number value, for example if you want to find out the average of three integer numbers then you are declare num1, num2 & num3 as int but you have to use double as the return type of the avr
method because the average of 3 int numbers can be a decimal value.
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> using namespace std; int main() { system ("CLS"); //to clear the screen double a,b,c,sum,av; cout<<"Enter the first number: "; cin>>a; cout<<"Enter the second number: "; cin>>b; cout<<"Enter the third number: "; cin>>c; sum=a+b+c; av=sum/3; cout<<"The Sum of entered numbers is:"<<sum<<"\n"; cout<<"The Average of entered numbers is:"<<av; return 0; } |
Output: