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:
- Include the iostream library: This library is used for input and output operations in C++.
#include <iostream>
- 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;
- 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;
- 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;
- 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:
- Save the code in a file with a .cpp extension, for example, average_numbers.cpp.
- Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the program using a C++ compiler.
- Run the compiled program:
./average_numbers
You will be prompted to enter three numbers, and the program will display their average.
Leave a Reply