Control Statements

Introduction

A control statement is a statement that causes program statements to execute in a manner that doesn’t relate to the order it appears in the source code. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. C supports three types of control statements namely selection, repetition and jump statements.
Selection Statements
These are also known as branching, decision making, or conditional statements. These statements execute program statements depending upon a given condition. C supports two selection statements: if and switch. There are different forms of if statements: if only, if-else-if, and if-else-if ladder.

The if only statement

Allows your program to execute a single statement, or a block of statements enclosed between braces, if a given condition is true. Its general form (syntax) is:
if (expression)
statement 1
OR
if (expression)
{
statement 1
statement 2

statement n
}
If expression evaluates to true (any non-zero value), statement or the block of statements enclosed between braces is executed. If expression evaluates to false (0), these are not executed. In either case, execution then passes to whatever code follows the if statement. Expression can be any valid C expression and statement can be simple or compound or even another control statement. For example,
if(amount >= 1000)
discount = amount * 0.05;

The if else statement

When there is a need of executing a statement or a block of statements enclosed between braces if a condition is true and another statement or a block of statements enclosed between braces to be executed otherwise, then we use if–else statements. Its syntax is:
if (expression)
statement 1
else
statement 2
OR
if (expression)
{
statement 1
statement 2

statement n
}
else
{
statement 1
statement 2

statement n
}
If expression evaluates to true (any non-zero value), statement or the block of statements in the if body is executed. If expression evaluates to false (0), statement or the block of statements in the else body is executed. For example,
if(amount >= 1000)
discount = amount * 0.05;
else
discount = amount * 0.03;
Using if-else, you can specify an action to be performed both when the condition is true and when it is false.
The if else statement resembles with the conditional operator (?:). Conditional operator is a ternary operator (demands 3 operands), and is used in certain situations, replacing if-else statement. Its general form is:
exp1 ? exp2 : exp3;
If exp1 is true, exp2 is executed and whole expression is assigned with value of exp2. If the exp1 is false, then exp2 is executed, and whole expression is assigned with exp2 value. For example,
c = a > b ? a+b : a-b;
is equivalent to
if(a>b)
c=a+b;
else
c=a-b;

The if else if ladder statement

If we have the situation where there are different actions that are executed depending upon different conditions with same type of instance then if-else-if ladder is useful. Its syntax is:
if (expression)
statement 1
else if
statement 2
………….
else
statement n
OR
if (expression)
{
statement 1
statement 2

statement n
}
else if
{
statement 1
statement 2

statement n
}
…………………..
else
{
statement 1
statement 2

statement n
}
The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed. If the final else is not present, no actions take place if all other conditions are false. For example,
if(amount >= 5000)
discount = amount * 0.1;
else if (amount >= 4000)
discount = amount * 0.07;
else if (amount >= 3000)
discount = amount * 0.05;
else
discount = amount * 0.03;

Body of if
True
False
Expression1
Expression2
Body of else if
True
False
Expression n
Body of else if
True
False
Body of else
Statement following else body

The switch statement

It is a multiple branch selection statement, which successively tests the value of an expression against a list of integer or character constants. When a match is found, the statement(s) associated with that constant are executed. Its syntax is:
switch (expression) {
case constant1:
statement(s) break;
case constant2:
statement(s) break; ...
case constantn:
statement(s) break;
default:
statement(s) }
The expression must evaluate to an integer type. The value of expression is tested against the constants present in the case labels. When a match is found, the statement sequence, if present, associated with that case is executed until the break statement or the end of the switch statement is reached. The statement following default is executed if no matches are found. The default is optional, and if it is not present, no action takes place if all matches fail. For example,
char ch;
printf("Enter a character:");
scanf("%c", &ch); //ch = getchar();
switch(ch)
{
case 'a':
case 'A':
printf("EXCELLENT");
break;
case 'b':
case 'B':
printf("VERY GOOD");
break;
case 'c':
case 'C':
printf("GOOD");
break;
case 'd':
case 'D':
printf("SATISFACTORY");
break;
case 'e':
case 'E':
printf("FAIL");
break;
default:
printf("Wrong entry!");
}
Things to remember with switch:
 A switch statement can only be used to test for equality of an expression. We cannot check for other comparisons like <, <=, >, >=
 switch expression must evaluate to an integral value
 No two case constants can be same
 Omission of a break statement causes execution to go to next case label
 The default label is executed when no case constants matches the expression value
Fig: Flow-chart of switch statement
First case body
True
False
Expression result equals first-case constant
Second case body
True
False
Expression result equals second-case constant
nth case body
True
False
Expression result equals nth-case constant
Default body
Statement following
switch

Repetition Statements

Repetition is the process of executing a statement or a block of statements enclosed between braces more than one time as long as some condition remains true. Repetition in C can be implemented using three control statements: for, while, and do – while statements. These statements are also known as iteration or looping statements.
The for statement
When we have the fixed number of iterations known then we use for loop (normally, while loop is also possible). Its basic syntax is:
for(expr1; expr2; expr3)
statement1
OR
for(expr1; expr2; expr3)
{
statement 1
statement 2

statement n
}
First before loop starts, the initialization (expr1) is executed that initializes the variable or variables in the loop. Second the condition (expr2) is evaluated, if it is true, the statement (s) in the body of for loop will be executed. Finally, the increment/decrement (expr3) will be executed, and the condition (expr2) will be evaluated, this continues until the condition (expr2) is false, at which point control passes to next statement following for loop. For example,
int i, s = 0;
for(i = 0; i <= 10; i++)
s = s + i;
printf("Sum = %d", s);

