Write a program in C++, to find max of two numbers using if else control structure.
Write a program in C++, to find max of two numbers using if else control structure.
Best answer

Answer: Compare the two numbers with if; if the first is greater it is the maximum, else the second is.
#include <iostream>
using namespace std;
int main()
{
int num1, num2, max_no;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
if (num1 > num2)
max_no = num1;
else
max_no = num2;
cout << "Maximum of the two numbers is " << max_no << endl;
return 0;
}How it works: the two numbers are read with cin. The condition num1 > num2 is tested; if it is true, num1 is stored in max_no, otherwise (else) num2 is stored. If both numbers are equal, either one is the maximum, so the output is still correct.
Sample run: input 12 45 prints Maximum of the two numbers is 45.
Note that the body of main() must be enclosed in braces { }, and a new line is printed with endl or "\n".
Log in or create a free account to answer this question.