BIT104 SLM Library - SLM - Unit 05

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Principles of C Programming Unit 5

Unit 5 Control Statements and Decisions Making

Structure:
5.1 Introduction
Objectives
5.2 The goto Statement
5.3 The if statement
The if-else Statement
Nesting of if Statements
5.4 The switch Statement
5.5 The while Loop
5.6 The do…while Loop
5.7 The for Loop
The nesting of for Loops
5.8 The break Statement and continue Statement
5.9 Summary
5.10 Terminal Questions
5.11 Answers
5.12 Exercises

5.1 Introduction
In the previous unit, we discussed the data types that are supported in C
and the types of Input/output operators available in C. This unit will enable
us to use the various types of control statements for making a decision in
C programs.
C program is set of statements which are normally sequentially executed in
the order in which they appear. Statements are the set of instructions.
Following is the example of simple statement:
printf(“Hello World”);
y=x+1;
Block statements are simply groups of related statements that are treated
as a unit. The statements that make up a block are logically bound together.
Block statements are also called compound statements. A block is begun
with a {and terminated by its matching}. Block statements are used to group
multiple statements in branching and looping statements. Following is the
example of a block statement:
Sikkim Manipal University B2074 Page No.: 95
Principles of C Programming Unit 5

{
sum = sum + i;
i++;
}
By default, statements are executed in sequence, one after another. We can,
however, alter that sequence of flow of instruction by using control flow
constructs. Control flow instructions are of two types: Branching statements
and iteration statements.
Branching statements are used to transfer the program flow control from
one point to another. They can be categorized as conditional branching and
unconditional branching.
In the conditional controlled branching, a condition is given. This condition is
logically evaluated. Depending upon whether the condition evaluates to
either the true or the false state, appropriate branching is taken. Conditional
branching statement in C language are If, If-else, switch and conditional
operator statements. We already discussed about conditional operator
statement in unit 3.
Unconditional branching means transferring the control of the program to a
specified statement without any conditions. The goto, break, continue and
return statements are unconditional branching statement. We will discuss
goto, break and continue statement in this unit.
Iterations (Looping) is process of repeating statement or set of statements
again and again until specified condition hold true. We will also discuss
about the loops in this unit. Loops generally consist of two parts: one or
more control expressions which control the execution of the loop, and the
body, which is the statement or a set of statements that is executed over
and over again. C language provides following three looping statements:
1. while statement
2. do-while statement
3. for statement
In C language, a true/false condition can be represented as an integer. In C,
“false'' is represented by a value of 0 (zero), and “true'' is represented by
any value that is nonzero, preferably by value of 1(Since there are many
nonzero values)

Sikkim Manipal University B2074 Page No.: 96


Principles of C Programming Unit 5

Objectives:
After studying this unit, you should be able to:
 discuss how to control the flow of execution of statements using control
flow instruction.
 explain branch unconditionally from one point to another in the program.
 discuss various looping statement available in C.
 illustrate how to exit from the loop depending on some condition.
 describe how to break the current iteration and continue with next
iteration of loop.

5.2 The goto Statement


The goto statement in used to branch unconditionally from one point to
another in the program. Since C has a rich set of control structures and
allows additional control using break and continue, there is little need for
goto, such as jumping out of a set of deeply nested loops.
The goto statement requires a label for operation of to identify the place
where the branch is to be made. A label is a valid identifier followed by a
colon. The label is placed immediately before the statement where the
control is to be transferred. Furthermore, the label must be in the same
function as the goto that uses it— we cannot jump between functions. The
general form of the goto statement is shown below:

goto label; label:


----------- statement;
----------- ------------
----------- ------------
label: -------------

statement; goto label;(i) Forward jump (ii) Backward jump


The label can be anywhere in the program either before the goto or after the
goto label; statement.
During execution of the program when a statement like
goto first;

Sikkim Manipal University B2074 Page No.: 97


Principles of C Programming Unit 5

