• No results found

Selection and Control Structures

Learning Objectives

After completing this chapter, you will be able to:

 Apply selection statements in your programs

 Apply control structures in your programs

Basic Programming Constructs

The basic programming constructs are sequence, selection, and iteration (looping). In a sequence construct, the instructions are executed in the same order in which they appear in the program. In a selection structure, the control flow can be altered by evaluating conditions. In an iterative structure, a group of instructions is executed repeatedly, until some condition is satisfied.

Statements in C

Simple Statement (expression statement)

An expression terminated by a semicolon (;) is termed to be a simple statement (or expression statement).

Example 4. 1 a=8;

c=a+b;

;  Null statement

Compound Statements / Blocks

Compound statements are used to group the statements into a single executable unit. It consists of one or more individual statements enclosed within the braces { }.

Example 4. 2 { { { a=10; a=1; b=10; x=a*b; { c=a + b; y = x * b – k; b=2; c=3; } } } } Sequence

A program, which consists of declaration statements, input-output statements, and one or more simple expression statements, is executed in a sequential manner.

Selection Statements

Selection statements are used to alter the normal sequential flow of control. It provides the ability to decide the order of execution. The following are the selection constructs available in C:

 “ if ” statement

 Conditional / Ternary operator statement (? :)

 “switch” statement

‘if’ Statement

The if statement, allows us to establish decision-making in the programs. Programs may require certain logical tests to be carried out at some particular points. The tests and subsequent decisions are made by evaluating a given expression as either True (non zero) or False (zero). An expression involves arithmetic, relational, and/or logical operators. Depending on the result of the expression the statements are executed.

The if statement has three basic forms:

 Simple if-else  Nested if  if-else if ladder Simple “if-else” General Form: if (expression) { statements1; } [ else { statements2; } ] statements3;

[ ] is used to represent the optional usage of ‘else’ block.

Expression can be arithmetic, logical, and/or relational expression. If the expression is evaluated to true (nonzero), the statements1 are executed and the control is transferred to the statements (statements3) next to the if construct is executed. If the expression is evaluated to false (zero), the statements1 will be skipped and the else part statements (statements2) are executed. If the else part is not specified, the statements (statements3) next to the if construct is executed.

Example 4.3: Program to find maximum of two numbers. if (a<b)

max = b; else

max = a;

printf(“ max = %d” ,max);

Short-circuit Evaluation

Whenever the expression with the operators && and || are evaluated, the evaluation process stops as soon as the outcome, true or false is known. For example:

expr1 && expr2

If the value of expr1 is zero, the evaluation of expr2 will not occur [ 0 AND anything is 0] expr1 || expr2

If expr1 has non-zero value, the evaluation of expr2 will not occur [ 1 OR anything is 1]

Nested ‘if’ Statement

Body of an ‘if’ statement contains another ‘if’ statement. General Form: if (expression) { statements1; if (expression) statements-1; } else { statements2; if (expression) statements-2; } Example 4.4

Program to find the maximum of 3 numbers. if (a>b) if (a>c) printf(“largest = %d”, a); else printf (“largest = %d”,c); else if (c>b) printf (“largest = %d”,c); else printf (“largest = %d”,b);

‘if… else if’ Ladder Statement General Form: if (expression) statements1; else if (expression) statements2; else if(expression) statements3; else statements4;

Each condition is evaluated in order and if any condition is true the corresponding statement is executed and the remainder of the chain is skipped. The final ‘else’ statement is executed only if none of the previous conditions are satisfied. Final ‘else’ serves as a default case and is useful in detecting an impossible or error condition.

Example 4.5 if (mark >= 75) printf(“Honours\n”); else if (mark >=60) printf(“First Class\n”); else if (mark >=50) printf(“Second Class\n”); else if (mark >=45) printf(“Third Class\n”); else printf(“Fail\n”);

Conditional / Ternary / ?: Operator

This operator takes 3 expressions / operands. It is a more efficient form for expressing simple if statements.

General form:

[variable = ]expr1? expr2: expr3;

This simply states:

if (expr1 is true) then expr2 else expr3

Where:

 expr2 is evaluated, if the value of expr1 is non-zero (true part).

Example 4.6

max = (a>b) ? a : b;

which is similar to the following if-else statement. if (a>b)

max = a; else

max = b;

Switch Statement

This is a conditional control statement that allows some particular group of statements to be chosen from several available groups. It is a multi-way conditional statement generalizing the ‘if- else’ statement. A switch statement allows a single variable to be compared with several possible case labels, which are represented by constant values. If the variable matches with one of the constants, then an execution jump is made to that point. A case label can not appear more than once and there can only be one default expression.

General Form:

switch (expression) {

case item1: statement 1; break;

case item2: statement 2; break;

case itemn: statement n; break;

default : statement; }

Expression in the switch statement, must be an integer valued expression. Expression may be a constant value, variable, array variable, pointer variable, relational expression, logical expression, and/or arithmetic expression. Items which represent the case labels must be an integer constant or character constant. Default case is optional and if specified, default statements will be executed, if there is no match for the case labels.

The break is needed to terminate the switch after the execution of particular choice. Otherwise the next cases get evaluated.

