What is if-else Statement ?
The if else statement is another type of if statement. It is used to make two-way decisions. It executes one block of statement(s) when the condition is true and the other when it is false. In any situation, one block is executed and the other is skipped. In if-else statement:
- Both blocks of statement can never be executed.
- Both blocks of statements can never be skipped.
Syntax
Its syntax is as follows.
if (condition)
statement;
else
statement;
Two or more statements are written in curly brackets { } .
The syntax for compound statements in if else statement is as follows.
if (condition)
{
statement 1;
statement 2;
statement N;
}
else
{
statement 1;
statement 2;
statement N;
}
Program to print positive number entered by the user.
If the user enters a negative number, it is skipped.
#include <iostream> using namespace std; int main() { int number; cout << "Enter an
integer: "; cin >> number; // checks if the number is
positive
if (number > 0) {
cout << "You entered a positive integer: " <<
number << endl;
} cout << "This
statement is always executed."; return 0; } |
Output:
Enter an integer: 5 You entered a positive number: 5 This statement is always
executed. |
0 Comments