In C++ actions can be made based on decisions on different conditions. logical conditions are less than (<), greater than (>), equal to (==), less than or equal to (<=), greater than or equal to (>=) and not equal to (!=). ‘if’ statement is used to execute a block of code when a specified condition is true. The following program shows use of a ‘if’ statement.
#include<iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter first integer number ";
cin>>a;
cout<<"Enter second integer number ";
cin>>b;
if ( a > b) {
cout<<"First number is greater than second";
}
return 0;
}
Output:
Enter first integer number 12
Enter second integer number 8
First number is greater than second
‘else’ statement is used to execute a block of code when condition in the ‘if’ statement is false. The following program shows use of ‘if-else’ statement.
#include<iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter first integer number ";
cin>>a;
cout<<"Enter second integer number ";
cin>>b;
if (a > b) {
cout<<"First number is greater than second ";
}
else {
cout<<"Second number is greater than first ";
}
return 0;
}
Output1:
Enter first integer number 12
Enter second integer number 8
First number is greater than second
Output2:
Enter first integer number 8
Enter second integer number 12
Second number is greater than first
‘else if’ statement is used to execute a block of code when condition in the ‘if’ statement is not fulfilled. When conditions in both ‘if’ and ‘else if’ statement in not fulfilled then ‘else’ statement get executed. The following program shows the use of ‘if-else if-else’ statement.
#include<iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter first integer number ";
cin>>a;
cout<<"Enter second integer number ";
cin>>b;
if (a > b) {
cout<<"First number is greater than second ";
}
else if (a == b) {
cout<<"First number is equal to second ";
}
else {
cout<<"Second number is greater than first ";
}
return 0;
}
Output1:
Enter first integer number 12
Enter second integer number 8
First number is greater than second
Output2:
Enter first integer number 12
Enter second integer number 12
First number is equal to second
Output3:
Enter first integer number 8
Enter second integer number 12
Second number is greater than first