It is a powerful decision-making statement. This statement is used to control the flow of execution of statements. if and else both are keywords. The normal flow of a program is altered by the if-else statement.
Syntax of if-else statement:
1 2 3 4 5 6 7 8 |
if (condition) { //execute if condition is true; } else { //execute if condition is false; } |
First of all, the condition is check and then, depending on whether the condition is true (non zero) or false (zero), it transfers the control to a particular statement.
If the condition is true then the statements inside the if block gets executed otherwise statements inside else block get executed.
if can be standalone but else cannot be standalone.
Flowchart of if-else statement:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int main() { int x = 20; int y = 25; if (x == y) { printf("x and y are equals"); } else { printf("x and y are not equals"); } } |
Output:
1 |
x and y are not equals |
Note: There should not be any statement between if and else.
If any statement exists between if and else then compiler gives an error.
For example:
1 2 3 4 5 6 7 8 9 |
if (1) { printf("hi"); } printf("goodbye"); //error else { printf("bye"); } |
The Condition of if will be any of the following to print output ‘hi’:
- constant
- string (“hello”)
- keyword (‘for’, ‘int’, sizeof(int))
- character (‘a’, ‘A’)
- Number (10, -600,)
- null character (null)
- NULL
- Logical expression (1 && 1)
- Arithmatic expression (5 + 2 % 5)
Forms of if-else statements
There are many forms of if statements, check out Forms of if: page for more details. These variations are used in different ways.