0% found this document useful (0 votes)
46 views35 pages

CPPM Unit 4

FYBCA, CPPM UNIT 4

Uploaded by

aatifmulla40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views35 pages

CPPM Unit 4

FYBCA, CPPM UNIT 4

Uploaded by

aatifmulla40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Dr. Ashish B.

Patel
Department Head (BCA) & Assistant Professor
Naran Lala College of Professional and Applied Sciences,
Navsari

1
Course Content Unit 4
UNIT-4: Iterative statements :
4.1 while loop
4.2 do..while loop
4.3 for loop
4.4 Nested while, do..while and for loops
4.5 Jumping statement: (break and continue).

2
UNIT-4: Learning Objectives
 Discuss while statement
 Explain do…while statement
 Describe for statement
 Illustrate how jumps are applied in loops

3
Decision Making and Looping
Introduction. We have seen in the previous unit that it is possible to execute a
segment of a program repeatedly by introducing a counter and later testing using the
if statement. While this method is quite satisfactory for all practical purposes, we
need to initialize and increment a counter and test its value at an appropriate place in
the program for the completion of the loop. For example, suppose we want to
calculate the sum of squares of all integers between 1 and 10. we can write a
program using if statements as follows:

4
Decision Making and Looping
This program does the following things:
1. Initializes the variable n.
2. Computes the square of n and adds it to sum.
3. Tests the value of n to see whether it is equal to 10 or not. If it is equal to 10,
then the program prints the results.
4. If n is less then 10, then it is incremented by one and the control goes back to
compute the sum again. The program evaluates the statement sum = sum + n *
n; 10 times. That is, the loop is executed 10 times. This number can be
increased or decreased easily by modifying the relational expression
appropriately in the statement if( n = = 10). On such occasions where the exact
number of repetitions are known, there are more convenient methods of looping
in C. These looping capabilities enable us to develop concise programs
containing repetitive processes without the use of goto statements.

5
Decision Making and Looping
In looping, a sequence of statements are executed until some conditions for
termination of the loop are satisfied. A program loop therefore consists of two
segments, one known as the body of the loop and the other known as the control
statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure
may be classified either as the entry-controlled loop or as the exit-controlled loop.
The flowcharts in fig. 7.1 (on next slide) illustrated these structures. In the entry-
controlled loop, the control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, then the body of the loop will not be
executed. In the case of an exit-controlled loop, the test is performed at the end of
the body of the loop and therefore the body is executed unconditionally for the first
time. The entry-controlled and exit-controlled loops are also known as pre-test and
post-test loops respectively.

6
Decision Making and Looping

7
Decision Making and Looping
The test conditions should be carefully stated in order to perform the desired number
of loop executions. It is assumed that the test condition will eventually transfer the
control out of the loop. In case, due to some reasons it does not do so, the control
sets up an infinite loop and the body is executed over and over again.
A looping process, in general, would include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
The test may be either to determine whether the loop has been repeated the specified
number of times or to determine whether a particular condition has been met.
The C language provides three constructs for performing loop operations. They are:
The while statement, The do...while statement, The for statement.
We shall discuss the features and applications of each of these statements in this
8
unit.
Decision Making and Looping
Based on the nature of control variable and the kind of value assigned to it for
testing the control expression, the loops may be classified into following two
general categories:
1. Counter-controlled loops
2. Sentinel-controlled loops
When we know in advance exactly how many times the loop will be executed, we use a
counter-controlled loop. We use a control variable as counter. The counter must be
initialized, tested and updated properly for the desired operations. The number of times
we want to execute the loop may be a constant or a variable that is assigned a value. A
counter-controlled loop is sometimes called definite repetition loop.
In a sentinel-controlled loop, a special value called a sentinel value is used to change
the loop control expression from true to false. For example, when reading data we may
indicate the “end of data” by a special value, like -1 and 999. The control variable is
called sentinel variable. A sentinel-controlled loop is often called indefinite repetition
loop because the number of repetitions is not known before the loop begins executing.
9
The While Statement
The simplest of all the looping structures in C is the while statement. We have used
while in many of our earlier programs. The basic format of the while statement is:
while( test condition)
{
body of the loop
}
The while is an entry controlled loop statement. The test-condition is evaluated
and if the condition is true, then the body of the loop is executed. After execution of
the body, the test-condition is once again evaluated and if it is true, the body is
executed once again. This process of repeated execution of the body continues until
the test-condition finally becomes false and the control is transferred out of the loop.
On exit, the program continues with the statement immediately after the body of the
loop.
The body of the loop may have one or more statements. The braces are needed only
if the body contains two or more statements. However, it is good practice to use
10
braces even if the body has only one statement.
The While Statement

