Often we wish to perform more than one operation when the condition in an if statement evaluates as true and/or false as shown in Fig. In such situations, we use block statements (also called compound statements) within the if statement.
When both alternative statements in the general format of an if-else statement (i. e., statement1 and statement2) are block statements, the if-else statement may be written in one of the styles given below:
If expression expr is true (i.e., non-zero), statements within the if block are executed in the given sequence; otherwise statements in the else block are executed. The flowchart for this statement is given in Fig. a. Note that the statements within the if and else blocks are indented to improve readability. Also, observe the style of using opening braces in a block. In first style, it is written on a line by itself, whereas in second style, it is written on the line containing the if and else keywords. Both styles are commonly used. The second style is used in this book mainly because it saves space.
If statement 1 or statement2 (but not both) in the if-else statement is a block statement, we get two other forms of if-else statements as shown below.
Similarly, we can replace statement] in a simple if statement with a block statement as
if (expr) {
statement1 a ;
statement1 b ;
…….
}
The flowchart for this simple if statement is given in Fig. b. Finally note that when the if block and else block contain a single statement, curly braces are not required. However, programmers often use such braces as shown below:
if (expr) {
statement1;
}
else {
statement2;
}
This form requires more lines, however, it simplifies the addition of one or more statements in if and/or else blocks and also prevents introduction of difficult to trace bugs when such statements are added without braces.
Illustrates if-else expression.
#include<stdio.h>
void main()
{
int A, B;
clrscr();
printf("Enter two integers:");
scanf("%d %d",&A,&B);
if (A % B)
printf("A is not divisible by B.\n");
else
printf("A is divisible by B.\n");
}