It may so happen that in a program we want more than one statement to be executed if the expression following if is satisfied. If such multiple statements are to be executed then they must be placed within a pair of braces as illustrated in the below example.
The current year and the year in which the employee joined the organization are entered through the keyboard. If the number of years for which the employee has served the organization is greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of service are not greater than 3, then the program should do nothing.
/Calculation of Bonus */
int bonus, cy, yoj, yr_of_ser;
printf(“Enter current year and year of joining”);
scanf(“%d %d”,&cy, &joj);
printf(“Bonus =Rs. %d”,bonus);
In the above program we observe that
- The two statements to be executed on satisfaction of the condition have been enclosed within a pair of braces.
- If a pair of braces is not used then the C compiler assumes that the programmer wants only the immediately next statement after the if to be executed on satisfaction of the condition.
- In other words we can say that the default scope of the if statement is the immediately next statement after it.
- 61The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements…
- 60The programs that we have learned/developed in this tutorial so far used either a sequential or a decision control instruction. In the first one, the calculations were carried out in a fixed order, while in the second, an appropriate set of instructions were executed depending upon the outcome of the condition…