11
The Do…While Statement
The while loop construct that we have discussed in the previous section, makes a
test of condition before the loop is executed. Therefore, the body of the loop may
not be executed at all if the condition is not satisfied at the very first attempt. On
some occasions it might be necessary to execute the body of the loop before the test
is performed. Such situation can be handled with the help of the do statement. This
takes the form:
do
{
body of the loop

} while(test-condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop
first. At the end of the loop, the test-condition in the while statement is evaluated. If
the condition is true, the program continues to evaluate the body of the loop once
again. This process continues as long as the condition is true. When the condition
becomes false, the loop will be terminated and the control goes to the statement that
appears immediately after the while statement. 12
The Do…While Statement
Since the test-condition is evaluated at the bottom of the loop, the do....while
construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.
A simple example of a do....while loop is:
do
{
printf(“Input a number\n”);
number = getnum ( );
} while (number > 0);

This segment of a program reads a number from the keyboard until a zero or a
negative number is keyed in, and assigned to the sentinel variable number.
The test conditions may have compound relations as well. For instance, the
statement: while( number > 0 && number < 100); in the example would cause the
loop to be executed as long as the number keyed in lies between 0 and 100.
13
The For Statement
The for loop is another entry-controlled loop that provides a more concise loop
control structure. The general form of the for loop is:
for(initialization; test-condition; increment or decrement)
{
body of the loop
}
The execution of the for statement is as follows:
1. Initialization of the control variable is done first, using assignment statements
such as i = 1 and count = 0. The variables i and count are known as loop-control
variables.
2. The value of the control variable is tested using the test-condition. The test-
condition is a relational expression, such as i < 10 or i > 0, that determines
when the loop will exit. If the condition is true, the body of the loop is
executed; otherwise the loop is terminated and the execution continues with the
statement that immediately follows the loop.
14
The For Statement
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now, the control
variable is incremented or decremented using an assignment statement, such as
i = i + 1 or i = i – 1, and the new value of the control variable is again tested to
see whether it satisfies the loop condition. If the condition is satisfied, the body
of the loop is again executed. This process continues till the value of the control
variable fails to satisfy the test-condition.
Consider the following segment of a program:
for(x = 0; x <= 9; x = x + 1)
{
printf(“%d”, x);
}
printf(“\n”);
This for loop is executed 10 times and prints the digits 0 to 9 in one line. The three
sections enclosed within parentheses must be separated by semicolons. Note that
there is no semicolon at the end of the increment section, x = x + 1.
15
The For Statement
The for statement allows for negative increments. For example, the loop discussed
above can be written as follows:
for(x = 9; x >= 0; x = x - 1)
printf(“%d”, x);
printf(“\n”);
This loop is also executed 10 times, but the output would be from 9 to 0 instead of 0
to 9. Note that braces are optional when the body of the loop contains only one
statement.
Since the conditional test is always performed at the beginning of the loop, the body
of the loop may not be executed at all, if the condition fails at the start. For example,
for(x = 9; x < 9; x = x - 1)
printf(“%d”, x);
Will never be executed because the test condition fails at the very beginning itself.

16
The For Statement
One of the important points about the for loop is that all the three actions, namely
initialization, testing and incrementing/decrementing, are placed in the for
statement itself, thus making them visible to the programmers and users in one
place. The for statement and its equivalent of while and do…while statements are
shown in table 7.1.

17
The For Statement
Additional Features of For Loop.
The for loop in C has several capabilities that are not found in other loop constructs. For
example, more than one variable can be initialized at a time in the for statement. The
statements
p = 1;
for(n = 0; n < 17; ++n)
Can be rewritten as,
for(p = 1, n = 0; n < 17; ++n)
Note that the initialization section has two parts p = 1 and n = 1 separated by comma.
Like the initialization section, the increment section may also have more than one part.
For example, the loop
for(n = 1, m = 50; n < = m; n = n + 1, m = m – 1)
{
p = m / n;
printf(“%d %d %d\n”, n, m, p);
} 18
The For Statement
Is perfectly valid. The multiple arguments in the increment section are separated by
commas.
The third feature is that the test-condition may have any compound relation and the
testing need not be limited only to the loop control variable. Consider the example
below:
sum = 0;
for(i = 1; i < 20 && sum < 100; ++i)
{
sum = sum + i;
printf(“%d %d\n”, i, sum);
}
The loop uses a compound test condition with the counter variable i and sentinel
variable sum. The loop is executed as long as both the condition i < 20 and sum <
100 are true. The sum is evaluated inside the loop.

19
The For Statement
It is also permissible to use expressions in the assignment statements of initialization and
increment sections. For example, a statement of the type:
for(x = (m+n) / 2; x > 0; x = x / 2) is perfectly valid.
Another unique aspects of for loop is that one more sections can be omitted, if necessary.
Consider the following statements:
m = 5;
for( ; m != 100 ; )
{
printf(“%d\n”, m);
m = m + 5;
}
Both the initialization and increment sections are omitted in the for statement. The
initialization has been done before the for statement and the control variable is
incremented inside the loop. In such cases, the sections are left ‘blank’. However, the
semicolons separating the sections must remain. If the test-condition is not present, the
for statement sets up an ‘infinite’ loop. Such loops can be broken using break or goto
statements in the loop. 20
The For Statement
We can set up time delay loops using the null statement as follows:
for( j = 1000; j > 0; j = j – 1)
;
This loop is executed 1000 times without producing any output; it simply causes a
time delay. Notice that the body of the loop contains only a semicolon known as null
statement. This can also be written as follows:
for( j = 1000; j > 0; j = j – 1) ;
This implies that the C compiler will not give an error message if we place a
semicolon by mistake at the end of a for statement. The semicolon will be
considered a null statement.

21
Nesting of For Loops
Nesting of loops, that is, one for statement within another for statement, is allowed
in C. for example, two loops can be nested as follows:

22
Nesting of For Loops
The nesting may continue up to any desired level. The loops should be properly
indented so as to enable the reader to easily determine which statements are
contained within each for statement. (ANSI C allows up to 15 levels of nesting.
However, some compilers permit more).
The program to print the multiplication table discussed in below program can be
written more concisely using nested for statements as follows:

23
Selecting a Loop
Given a problem, the programmer’s first concern is to decide the type of loop
structures to be used. To choose one of the three loop supported by C, we may use
the following strategy:
• Analyse the problem and see whether it required a pre-test or post-test loop.
• If it requires a post-test loop, then we can use only one loop, do while.
• If it requires a pre-test loop, then we have two choices: for and while.
• Decide whether the loop termination requires counter-based control or sentinel-
based control.
• Use for loop if the counter-based control is necessary.
• Use while loop if the sentinel-based control is required.
• Note that both the counter-controlled and sentinel-controlled loops can be
implemented by all the three control structures.

24
Jumps in Loops
Loops perform a set of operations repeatedly until the control variable fails to satisfy
the test-condition. The number of times a loop is repeated is decided in advance and
the test condition is written to achieve this. Sometimes, when executing a loop it
becomes desirable to skip a part of the loop or to leave the loop as soon as a certain
condition occurs. For example, consider the case of searching for a particular name
in a list containing, say, 100 names. A program loop written for reading and testing
the names 100 times must be terminated as soon as the desired name is found. C
permits a jump from one statement to another within a loop as well as a jump out of
a loop.

25
Jumps Out of a Loop
An early exit from a loop can be accomplished by using the break statement or the
goto statement. We have already seen the use of the break in switch statement and
the goto in the if…else construct. These statements can also be used within while,
do…while, or for loops. They are illustrated in figures 7.9 and 7.10 (on slide no. 27
and 28).
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 will exit only a single loop.

26
Jumps Out of a Loop

27
Jumps Out of a Loop
Since a goto statement can transfer the control to any place in a program, it is useful
to provide branching within a loop. Another important use of goto is to exit from
deeply nested loops when an error occurs. A simple break statement would not work
here.
The goto statement transfers the control of a program from one point to another.
However, the statement should be used with due diligence, as such control transfers
the program un-structured.

28
Structured Programming
Structured programming is an approach to the design and development of programs.
It is a discipline of making a program’s logic easy to understand by using only the
following basic three control structures:
1. Sequence (straight line) structure
2. Selection (branching) structure
3. Repetition (looping) structure
While sequence and loop structures are sufficient to meet all the requirements of
programming, the selection structure proves to be more convenient in some
situations.
The use of structured programming techniques helps ensure well-designed programs
that are easier to write, read, debug and maintain compared to those that are
unstructured.
Structured programming discourages the implementation of unconditional branching
using jump statements such as goto, break and continue. In its purest form,
structured programming is synonymous with “goto less programming”. Do
not go to goto statement! 29
Skipping a Part of a Loop
During the loop operations, it may be necessary to skip a part of the body of the loop
under certain conditions. For example, in processing of applications for some job, we
might like to exclude the processing of data of applicants belonging to a certain category.
On reading the category code of an applicant, a test is made to see whether his
application should be considered or not. If it is not to be considered, the part of the
program loop that processes the application details is skipped and the execution
continues with the next loop operation.
Like the break statement, C supports another similar statement called the continue
statement. However, unlike break which causes the loop to be terminated, the continue,
as the name implies, causes the loop to be continued with the next iteration after
skipping any statements in between. The continue statement tells the compiler, “SKIP
THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT
ITERATION”. The format of the continue statement is simply
continue;
The use of continue statement in loops is illustrated in figure 7.13 (on next slide). In
while and do…while loops, continue causes the control to go directly to the test-
condition and then to continue the iteration process. In the case of for loop, the
increment section of the loop is executed before the test condition is evaluated. 30
Skipping a Part of a Loop

31
Avoiding goto
As mentioned earlier, it is a good practice to avoid using goto. There are many
reasons for this. When goto is used, many compilers generate a less efficient code.
In addition, using many of them makes a program logic complicated and renders the
program unreadable. It is possible to avoid using goto by careful program design. In
case any goto is absolutely necessary, it should be documented. The goto jumps
shown in figure 7.15 would cause problems and therefore must be avoided.

32
Jumping out of the Program
We have just seen that we can jump out of a loop using either the break statement
or goto statement. In a similar way, we can jump out of a program by using the
library function exit( ). In case, due to some reason, we wish to break out of a
program and return to the operating system, we can use the exit( ) function, as
shown below:
……….
……….
if(test-condition) exit(0);
……….
……….
The exit( ) function takes an integer value as its argument. Normally zero is used to
indicate normal termination and a nonzero value to indicate termination due to some
error or abnormal condition. The use of exit( ) function requires the inclusion of the
header file #include<stdlib.h>.
33
Concise Test Expressions
We often use test expressions in the if, for, while and do…while statements that are
evaluated and compared with zero for making branching decisions. Since every
integer expression has a true/false value, we need not make explicit comparisons
with zero. For instance, the expression x is true whenever x is not zero, and false
when x is zero. Applying! Operator, we can write concise test expressions without
using any relational operators.
if(expression = = 0) is equivalent to if(!expression)
Similarly if(expression! = 0) is equivalent to if(expression)

For example,
if(m % 5 = = 0 && n % 5 = = 0) is same as if(!(m % 5) && !(n % 5))

34
35

You might also like