We can use comma operator for multiple initializations and multiple processing of loop control variables in for statement. For example
for (sum = 0, i = 1; i <= n; i++)
sum += i;
You can omit, any of the three expression of the for statement. However, semicolons must be present. If your remove all three expressions like for(; ;), it becomes infinite loop. You can also omit first expression and initialize it before the loop as follows.
int digit = 0;
for ( ; digit <= 9 ;digit++ )
printf("%d\n", digit);
exp1
True
False
exp2 ?
Body of for
Statement following for body
exp3

The while statement
When we do not know the number of iterations in advance then we use while loop (normally, for loop is also possible). Its basic syntax is:
while(expression)
statement 1
OR
while(expression)
{
statement 1
statement 2

statement n
}
Here while body is executed as long as the expression evaluates to true. First expression is evaluated. If expression is nonzero (true), then body is executed and control is passed back to the beginning of the while statement, otherwise control passes to next statement following the while statement. The statement inside the while loop must include some feature that eventually alters the value of the expression, thus providing a stopping condition for the loop. For example,
int i = 1, s = 0;
while (i <= 10)
{
s = s + i;
i++;
}
printf("Sum = %d", s);
Aberdeen Int’l College Tribhuvan University B.Sc.CSIT
Nawaraj Paudel Page 13 Control Statements
Fig: Flow-chart of while statement
The do-while statement
Similar to the while statement but condition is tested after the body of the loop is performed
Its basic syntax is:
do
statement1
while(expression);
OR
do
{
statement 1
statement 2

statement n
} while(expression);
First body of do-while is executed, and expression is evaluated. If the value of expression is nonzero (true), then control passes back to the beginning of the do statement and process repeats itself. When expression is zero (false), control passes to next statement following the do-while statement. For example,
True
False
expression ?
Body of while
Statement following while body

int i = 1, s = 0;
do
{
s = s + i;
i++;
}while(i <= 10);
printf("Sum = %d", s);
Note that a semicolon is present after the closing parenthesis of the expression. Also note that loop body will always be executed at least once, since the test for repetition does not occur until the end of the first pass through the loop. The do-while is most appropriate when the body associated with the loop must be executed at least once.
Fig: Flow-chart of do-while statement

Comparison of three loops

 Because of the features that are built into the for statement, it is particularly well suited for the situations in which the number of passes is known in advance.
 The while loop is used when the number of passes is not known in advance.
 Use do-while loop when you want the loop body to execute at least once for the first time regardless of the outcome of the condition.
 for and while are called entry-controlled loops and do-while is called exit-controlled loop.
True
False
expression ?
Body of do while
Statement following do-while body

Nested loops

Like selection statements, a loop can be nested within another. The inner and outer loops need not be same. It is essential, however, that one loop be completely embedded within the other—there can be no overlap. When one loop is nested inside another loop, the inner loop is first terminated and again restarted when the first loop starts for the next incremented value. The outer loop is terminated last. For example,
for(i=0;i<10;i++)
{
printf(“Hi”)
for(j=0;j<5;j++)
printf(“Hello”);
}

Nested Control Statements

Nested control statements can also involve both loops and selection statements. Thus, a loop can be nested within a selection statement, and a selection statement can be nested within a loop. Moreover, we can nest any control flow statement (selection and looping statement) within another. For example, the code fragment below prints natural numbers those are either divisible by 3 or divisible by 5 up to the number n.
for (i = 1; i <= n; i++)
if (i%3==0 || i%5 == 0)
printf("%d\n",i);

Jump Statements

For the transfer of control from one part to another, C also supports various jump statements. These are break, continue, goto, and return (discussed later).
The break statement
The use of break statement causes the immediate termination of a loop (for, while, or do-while) and switch from the point of break statement. It then passage program control to the statement following the loop or switch. In case of nested loops if break statement is in inner loop only the inner loop is terminated. For example,
for( int i=1; i<= 10; i++ )
{
if( i == 5 )
break;
printf(" i=%d”, i );
}
printf("oho char pachhi khai ta”);

The continue statement

Use of continue statement skips the remaining statements in the body of a loop and proceeds with the next iteration of the loop. In case of while and do-while loops, test expression is evaluated immediately after the continue statement is executed and in case of for loop, increment/decrement expression is executed and then the test expression is evaluated. For example,
for(i=0;i<10;i++)
{
if(i>5&&i<8)
continue;
printf("%d\n",i);
}

The goto statement

The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. In its general form, the goto statement is written as
goto label;
Here, label is an identifier that is used to label the target statement to which control will be transferred. It is considered a harmful construct because it causes an unconditional jump to a labeled statement. For example,
int num;
here: // this is label for goto
printf("\nEnter a positive number ");
scanf("%d",&num);
if(num < 0)
goto here; //this statement transfers the control to label here
printf("\nNumber = %d",num);
 

No comments:

Post a Comment