Press ESC to close

How to Find Average of Three Numbers in C++

Photo by luis gomes

Below is the C++ program to find the average of three numbers.

#include <iostream>
using namespace std;
int main() {
    // Declare variables to store the numbers and their average
    double num1, num2, num3, average;
    // Ask the user to enter the 1st number
    cout << "Enter the first number: ";
    cin >> num1;
    // Ask the user to enter the 2nd number
    cout << "Enter the second number: ";
    cin >> num2;
    // Ask the user to enter the 3rd number
    cout << "Enter the third number: ";
    cin >> num3;
    // Find the average of the three numbers
    average = (num1 + num2 + num3) / 3;
    // Output the average
    cout << "The average of " << num1 << ", " << num2 << ", and " << num3 << " is " << average << endl;
    return 0;
}

 

Explanation:

  1. Include the iostream library: This library is used for input and output operations in C++.
#include <iostream>
  1. Use the std namespace: By adding using namespace std;, we can avoid prefixing std:: to standard library functions and objects like cout and cin.
using namespace std;
  1. Main function: The execution of a C++ program begins with the main function.
int main() {
// Code here
    return 0;
}

    4. Declare variables: We declare four variables num1, num2, num3, and average to store the numbers input by the user and their average.

 

double num1, num2, num3, average;
  1. Prompt the user for input: Using cout, we display a message to the user asking them to input three numbers. We then use cin to read the numbers.
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;

6. Calculate the average: We add num1, num2, and num3, then divide the sum by 3 to find the average.

 

average = (num1 + num2 + num3) / 3;
  1. Display the result: Finally, we output the average using cout.
cout << "The average of " << num1 << ", " << num2 << ", and " << num3 << " is " << average << endl;

How to Compile and Run the Program:

  1. Save the code in a file with a .cpp extension, for example, average_numbers.cpp.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Compile the program using a C++ compiler. 
  5. Run the compiled program:

./average_numbers

You will be prompted to enter three numbers, and the program will display their average.

Leave a Reply

Your email address will not be published. Required fields are marked *