is met, the flow of control will jump to the statement that immediately follows
the label first. This happens unconditionally.
Note that a goto is used to break the normal sequential execution of the
program unconditionally. If the label is before the statement goto label; a
loop will be formed and some statements will be executed repeatedly. Such
a jump is known as a backward jump. On the other hand, if the label is
placed after the goto label; some statements will be skipped and the jump is
known as the forward jump.
We can use goto at the end of a program to direct the control to go to the
input statement, which read further data. Consider the following example
program:
Program 5.1: Program to find square root using unconditional
branching goto
main()
{
double a, b;
read:
printf(“enter the value of a\n”);
scanf(“%f”, &a);
if (a<0) goto read;
b=sqrt(a);
printf(“%f %f \n”,a, b);
goto read;
}

The program uses two goto statements, one at the end, after printing the
results to transfer the control back to the input statements and the other to
skip any further computation when the number is negative. This program
evaluates the square root of a series of numbers read from the terminal. At
the end of program there is the second unconditional goto statement and
the control is always transferred back to the input statement. In fact, this
program puts the computer in a permanent loop known as an infinite loop.
To avoid such kind of situation, it is preferable not to use a goto statement.

Sikkim Manipal University B2074 Page No.: 98


Principles of C Programming Unit 5

Self Assessment Questions


1. The goto requires a _________ in order to identify the place where the
branch is to be made.
2. goto is an unconditional branching statement. (True/False)

5.3 The if statement


In C, the simplest way to modify the control flow of a program is with an if
statement. It can be used to evaluate the conditions as well as to make the
decision on whether the block of code controlled by if statement is going to
be executed. If is a conditional branching statement. General form of if
statement is:
if (expression)
{
statement(‘s)
}
where expression is any expression and statement(‘s) may be a single
statement or a group of statements. If the expression evaluates to true, the
statement (‘s) will be executed; otherwise the statement (‘s) will be skipped
and the execution will jump to the next statement after closing braces. (We
do not need to, and should not, put a semicolon after the closing brace,
because the series of statements enclosed by braces is not itself a simple
expression statement.) If statement illustrated in the figure 5.1.

False
expression
?

True

Statement (‘s)

Next-
Statement

Figure 5.1: Flow Chart of Simple If - statement

Sikkim Manipal University B2074 Page No.: 99


Principles of C Programming Unit 5

Example 5.1: Compare two variables x and max; if x is greater than max, x
gets assigned to max.
if(x > max)
max = x;
Program 5.2: Program to check two numbers for equality.

# include < stdio.h >


void main ( )
{
int x, y;
printf (“Enter two numbers :”);
scanf (“%d %d”, &x,&y);
if ( x == y )
printf( "Both numbers are equal" ) ;
}

5.3.1 The if-else Statement


if statement may also optionally contain a second statement, the “else
clause,'' which is to be executed if the condition is not met. The general
syntax of an if statement is:
if( expression )
{
statement (‘s) -1
}
else
{
statement (‘s) -2
}
If the expression evaluates to true, the first statement or block of statements
following the if statement is executed and if the expression evaluates to ‘not
true’ that is false, the second statement or block of statements (following the
keyword else) is executed. This is illustrated in the figure 5.2.

Sikkim Manipal University B2074 Page No.: 100


Principles of C Programming Unit 5

True False
expression
?

Statement (‘s)-1 Statement (‘s) -2

Next-
Statement

Figure 5.2: Flow Chart of If -else statement


(Note: Next-Statement is the statement after if –else statement.)

Example 5.2: In this example, we can compute a meaningful average only if


n is greater than 0; otherwise, we print a message saying that we cannot
compute the average.
if(n > 0)
average = sum / n;
else {
printf("can't compute average\n");
average = 0;
}
(Note it is not compulsory to enclosed single statement within braces).

Sikkim Manipal University B2074 Page No.: 101


Principles of C Programming Unit 5

Program 5.3: To find whether a number is negative or positive

#include < stdio.h >


void main ( )
{
int num;
printf (“Enter the number”);
scanf (“%d”, &num);
if (num < 0)
printf (“The number is negative”)
else
printf (“The number is positive”);
}

5.3.2 Nesting of if Statements


It is also possible to nest one if statement inside another. In many cases, a
program has to make a series of related decisions. For this purpose, we can
use nested if statements.
Example 5.3: Decide roughly which quadrant of the compass we are
walking into, based on an x value which is positive if we are walking east,
and a y value which is positive if we are walking north, here is the code:

