if…else Statement in C
if…else statement is an extension of if statement supported by C language. The statement is a two-way decision making statement in which the condition is evaluated first and if it evaluates to true one set of statements is executed and other set is not. Conversely, if the condition evaluates to false then the other set will be executed but the first set won’t. The general syntax of if else statement is as follows:
if ( condition )
statement1;
else
statement2;
The condition can be any expression that evaluates to True or False. Also, statement1 and statement2, both can be a simple statement or compound statement. The following code snippet shows various legitimate if..else statements.
int x, y;
x = 10;
y = 20;
/* Using Constant values */
if ( 10 )
printf(“I will be displayed\n”);
else
printf(“I will NOT be displayed\n”);
if ( 0 )
printf(“I will NOT be displayed\n”);
else
printf(“I will be displayed\n”);
/* Using Variables values */
if ( x )
printf(“I will be displayed\n”);
else
printf(“I will NOT be displayed\n”);
/* Using Arithmetic Expressions */
if ( x + y )
printf(“I will be displayed\n”);
else
printf(“I will NOT be displayed\n”);
/* Using Relational Expressions */
if ( x < y )
printf(“I will be displayed\n”);
else
printf(“I will NOT be displayed\n”);
if ( x > y )
printf(“I will NOT be displayed\n”);
printf(“I will be displayed\n”);
/* Using Logical Expressions values */
if ( x + y > 10 && y > 10)
printf(“I will be displayed\n”);
else
printf(“I will NOT be displayed\n”);
if ( x + y > 10 && 0 )
printf(“I will NOT be displayed\n”);
else
printf(“I will be displayed\n”);
In addition, no matter whether a condition evaluates to True or False, the rest of the statements which immediately follow the construct will be executed normally. The following code snippet explains this.
if (0 )
printf(“I will NOT be displayed\n”);
else
printf(“I will be displayed\n”);
printf(“I will be displayed\n”);
The following code snippet explains how a compound statement can be used with if..else construct. However, it should be noted that it is not necessary that compound statement when used should be used with both if and else.
if ( 0 )
{
printf(“I will NOT be displayed\n”);
printf(“Me too NOT displayed\n”);
printf(“Same her, NOT displayed\n”);
}
else
printf(“I will be displayed\n”);
printf(“Oh! I will be displayed\n”);