C++ if-else statement
- In this type of statement, there are two blocks are present: if and else. If block will always be executed when the given condition is true; if condition is false then else block will be executed. if-else statement take care of true as well as false condition.
- if-else statement provides one alternative choice to the user. If condition is true then statements of if block will be executed and if condition is false then statements present inside the else block will be executed.
- Here is a syntax of if-else statement is as follows:
- If the condition is true then the statements present inside the if block will be executed and if the condition is false then the statements present inside the else block will be executed. You can understand the concept of if-else statement more clearly with the help of following diagram:
- Here is an example of if-else statement as follows:
cout<<“n Enter the value of a and b:”;
cout<<“value of a and b are equal”;
cout<<“value of a and b are not equal”;
The output of the above program is as follows:
Enter the value of a and b:4
value of a and b are not equal
In the above example we have declared two variables a and b. here we have used cin function to read the input from the console. When we give the input then first value is assigned to a, and 2nd value is assigned to b. after that we have used if-else statement. Inside this we have checked that if the both variable values are same then if block will be executed otherwise else block will be execute. In this example both variable values are different. So else part will be executed.