We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear Decision Making. This happens when no options or no repetitions of certain calculations are necessary. However, in practice, we have a number of situations where we may have to change the order of execution of statements based on certain conditions, or repeat a group of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.
C language possesses such decision-making capabilities by supporting the following statements:
- if statement
- switch statement
- Conditional operator statement
- goto statement
These statements are popularly known as decision-making statements. Since these statements ‘control’ the flow of execution, they are also known as control statements.
We have already used some of these statements in the earlier examples. Here, we shall discuss their features, capabilities and applications in more detail.
DECISION MAKING WITH IF STATEMENT
The if statement is a powerful decision-making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It takes the following form
if (test expression)
It allows the computer to evaluate the expression first and then, depending on whether the value of the expression (relation or condition) is true’ (or non-zero) or ‘false’ (zero), it transfers the control to a particular statement. This point program has two paths to follow, one for the true condition and the other for the flash condition.
..... ..... if (category == SPORTS) { marks = marks + bonus_marks; } printf("%f", marks); ..... .....
The program tests the type of category of the student. If the student belongs to the SPORTS category, then additional bonus_marks are added to his marks before they are printed. For others, bonus_marks are not adde.
The program in given reads four values a, b, c, and d from the terminal and evaluates the ratio of (a+b) to (c-d) and prints the result, if c-d is not equal to zero.
Program main() { int a, b, c, d; float ratio; printf("Enter four integer values\n"); scanf("%d %d %d %d", &a, &b, &c, &d); if (c-d != 0) /* Execute statement block */ { ratio = (float)(a+b)/(float)(c-d); printf("Ratio = %f\n", ratio); } } Output Enter four integer values 12 23 34 45 Ratio = -3.181818 Enter four integer values 12 23 34 45
The second run has neither produced any results nor any message. During the second run, the value of (c-d) IS equal to zero and therefore, the statements contained in the statement-block are skipped. Since no other statement follows the statement-block, program stops without producing any output. Decision Making and Branching in C
Note the use of float conversion in the statement evaluating the ratio. This is necessary to avoid truncation due to integer division. Remember, the output of the first run -3.181818 is printed correct to six decimal places. The answer contains a round off error. If we wish to have higher accuracy, we must use double or long double data type.
The program has to test two conditions, one for weight and another for height. This is done using the compound relation
if (weight < 50 && height > 170)
This would have been equivalently done using two if statements as follows:
if (weight < 50) if (height 170) count = count +1;
If the value of weight is less than 50, then the following statement is executed, which in turn is another if statement. This if statement tests height and if the height is greater than 170, then the count is incremented by 1.
Program main() { int count, i; float weight, height count = 0; printf("Enter weight and light for 10 boys\n"); for (i =1; i<= 10; i++) { scanf("%f %f", &weight, &height); if (weight <50 && height > 170) } printf("Number of boys with weight < 50 kg\n"); printf("and height > 170 cm = %d\n", count); } Output Enter weight and height for 10 boys 45 176.5 55 174.2 47 168.0 49 170.7 54 169.0 53 170.5 49 167.0 48 175.0 47 167 51 170 Number of boys with weight < 50 kg and height > 170 cm = 3
Applying De Morgan’s Rule
While designing decision statements, we often come across a situation where the logical NOT operator is applied to a compound logical expression, like ! (x&&yll!z). However, a positive logic is always easy to read and comprehend than a negative logic. In such cases, we may apply what is known as De Morgan’s rule to make the total expression positive. This rule is as follows:
“Remove the parentheses by applying the NOT operator to every logical expression component, while complementing the relational operators”
-
-
-
-
-
- x becomes !x
- !x becomes x
- && becomes ||
- || becomes &&
-
-
-
-
Examples : !(x && y || !z) becomes !x || !y && z !(x < = 0 || !condition) becomes x >0&& condition
If the test expression is true, then the true-block statement(s), immediately following the if statements are executed; otherwise, the false-block statement are executed. In either case, either true-block transferred subsequently to the statemen-x.
Let us consider an example of counting the number of boys and girls in a class. We use code 1 for a boy and 2 for a girl
..... ..... if (code == 1) boy = boy + 1; if (code == 2) girl = girl+1; ..... .....
The first test determines whether or not the student is a boy. If yes, the number of boys is increased by 1 and the program continues to the second test. The second test again determines whether the student is a girl. This is unnecessary. Once a student is identified as a boy, there is no need to test again for a girl. A student can be either a boy or a girl, not both. The above program segment can be modified using the else clause as follows:
..... ..... if (code == 1) boy = boy + 1; else girl = girl + 1; xxxxxxxxxx .....
Here, if the code is equal to 1 . the statement boy = boy + 1 ; is executed and the control is transferred to the statement xxxxxx, after skipping the else part. If the code is not equal to 1, the statement boy = boy 1; is skipped and the statement in the else part girl girl: 1 ; is executed before the control reaches the statement xxxxxxxx.
Consider the program given in Decision Making and Branching in C When the value (c-d) is zero, the ratio is not calculated and the program stops without any message. In such cases we may not know whether the program stopped due to a zero value or some other error.
The program uses count to count the number of terms added. The program stops when the value the term is less than 0.0001 (ACCURACY). Note that when a term is less than ACCURACY, the of of n is set equal to 999 (a number higher than 100) and therefore the while loop terminates. The results are printed outside the while loop.
NESTING OF IF….ELSE STATEMENTS – DECISION MAKING
When a series of decisions are involved, we may have to use more than one if…else statement in nested form as shown below:
The logic of execution is illustrated in image. If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true,
the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statemet-x.
A commercial bank has introduced an incentive policy of giving bonus to all its deposit holders. The policy is as follows: A bonus of 2 per cent of the balance held on 31st December is given to every one, irrespective of their balance, and 5 per cent is given to female account holders if their balance is more than Rs. 5000.
Dangling Else Problem
One of the classic problems encountered when we start using nested if….else statements is the dangling else. This occurs when a matching else is not available for an if. The answer to this problem is very simple. Always match an else to the most recent unmatched if in the current block. In some cases, it is possible that the false condition is not required. In such situations, else statement may be omitted
“else is always paired with the most recent unpaired if’
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the default-statement will be executed. logic of execution of else if ladder statements.
Rules for Decision Making Indentation
When using control structures, a statement often controls many other statements that follow it. In such situations it is a good practice to use indentation to show that the indented statements are dependent on the preceding controlling statement. Some guidelines that could be followed while using indentation are listed below:
- Indent statements that are dependent on the previous statements; provide at least three spaces of indentation.
- Align vertically else clause with their matching if clause.
- Use braces on separate lines to identify a block of statements.
- Indent the statements in the block by at least three spaces to the right of the braces.
- Align the opening and closing braces.
- Use appropriate comments to signify the beginning and end of blocks.
- Indent the nested statements as per the above rules.
- Code only one clause or statement on each line.
THE SWITCH STATEMENT – DECISION MAKING AND BRANCHING
We have seen that when one of the many alternatives is to be selected, we can use an if statement to control the selection.
However, the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes difficult to read and follow. At times, it may confuse even the person who designed it. Fortunately, C has a built-in multiway decision statement known as a switch.
The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed.
The general form of the switch statement is as shown below: switch (expression) case value-1: block-1 break; case value-2: block-2 break; default: default-block break; statement-x;
The expression is an integer expression or characters. Value-1, value-2 are constants or constant expressions (evaluable to an integral constant) and are known as case labels. Each of these values should be unique within a switch statement. block-1, block-2 are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon (;).
When the switch is executed, the value of the expression is successfully compared against the values value-1, value-2,…. If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.
The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x. (ANSI C permits the use of as many as 257 case labels).
Rules for switch statement
- The switch expression must be an integral type.
- Case labels must be constants or constant expressions.
- The break statement transfers the control out of the switch statement.
- Case labels must be unique. No two labels can have the same value.
- Case labels must end with colon.
- Decision Making and Branching
- The break statement is optional. That is, two or more case labels may belong to the same statements.
- The default label is optional. If present, it will be executed when the ex-pression does not find a matching case label.
- There can be at most one default label.
- The default may be placed anywhere but usually placed at the end.
- It is permitted to nest switch statements.
Read More Topics |
Functions of Layer in the OSI Model |
The Open System Interconnection (OSI) Model |
The Point-to-Point Protocol (PPP) |
Carrier Sense Multiple Access with Collision Detection |