Example 4.7 switch (op) { case ‘+’: c=a+b; break; case ‘-’: c=a-b; break; case ‘*’: c=a*b; break; case ‘/’: c=a/b; break; default:

printf (“Invalid operator”); }

Iteration Statements

Most of the real world applications require some set of instructions to perform repetitive actions on a stream of data. There are several ways to execute loops in C. The statements used for looping are: ‘for’, ‘while’, ‘do- while’.

‘for’ statements

This statement is used to repeat a statement or a set of statements for a specified number of times or until a condition satisfied.

General Form:

for (expression1; expression2; expression3) {

statement / block of statements; }

Where:

 expression1 initializes the counter/index variable. The initialization is usually an assignment statement that is used to set the index variable or loop control variable.

 expression2 is to set a terminating condition. It is evaluated at the beginning of every iteration. If the test condition is True, the statements inside the loop are executed. If the test condition is False, the control is transferred to the statement, which follows the loop.

 expression3 is the loop variant/modifier (increment / decrement), which is evaluated at

These three expressions are separated by semicolons.

Example 4.8

(1) for (x=0; ((x>3) && (x<9)); x++)

(2) for (x=0, y=4; ((x>3) && (y<9)); x++, y+=2) (3) for (x=0, y=4, z=4000; z ; z/=10)

(4) c=2;

for (;c<=20;c=c+2)

(5) for (c=2;;++c)  infinite loop

(6) c=2; for (;c<=20;) { printf (“%d”, c); c++; } (7) int c=0;

for(;;)  infinite loop

{ c+=1;

printf (“c=%d”, c); }

Nested ‘for’ statement

There are many situations in which a loop statement contains another loop statement. Such loops are called nested loops.

Example 4.9 for (i=1;i<=3;i++) { printf(“\n i = %d”,i); for (j=1;j<=3; j++) printf (“\n j = %d”,j); }

In the above example, the loop controlled by the value of ‘i’ is called the outer loop. The second loop, controlled by the value of ‘j’, is called inner loop. All statements in the inner loop are within the boundaries of the outer loop. Different variables must be used to control each loop. For each & every iteration through the outer loop, the inner loop runs completely.

‘while’ statement

The while is an entry controlled loop statement. The conditional expression is evaluated at the beginning and the result of the expression decides on the execution of the body of loop. If the result is True, the body of the loop is executed,

General Form:

while (expression) {

Statements; }

Expression can be a constant value, variable or any expression. If the expression evaluates to True, the body of the loop is executed, otherwise statements after the while block is executed. After executing the body of the loop, the expression is checked again. The body of the loop is executed repeatedly until the expression is False. If the expression is initially False, the body of loop is not executed at all.

The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements.

Example 4.10

Different ways to use while loops

(1) while(x--){ }; (2) while(x = x+1){ }; (3) while(x) { }; (4) while(1); (5) while ( (ch = getche ( )) != ‘q’) putchar(ch); (6) c=1; while (c<=10) { printf (“%d”,c); ++c; }

‘do - while’ statement

The do... while is an exit controlled loop statement. General Form:

do

statement (s); while (expression);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the expression in the while statement is evaluated. If the expression is evaluated to True, the program continues to evaluate the body of the loop once again. This process continues as long as the expression evaluates to True. When the condition becomes False, the loop will be terminated and control is transferred to the next statement following the do..while. Since the expression is tested at the end of the loop, the body of the loop is executed at least once.

Example 4.11 int d=1; do { printf (“%d\n”,d); ++d; } while (d<=10);

Break, Continue Statements

Break Statement

The break statement can appear in the switch statement and the loop statements. It causes the execution of the current enclosing switch case or the loop to terminate.

General Form: break; Example 4.12 for(loop=0;loop<50;loop++) { If (loop==10)

break; /* control will come out of the loop. */ printf("%d\n",loop);

}

Only numbers 0 through 9 are printed.

Continue Statement

The continue statement can only appear in the loop statements. It is used to terminate the current iteration. It skips rest of the statements in the body of the loop and begins the next iteration. General Form: continue; Example 4.13 for(loop=0;loop<100;loop++) { if (loop==50) continue; printf("%d\n",loop); }

Summary

 if statement is a condition based decision making statement.

 Ternary operator is more efficient form for expressing simple if statements.

 Switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups.

 Looping allows a program to repeat a section of code any number of times or until some condition occurs.

 for, while, and do-while statements are repetitive control structures available in C , that are used to carry out conditional looping.

 break statement is used to terminate the loop but continue statement skips the current iteration and continues the loop with the next iteration.

Test your Understanding

1. Which of the following statements are true?

a. An if statement must always include an else clause. b. An if statement may include only simple statements. c. if clause can contain another if statement.

2. When will the default case in switch statement be executed?

3. What is the output of the following piece of code? main( ) { int i=3; switch(i) { default : printf(“0”); case 1 : printf(“1”); break; case 2 : printf(“2”); break; case 3 : printf(“3”); break; } }

5. What is the output of the following code? while(1) { if (printf (“%d”, printf (“%d”))) break; else continue; } Answers: 1. c

2. Default case is executed, whenever evaluated expression does not matches with any of the case labels.

3. 3

4. While is an entry controlled loop (condition is checked in the beginning) and do..while is exit controlled loop (condition is checked at the end). The loop statements of do..while will get executed at least once.

Related documents