Source Code
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3; // Declare variables to hold the three numbers
cout << "Enter the first number: "; // Prompt the user to enter the first number
cin >> num1; // Read the first number from the standard input stream
cout << "Enter the second number: "; // Prompt the user to enter the second number
cin >> num2; // Read the second number from the standard input stream
cout << "Enter the third number: "; // Prompt the user to enter the third number
cin >> num3; // Read the third number from the standard input stream
int largest = num1; // Initialize the largest number to the first number
// Compare the second number to the largest number
if (num2 > largest)
largest = num2;
// Compare the third number to the largest number
if (num3 > largest)
largest = num3;
cout << "The largest number is: " << largest << endl; // Print the largest number
return 0;
}
Code Explanation
This program declares three variables num1
, num2
, and num3
of type int
to hold the three numbers entered by the user. It then uses the cout
object to print prompts asking the user to enter the numbers and the cin
object to read the numbers from the standard input stream.
To find the largest number, the program initializes a variable largest
to the value of num1
. It then uses two if
statements to compare num2
and num3
to largest
and update largest
if either of these numbers is greater than largest
.
Finally, the program uses the cout
object to print the value of largest
, which is the largest number among the three numbers.
Explanation about if-else
In C++, the if-else
statement is a control flow statement that allows you to execute a block of code conditionally.
The if
clause specifies a condition, and the code inside the {}
brackets following the if
clause is executed if the condition is true. The else
clause specifies an alternative block of code to execute if the condition is false.
Leave a Reply