Friday 23 November 2012

Control Statements in C

Programming with C Unit 7

Unit 7 Control Statements
Structure
7.0 Introduction
7.1 The while loop
Self Assessment Questions
7.2 The do…while loop
Self Assessment Questions
7.3 The for loop
Self Assessment Questions
7.4 The nesting of for loops
7.5 The break statement
Self Assessment Questions
7.6 The continue statement
Self Assessment Questions
7.7 Summary
7.8 Terminal Questions
7.9 Answers to Self Assessment Questions
7.10 Answers to Terminal Questions
7.11 Exercises
7.0 Introduction
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. A while loop has one conditional expression, and executes
as long as that condition is true.
As far as C is concerned, a true/false condition can be represented as an
integer. (An integer can represent many values; here we care about only
Programming with C Unit 7
Sikkim Manipal University Page No. 97
two values: “true'' and “false.'' The study of mathematics involving only two
values is called Boolean algebra, after George Boole, a mathematician who
refined this study.) In C, “false'' is represented by a value of 0 (zero), and
“true'' is represented by any value that is nonzero. Since there are many
nonzero values (at least 65,534, for values of type int), when we have to
pick a specific value for “true,'' we'll pick 1.
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
body of the loop for a specified number of times. The break statement is
used to exit any loop. However, unlike break, the continue causes the
control to go directly to the testcondition
and then to continue the iteration
process.
Objectives
At the end of this unit, you will be able to:
· Repeat the execution of statements by checking the condition before
the loop body is executed.
· Repeat the execution of statements by checking the condition at the
end of the loop.
· Exit from the loop depending on some condition.
· Break the current iteration and continue with next iteration of loop.
7.1 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. A while loop has one control
expression, and executes as long as that expression is true. Here before
executing the body of the loop, the condition is tested. Therefore it is called
Programming with C Unit 7
Sikkim Manipal University Page No. 98
an entrycontrolled
loop. The following example repeatedly doubles the
number 2 (2, 4, 8, 16, ...) and prints the resulting numbers as long as they
are less than 1000:
int x = 2;
while(x < 1000)
{
printf("%d\n", x);
x = x * 2;
}
(Once again, we've used braces {} to enclose the group of statements which
are to be executed together as the body of the loop.)
The general syntax of a while loop is
while( expression )
statement(s)
A while loop starts out like an if statement: if the condition expressed by the
expression is true, the statement is executed. However, after executing the
statement, the condition is tested again, and if it's still true, the statement is
executed again. (Presumably, the condition depends on some value which
is changed in the body of the loop.) As long as the condition remains true,
the body of the loop is executed over and over again. (If the condition is
false right at the start, the body of the loop is not executed at all.)
As another example, if you wanted to print a number of blank lines, with the
variable n holding the number of blank lines to be printed, you might use
code like this:
while(n > 0)
{
printf("\n");
Programming with C Unit 7
Sikkim Manipal University Page No. 99
n = n 1;
}
After the loop finishes (when control “falls out'' of it, due to the condition
being false), n will have the value 0.
You use a while loop when you 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; presumably, it makes at least some progress at its task.
When the expression becomes false, the task is done, and the rest of the
program (beyond the loop) can proceed. When we think about a loop in this
way, we can see an additional important property: 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. (It's always a good
idea to think about the “boundary conditions'' in a piece of code, and to
make sure that the code will work correctly when there is no work to do, or
when there is a trivial task to do, such as sorting an array of one number.
Experience has shown that bugs at boundary conditions are quite common.)
Program 7.1 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;
Programming with C Unit 7
Sikkim Manipal University Page No. 100
while(i<n)
{
printf("\n enter number ");
scanf(“%d”, &num);
if(large<num)
large=num;
i++;
}
printf("\n large = %d”, large);
}
Program 7.2 Program to evaluate sine series sin(x)=xx^
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;
Programming with C Unit 7
Sikkim Manipal University Page No. 101
i++;
}
printf"\nsum of sine series is %f", sum);
}
Self Assessment Questions
i) A _______ loop starts out like an if statement .
ii) State true or false
while is an entrycontrolled
loop.
7.2 do…while loop
The do…while loop is used in a situation where we need to execute the
body of the loop before the test is performed. Therefore, the body of the
loop may not be executed at all if the condition is not satisfied at the very
first attempt. Where as while loop makes a test of condition before the body
of the loop is executed.
For above reasons while loop is called an entrycontrolled
loop and
do..while loop is called an exitcontrolled
loop.
do while loop takes the following form:
do
{
Body of the loop
}
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 conditional expression in the
while statement is evaluated. If the expression is true, the program
continues to evaluate the body of the loop once again. This process
continues as long as the expression is true. When the expression becomes
Programming with C Unit 7
Sikkim Manipal University Page No. 102
false, the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
On using the do loop, the body of the loop is always executed at least once
irrespective of the expression.
Program 7.3: A program to print the multiplication table from 1 x 1 to
10 x 10 as shown below using dowhile
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);
Programming with C Unit 7
Sikkim Manipal University Page No. 103
col=col+1;
}
while (col<=colmax);
printf(“\n”);;
row=row+1;
}
while(row<=rowmax);
Printf("............................................................................................................\
n");
}
Self Assessment Questions
i) On using the ________, the body of the loop is always executed at
least once irrespective of the expression.
ii) State true or false
do…while is an entrycontrolled
loop.
7.3 The for loop
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 entrycontrolled
loop.
Generally, the syntax of a for loop is
for(expr1; expr2; expr3) statement(s)
(Here we see that the for loop has three control expressions. As always, the
statement can be a braceenclosed
block.)
Many loops are set up to cause some variable to step through a range of
values, or, more generally, to set up an initial condition and then modify
some value to perform each succeeding loop as long as some condition is
true. The three expressions in a for loop encapsulate these conditions:
expr1 sets up the initial condition, expr 2 tests whether another trip through
Programming with C Unit 7
Sikkim Manipal University Page No. 104
the loop should be taken, and expr3 increments or updates things after each
trip through the loop and prior to the next one. 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, i < 10 as expr2 , i = i + 1 as
expr3, and the call to printf as statement, the body of the loop. So the 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 sees a 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. During the execution of a for loop, the
sequence is:
expr1
expr2
statement
expr3
expr2
statement
expr3
...
expr2
statement
expr3
expr2
Programming with C Unit 7
Sikkim Manipal University Page No. 105
The first thing executed is expr1. expr3 is evaluated after every trip through
the loop. The last thing executed is always expr2, because when expr2
evaluates false, the loop exits.
All three expressions of a for loop are optional. If you leave out expr1, there
simply is no initialization step, and the variable(s) used with the loop had
better have been initialized already. If you 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 you break out of it some other way, the loop runs
forever). If you leave out expr3, there is no increment step.
The semicolons separate the three controlling expressions of a for loop.
(These semicolons, by the way, have nothing to do with statement
terminators.) If you leave out one or more of the expressions, the
semicolons remain. Therefore, one way of writing a deliberately infinite loop
in C is
for(;;)
...
It's also worth noting that a for loop can be used in more general ways than
the simple, iterative examples we've seen so far. The “control variable'' of a
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 you needed, or it could be
a floatingpoint
variable, or it could be another type of variable which we
haven't met yet which would step, not over numeric values, but over the
elements of an array or other data structure. Strictly speaking, a for loop
doesn't have to have a “control variable'' at all; the three expressions can be
anything, although the loop will make the most sense if they are related and
together form the expected initialize, test, increment sequence.
Programming with C Unit 7
Sikkim Manipal University Page No. 106
The powersoftwo
example using for is:
int x;
for(x = 2; x < 1000; x = x * 2)
printf("%d\n", x);
There is no earthshaking
or fundamental difference between the while and
for loops. In fact, given the general for loop
for(expr1; expr2; expr3)
statement
you could usually rewrite it as a while loop, moving the initialize and
increment expressions to statements before and within the loop:
expr1;
while(expr2)
{
statement
expr3;
}
Similarly, given the general while loop
while(expr)
statement
you could rewrite it as a for loop:
for(; expr; )
statement
Another contrast between the for and while loops is that although the test
expression (expr2) is optional in a for loop, it is required in a while loop. If
you leave out the controlling expression of a while loop, the compiler will
complain about a syntax error. (To write a deliberately infinite while loop,
you have to supply an expression which is always nonzero. The most
obvious one would simply be while(1) .)
Programming with C Unit 7
Sikkim Manipal University Page No. 107
If it's possible to rewrite a for loop as a while loop and vice versa, why do
they both exist? Which one should you choose? In general, when you
choose a for loop, its three expressions should all manipulate the same
variable or data structure, using the initialize, test, increment pattern. If they
don't manipulate the same variable or don't follow that pattern, wedging
them into a for loop buys nothing and a while loop would probably be
clearer. (The reason that one loop or the other can be clearer is simply that,
when you see a for loop, you expect to see an idiomatic
initialize/test/increment of a single variable, and if the for loop you're looking
at doesn't end up matching that pattern, you've been momentarily misled.)
Program 7.4: 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();
}
Programming with C Unit 7
Sikkim Manipal University Page No. 108
Self Assessment Questions
i) State true or false
for loop is an exitcontrolled
loop.
ii) State true or false
The “control variable'' of a for loop does not have to be an integer.
7.4 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++)
{
……
……
}
…….
…….
}
………
………
7.5 The break statement
The purpose of break statement is to break out of a loop(while, do while,
or for loop) or a switch statement. When a break statement is encountered
Programming with C Unit 7
Sikkim Manipal University Page No. 109
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 7.5: 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 1to 4 and prints the
message “Broke out of loop when 5 is encountered.
7.6 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). The
continue statement does not apply to a switch, like a break statement.
Unlike the break which causes the loop to be terminated, the continue ,
causes the loop to be continued with the next iteration after skipping any
statements in between.
Programming with C Unit 7
Sikkim Manipal University Page No. 110
Syntax: continue;
Program 7.6: 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..
Program 7.7: Program to sum integers entered interactively
#include <stdio.h>
int main(void)
{
long num;
long sum = 0L; /* initialize sum to zero */
int status;
printf("Please enter an integer to be summed. ");
printf("Enter q to quit.\n");
status = scanf("%ld", &num);
while (status == 1)
{
sum = sum + num;
printf("Please enter next integer to be summed. ");
Programming with C Unit 7
Sikkim Manipal University Page No. 111
printf("Enter q to quit.\n");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
7.7 Summary
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. 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, the continue , causes the loop to be continued with the
next iteration after skipping any statements in between.
7.8 Terminal Questions
1. State whether true or false
A continue statement can be used with switch .
2. _______causes the loop to be continued with the next iteration after
skipping any statements in between.
3. Write the output that will be generated by the following C program:
void main()
{
int i=0, x=0;
while (i<20)
{
if (i%5 == 0)
Programming with C Unit 7
Sikkim Manipal University Page No. 112
{
x+=i;
printf(“%d\t”, i);
}
i++;
}
printf(“\nx=%d”; x);
}
4. Write the output that will be generated by the following C program:
void main()
{
int i=0, x=0;
do
{
if (i%5 == 0)
{
x++;
printf(“%d\t”, x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
}
5. State whether true or false
A program stops its execution when a break statement is encountered.
7.9 Answers to Self Assessment Questions
7.1 i) while
ii) true
Programming with C Unit 7
Sikkim Manipal University Page No. 113
7.2 i) do…while
ii) false
7.3 i) false
ii) true
7.10 Answers to Terminal Questions
1. false
2. continue
3. 0 5 10 15
x = 30
4. 1 2 3 4
x = 4
5. false
7.11 Exercises
1. compare the following statements
a) while and do…while
b) break and continue
2. Write a program to compute the sum of digits of a given number using
while loop.
3. Write a program that will read a positive integer and determine and print
its binary equivalent using do…while loop.
4. 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.
Programming with C Unit 7
Sikkim Manipal University Page No. 114
5. 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);
6. Write programs to print the following outputs using for loops.
(a) 1 b) 1
2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4 4 4
7. 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
8. Write a program to print the multiplication table using nested for loops.

No comments:

Post a Comment