by Dinesh Thakur Category: Control Structures

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:

             Flowchartsfor if statements containing more than one statements in if and/or else blocks

           Block Statements in the if Statement

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.

           other forms of if-else statements

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");
 
}

Block Statements in the if Statement



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article