if(x > 0)
{
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
}
else {
if(y > 0)
printf("Northwest.\n");
else printf("Southwest.\n");
}
When we have one if statement (or loop) nested inside another, it's a very
good idea to use explicit braces {}, as shown, to make it clear (both to us
and to the compiler) how they are nested and which else goes with which if.
It is also a good idea to indent the various levels, also as shown, to make

Sikkim Manipal University B2074 Page No.: 102


Principles of C Programming Unit 5

the code more readable to humans. Why do both? We use indentation to


make the code visually more readable to ourself and other humans, but the
compiler doesn't pay attention to the indentation (since all whitespace is
essentially equivalent and is essentially ignored).

Here is an example of another common arrangement of if and else.


Suppose we have a variable grade containing a student's numeric grade,
and we want to print out the corresponding letter grade. Here is the code
that would do the job:

if(grade >= 90)


printf("A");
else if(grade >= 80)
printf("B");
else if(grade >= 70)
printf("C");
else if(grade >= 60)
printf("D");
else printf("F");
Depending on which of the condition is true, exactly one of the five printf
calls is executed. Each condition is tested in turn, and if one is true, the
corresponding statement is executed, and the rest are skipped. If none of
the conditions is true, we fall through to the last one, printing “F''.
In the cascaded if/else/if/else/... chain, each else clause is another if
statement. This may be more obvious at first if we reformat the example,
including every set of braces and indenting each if statement relative to the
previous one:

if(grade >= 90)


{
printf("A");
}
else {
if(grade >= 80)
{
printf("B");
}
else {
if(grade >= 70)
Sikkim Manipal University B2074 Page No.: 103
Principles of C Programming Unit 5

{
printf("C");
}
else {
if(grade >= 60)
{
printf("D");
}
else {
printf("F");
}
}
}
}
By examining the code this way, it should be obvious that exactly one of the
printf calls is executed, and that whenever one of the conditions is found
true, the remaining conditions do not need to be checked and none of the
later statements within the chain will be executed.
Program 5.4: Program to display the largest of three numbers
#include<stdio.h>
main()
{
int a,b,c,big;
printf (“Enter three numbers”);
scanf (“%d %d %d”, &a, &b, &c);
if (a>b) // check whether a is greater than b if true then
if(a>c) // check whether a is greater than c
big = a ; // assign a to big
else big = c ; // assign c to big
else if (b>c) // if the condition (a>b) fails check whether b is greater than
c
big = b ; // assign b to big
else big = c ; // assign C to big
printf (“Largest of %d,%d&%d = %d”, a,b,c,big);
}

Sikkim Manipal University B2074 Page No.: 104


Principles of C Programming Unit 5

Self Assessment Questions


3. the If is an unconditional branching statement (True/False)
4. Given x = 0, will the arithmetic operations inside the following if
statement be performed?
if (x != 0)
y = 123 / x + 456;

5.4 The switch Statement


C has a built-in multiple-branch selection statement, called switch, which
successively tests the value of an integer expression against a list of integer
or character constants. When a match is found, the statements associated
with that constant are executed.
In the last section, we see that nested if statements are used when there
are successive, related decisions to be made. However, the nested if
statements can become very complex in case there are many decisions to
be made. The switch statement, which can be used as an alternate to long if
statements that compare a variable to several "integral" values ("integral"
values are simply values that can be expressed as an integer, such as the
value of a char).
The general form of the switch statement is:
switch ( <expression> ) {
case value-1:
statement(‘s)
break;
case value-2:
statement(‘s)
break;
...
default:
statement(‘s)
break;
}
The expression must evaluate to an integer type. Value1, Value2 … are
constants or constant expressions (evaluates to an integral constant). Each
of these values should be unique within the switch statement. Statement (‘s)
are statement lists and may contain zero or more statements.

Sikkim Manipal University B2074 Page No.: 105


Principles of C Programming Unit 5

The switch statement works as follows:


1) Integer expression is evaluated.
2) The value of the expression given into switch is compared to the case-
value following each of the cases. When one case-value matches the
value of the expression, execute the statements for that case. If any of
the case-value a match is not found, execute the default statement.
3) Terminate switch when a break statement is encountered or by “falling
out the end”.
The break is used to break out of the case statements. Break is a keyword
that breaks out of the code block, usually surrounded by braces, which it is
in. In this case, break prevents the program from falling through and
executing the code in all the other case statements.
The default case is optional, but it is wise to include it as it handles any
unexpected cases. It can be useful to put some kind of output to alert that
the code is entering the default case if we do not expect it to.
An important thing to note about the switch statement is that the case
values may only be constant integral expressions. It is not legal to use case
like this:
int a = 10;
int b = 10;
int c = 20;
switch ( a ) {
case b:
/* Code */
break;
case c:
/* Code */
break;
default:
/* Code */
break;
}
The switch statements serve as a simple way to write long if statements.
The switch statements can be used to process input from a user that is for
menu selection.
Sikkim Manipal University B2074 Page No.: 106
Principles of C Programming Unit 5

Program 5.5: The Simple calculator program, which shows use of


switch statement.

// Simple Calculator
#include <stdio.h>
main()
{
int choice, numb1, numb2, ans;
printf("enter in two numbers -->");
scanf("%d %d", &numb1, &numb2); // Enter two numbers
printf(“Calculator Options: \n ”)
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("Enter the choice\n");
scanf("%d", &choice); // Enter Option
switch( choice ) {
case 1: //performs addition if choice==1
ans = numb1 + numb2;
break;
case 2: // performs subtraction if choice == 2
ans = numb1 - numb2;
break;
default: printf("Invalid option selected\n");
ans =-1;
}
printf(“Answer is %d ", ans );
}

We should remember the following points while using a switch statement:


1. The switch expression must be an integral type.
2. Case values must be unique (How to decide otherwise?)
3. Case values must be constants or constant expressions.
4. Case values must end with semicolon.
5. The break transfers the control out of the switch statements.
6. The break statement is optional. In that case, the computer continues to
execute the statements following the selected case until the end of the
switch statement.
7. Switch statement only tests for equality.
Sikkim Manipal University B2074 Page No.: 107
Principles of C Programming Unit 5

8. The default case is optional. If present, it will be executed when the


expression does not find a matching case label.
9. There can be at most one default label.
10. The default may be placed anywhere but usually placed at the end.
11. We can nest switch statements.
Self-Assessment Questions
5. The Switch statement only tests for equality. (True/False)
6. If _________ case present in switch statement, it will be executed
when the expression does not find a matching case values.
7. We cannot nest switch statements. (True/False)

5.5 The while Loop


Loops generally consist of two parts: one or more control expressions which
control the execution of the loop, and the body, which is the statement or set
of statements which is executed over and over.
The most basic loop in C is the while loop. The purpose of the while
keyword is to repeatedly execute a statement over and over while a given
condition is true. When the condition of the while loop is no longer logically
true, the loop terminates and program execution resumes at the next
statement following the loop. The general form of the while statement is:
while (expression)
{
Statement (‘s);
}
Here the expression is the condition of the while statement. This expression
is evaluated first. If the expression evaluates to a nonzero value, then the
statement (‘s) is executed. After that, expression is evaluated once again.
The statement (‘s) is then executed one more time if the expression still
evaluates to a nonzero value. This process is repeated over and over until
expression evaluates to zero, or logical false. The idea is that the code
inside the loop, (statement (‘s); above) will eventually cause expression to
be logically false the next time it is evaluated, thus terminating the loop. The
while loop is illustrated in figure 5.3. (Note: Next-statement is the statement
after while loop).

Sikkim Manipal University B2074 Page No.: 108


Principles of C Programming Unit 5

False
expression
?

True

Statement (‘s)

Next-
Statement

Figure 5.3: Flow chart of While loop

Here before executing the body of the loop that is statement (’s), the
expression evaluated. Therefore it is called an entry-controlled loop.

Example 5.4: The following example uses a while loop to continually read,
and then display, character input while the character input does not equal
‘\n’ (Enter key / new line character).
int c;
c = getchar();
while(c != ‘\n’)
{
putchar(c);
c = getchar();
}

Example 5.5: We can use while loop (as shown below), to print n (integer
variable holding the number of blank lines) blank lines on the screen.
while(n > 0)
{
printf("\n");
n = n - 1;
}

Sikkim Manipal University B2074 Page No.: 109


Principles of C Programming Unit 5

When n becomes zero, the loop finishes and control “falls out'' of while loop.

We use a while loop when we have a statement or group of statements


which may have to be executed a number of times to complete their task.
The controlling expression represents the condition “the loop is not done'' or
“there's more work to do.'' As long as the expression is true, the body of the
loop is executed. When the expression becomes false, the task is done, and
the rest of the program (beyond the loop) can proceed. If the expression
evaluates to “false'' before the very first trip through the loop, we make zero
trips through the loop. In other words, if the task is already done (if there's
no work to do) the body of the loop is not executed at all.

Program 5.6: Program to find largest of n numbers

Main()
{
int num, large, n, i;
clrscr();
printf("enter number of numbers \n");
scanf(“%d”,&n);
large=0;
i=0;
while(i<n)
{
printf("\n enter number ");
scanf(“%d”, &num);
if(large<num)
large=num;
i++;
}
printf("\n large = %d”, large);
}

Sikkim Manipal University B2074 Page No.: 110


Principles of C Programming Unit 5

Program 5.7: Program to evaluate sine series sin(x)=x-x^3/3!+x^5/5!-


x^7/7!+----- depending on accuracy

# include<stdio.h>
# include <math.h>
void main()
{
int n, i=1,count;
float acc, x, term, sum;
printf("enter the angle\n");
scanf(“%d”, &x);
x=x*3.1416/180.0;
printf(“\nenter the accuracy)";
scanf(“%f”, &acc);
sum=x;
term=x;
while ((fabs(term))>acc)
{
term=-term*x*x/((2*i)*(2*i+1));
sum+=term;
i++;
}
printf"\nsum of sine series is %f", sum);
}

Self Assessment Questions


8. Can the following while loop print out anything?
int i = 10;
while (i<10){
printf(“%c”, i++);
}
9. while is an entry-controlled loop. (True/False)

5.6 The do-while Loop


The do-while loop is used in situations when the statements (body) in the
loop are guaranteed to be executed at least once before the expression is
tested. In the while statement that we have seen, the conditional expression

Sikkim Manipal University B2074 Page No.: 111


Principles of C Programming Unit 5

is set at the very top of the loop. However, in this section, we are going to
see another statement used for looping, do-while, which puts the expression
at the bottom of the loop. Therefore, The while loop is called an entry-
controlled loop and do-While loop is called an exit-controlled loop. The do-
while loop takes the following form:
do
{
Statement(‘s)
}
while (expression);
Here, the statements inside the statement block are executed once, and
then expression is evaluated in order to determine whether the looping is to
continue. If the expression evaluates to a nonzero value, the do-while loop
continues; otherwise, the looping stops and execution proceeds to the next
statement following the loop. On using the do-while loop, the body of the
loop is always executed at least once irrespective of the expression. The
do-while loop is illustrated in figure 5.4. (Note: Next-statement is the
statement after while loop).

Statement (‘s)

True

expression
?

False
Next-
Statement

Figure 5.4: Flow chart of do While loop

Sikkim Manipal University B2074 Page No.: 112


Principles of C Programming Unit 5

Program 5.8: A program to print the multiplication table from 1 x 1 to


10 x 10 as shown below using do-while loop.
1 2 3 4 …………………… 10
2 4 6 8 …………………… 20
3 6 9 12 …………………… 30
4 …………………… 40
. .
. .
. .
10 100

// Program to print multiplication table


main()
{
int rowmax=10,colmax=10,row,col,x;
printf(" Multiplication table\n");
printf("......................................\n");
row=1;
do
{
col=1;
do
{
x=row*col;
printf(“%4d”, x);
col=col+1;
}
while (col<=colmax);
printf(“\n”);;
row=row+1;
}
while(row<=rowmax);
Printf(".......................................................................................................
.\n");
}

Note: There is a semi-colon behind the while line.

Sikkim Manipal University B2074 Page No.: 113


Principles of C Programming Unit 5

Self Assessment Questions


10. On using the ________, the body of the loop is always executed at
least once irrespective of the expression.
11. The do-while is an entry-controlled loop. (True/False)

5.7 The for Loop


C provides the for statement as another form for implementing loops. The
for loop is used to repeat the execution of set of statements for a fixed
number of times. The for loop is also an entry-controlled loop. The syntax of
a for loop is:
for(expr1; expr2; expr3)
{
statement (‘s)
}
The loops we have seen so far are typical of most repetition structures in
that they have three loop control components in addition to the loop body:
1. Initialization of the loop control variable (i.e. loop variable or control
variable),
2. Test of the loop repetition condition, and
3. Change (update) of the loop control variable.
The three expressions in for loop encapsulate these components: expr1
sets up the initial condition, expr2 tests whether another trip through the
loop should be taken, and expr3 increments or updates things after each trip
through the loop and prior to the next one. The for loop is illustrated in the
figure 5.5.

Initialization Statement Update Statement

expression ? True

False Statement (‘s)

Next-Statement

Figure 5.5: Flow Chart of for loop

Sikkim Manipal University B2074 Page No.: 114


Principles of C Programming Unit 5

Example 5.6: Consider the following:


for (i = 0; i < 10; i = i + 1)
printf("i is %d\n", i);
In the above example, we had i = 0 as expr1 is initialization statement,
i < 10 as expr2 is test expression, i = i + 1 as expr3 is update statement,
and the call to printf as statement, the body of the loop. for loop began by
setting i to 0, proceeded as long as i was less than 10, printed out i's value
during each trip through the loop, and added 1 to i between each trip
through the loop. When the compiler looks for loop, first, expr1 is evaluated.
Then, expr2 is evaluated, and if it is true, the body of the loop (statement) is
executed. Then, expr3 is evaluated to go to the next step, and expr2 is
evaluated again, to see if there is a next step. We can trace the execution of
the sample loop as shown in Table 5.1:
i=0 //initialization expr1 – in first iteration
Table 5.1: Output tracing for loop

Iteration i (After Update – i<10 (checking – Output


expr3) expr2) Statement -
printf
1st - TRUE i is 0
2nd 1 TRUE i is 1
3rd 2 TRUE i is 2
4th 3 TRUE i is 3
5th 4 TRUE i is 4
6th 5 TRUE i is 5
7th 6 TRUE i is 5
8th 7 TRUE i is 5
9th 9 TRUE i is 5
10th 10 TRUE i is 5
11th 11 FALSE -

Sikkim Manipal University B2074 Page No.: 115


Principles of C Programming Unit 5

During the execution of a for loop, the sequence is:


expr1
expr2
statement
expr3
expr2
statement
expr3
...
expr2
statement
expr3
expr2
All three expressions of for loop are optional. If we leave out expr1, there
simply is no initialization step, and the variable(s) used with the loop had
better have been initialized already. If we leave out expr2, there is no test,
and the default for the for loop is that another trip through the loop should be
taken (such that unless we break out of it some other way, the loop runs
forever). If we leave out expr3, there is no increment step.
The semicolons separate the three controlling expressions of for loop.
(These semicolons, by the way, have nothing to do with statement
terminators.) If we leave out one or more of the expressions, the semicolons
remain. Therefore, one way of writing a deliberately infinite loop in C is
for(;;)
...
The three expressions can be anything, although the loop will make most
sense if they are related and together form the expected initialize, test,
increment sequence.
It is also worth noting that for loop can be used in more general ways than
the simple, iterative examples we have seen so far. The “loop control
variable'' of for loop does not have to be an integer, and it does not have to
be incremented by an additive increment. It could be “incremented'' by a
multiplicative factor (1, 2, 4, 8, ...) if that was what we needed, or it could be
a floating-point variable, or it could be another type of variable which we
Sikkim Manipal University B2074 Page No.: 116
Principles of C Programming Unit 5

have not met yet which would step, not over numeric values, but over the
elements of an array or other data structure.
Example 5.7: The powers-of-two using for loop is:
int x;
for(x = 2; x < 1000; x = x * 2)
printf("%d\n", x);
The initialization expression of for loop can contain more than one
statement separated by a comma. For example,
for ( i = 1, j = 2 ; j <= 10 ; j++ )
There is no fundamental difference between the while and for loops. We can
rewrite for loop as a while loop, moving the initialize and increment
expressions to statements before and within the loop:
expr1;
while(expr2)
{
Statement (‘s)
expr3;
}
Similarly, given the general while loop
while(expr) {
statement (‘s) }

We could rewrite it as for loop:


for(; expr; ){
statement (‘s)}
Another contrast between for and while loops is that although the test
expression (expr2) is optional in for loop, it is required in a while loop. If we
leave out the controlling expression of a while loop, the compiler will
complain about a syntax error. To write a deliberately infinite while loop, we
have to supply an expression which is always nonzero. The most obvious
one would simply be while(1).
If it is possible to rewrite for loop as a while loop and vice versa, the
question that arises is why do they both exist and which one must be
chosen? In general, when we choose for loop, its three expressions should

Sikkim Manipal University B2074 Page No.: 117


Principles of C Programming Unit 5

all manipulate the same variable or data structure, using the initialize, test,
increment pattern. If they do not manipulate the same variable or do not
follow that pattern, it is preferable to use a while loop.
Program 5.9: A Program to find the factorial of a number
void main()
{
int M,N;
long int F=1;
clrscr();
printf(“enter the number\n”)";
scanf(“%d”,&N);
if(N<=0)
F=1;
else
{
for(M=1;M<=N;M++)
F*=M;
}
printf(“the factorial of the number is %ld”,F);
getch();
}
5.7.1 The Nesting of for Loops
Nesting of for loops, that is, one for statement within another for statement,
is allowed in C. For example, two loops can be nested as follows:
for(i=1;i<10;i++)
{
…….
…….
for(j=1;j<5;j++)
{
……
……
}
…….
}
………

Sikkim Manipal University B2074 Page No.: 118


Principles of C Programming Unit 5

5.8 The break Statement and continue Statement


The purpose of the break statement is to exit out of a loop (while, do while,
or for loop) or a switch statement. When a break statement is encountered
inside a loop, the loop is immediately exited and the program continues with
the statement immediately following the loop. When the loops are nested,
the break would only exit from the loop containing it. That is, the break
would exit only a single loop.
Syntax : break;

Program 5.10: Program to illustrate the use of break statement.


void main ( )
{
int x;
for (x=1; x<=10; x++)
{
if (x==5)
break; /*break loop only if x==5 */
printf(“%d”, x);
}
printf (“\nBroke out of loop”);
printf( “at x =%d“);
}

The above program displays the numbers from 1 to 4 and prints the
message “Broke out of loop when 5 is encountered.

The continue Statement


The continue statement is used to continue the next iteration of the loop by
skipping a part of the body of the loop (for, do-while or while loops).
Unlike the break which causes the loop to be terminated, the continue,
causes the loop (for, do-while or while loops) to be continued with the next
iteration after skipping any statements in between. With “continue;” it is
possible to skip the rest of the commands in the current loop and start from
the top again. The continue statement does not apply to a switch, like a
break statement.
Syntax: continue;

Sikkim Manipal University B2074 Page No.: 119


Principles of C Programming Unit 5

Program 5.11: Program to illustrate the use of continue statement.

void main ( ) {
int x;
for (x=1; x<=10; x++)
{ if (x==5)
continue; /* skip remaining code in loop
only if x == 5 */
printf (“%d\n”, x);
}
printf(“\nUsed continue to skip”);
}

The above program displays the numbers from 1to 10, except the number 5.

Self-Assessment Questions
12. The for loop is an exit-controlled loop. (True/False)
13. Do the following two for loops have the same number of iterations?
for (j=0; j<8; j++);
for (k=1; k<=8; k++);
14. The _________statement is used to continue the next iteration of the
loop by skipping a part of the body of the loop.

5.9 Summary
Let us recapitulate important points discussed in this unit:
 In C by default, statements are executed in sequence, one after another.
We can, however, modify that sequence by using control flow constructs.
 C language possesses decision making capabilities and supports the
following statements known as the control or decision making
statements: goto, if, switch.
 The goto statement is used to branch unconditionally from one point to
another in the program.
 The simplest way to modify the control flow of a program based on
condition is with if statement. Switch statements serve as a simple way
to write long if statements when the requirements are met.
 The most basic loop in C is the while loop. A while loop has one control
expression, and executes as long as that expression is true.

Sikkim Manipal University B2074 Page No.: 120


Principles of C Programming Unit 5

 do..while loop is used in a situation where we need to execute the body


of the loop before the test is performed.
 The for loop is used to execute the set of statements repeatedly for a
fixed number of times. It is an entry controlled loop.
 Break statement is used to exit any loop. Unlike the break which causes
the loop to be terminated, continue statement, causes the loop to be
continued with the next iteration after skipping any statements in
between.

5.10 Terminal Questions


1. Explain different types of if statements with examples.
2. Explain the syntax of switch statement with an example.
3. Consider the following program segment:
x=1;
y=1;
if (n>0)
x=x+1;
y=y-1;
printf(“%d %d”,x,y);

What will be the values of x and y if n assumes a value of (a) n=1 and
(b) n=0.
4. Rewrite the following without using compound relation:
if (grade<=59 && grade>=50)
second = second +1;
5. Write a program to check whether an input number is odd or even.
6. Write a C program to calculate the average of 10 numbers.
7. Write the output that will be generated by the following C program:
void main()
{
int i=0, x=0;
do
{
if (i%5 == 0)
{

Sikkim Manipal University B2074 Page No.: 121


Principles of C Programming Unit 5

x++;
printf(“%d\t”,
x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
}

5.11 Answers
Self-Assessment Questions
1. label
2. true
3. false
4. No
5. true
6. default
7. false
8. No
9. true
10. do-while
11. false
12. false
13. yes
14. continue
Terminal Questions
1. In C, the simplest way to modify the control flow of a program is with if
statement. (Refer section 5.3 for more detail)
2. C has a built-in multiple-branch selection statement, called switch,
which successively tests the value of an integer expression against a
list of integer or character constants. (Refer section 5.4 for more detail)
3. (a) x=2, y=0
(b) x=1, y=0
(Refer section 5.3 for more detail about if statement)

Sikkim Manipal University B2074 Page No.: 122


Principles of C Programming Unit 5

4. if (grade<=59)
if (grade>=50)
second = second+1;
(Refer section 5.3 for more detail about if statement)
5. void main()
{
int no;
printf(“enter a number\n”);
scanf(“%d”,&no);
if (no%2==0)
printf(“even number\n”);
else printf(“odd number\n”);
}
(Refer section 5.3 for more detail about if statement)
6.
main()
{
int count; /* DECLARATION OF
float sum, average, number; VARIABLES */
sum = 0; / * INITIALIZATION OF
count = 0; VARIABLES*/
printf(“Enter Ten numbers: \n”)
while (count<10)
{
scanf(“%f”, &number);
sum = sum + number;
count = count + 1;
}
average = sum / N;
printf(“Sum = %f \n“, N, sum);
printf(“Average = %f”, average);
}
Output
Enter Ten numbers:
1
Sikkim Manipal University B2074 Page No.: 123
Principles of C Programming Unit 5

2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
Sum= 38.799999
Average= 3.880000
(Refer section 5.5 - for more detail on while statement)

7. 1. 2 3 4
x=4
(Refer section 5.3 for more detail about if statement - and for while
statement - Refer section 5.5)

5.12 Exercises
1. Write a program to check whether a given number is odd or even using
switch statement.
2. Write a program to find the roots of a quadratic equation.
3. Compare the following statements
a) while and do…while
b) break and continue
4. Write a program to compute the sum of digits of a given number using
while loop.
5. Write a program that will read a positive integer and determine and
print its binary equivalent using do-while loop.
6. The numbers in the sequence
1 1 2 3 5 8 13 ………..
are called Fibonacci numbers. Write a program using do-while loop to
calculate and print the first n Fibonacci numbers.

Sikkim Manipal University B2074 Page No.: 124


Principles of C Programming Unit 5

7. Find errors, if any, in each of the following segments. Assume that all
the variables have been declared and assigned values.
(a)
while (count !=10);
{
count = 1;
sum = sum + x;
count = count + 1;
}
(b)
do;
total = total + value;
scanf(“%f”, &value);
while (value ! =999);
8. Write programs to print the following outputs using for loops.
(a) 1 b) 1
22 2 2
333 3 3 3
4444 4 4 4 4
9. Write a program to read the age of 100 persons and count the number
of persons in the age group 50 to 60. Use for and continue statements.

Reference and further reading:


1. Balaguruswami, “Programming In Ansi C 5E” Tata McGraw-Hill
2. Ajay Mittal (2010), “Programming In C: A Practical Approach”, Published
by Pearson education.

Sikkim Manipal University B2074 Page No.: 125

You might also like