C Programming
DECISION MAKING and LOOPING
INTRODUCTION
It is possible to execute a segment of a program repeatedly by introducing a counter and
later testing it using the If statement. 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. On such occasions where the exact
number of repetitions are know, 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.
In looping, a sequence of statements are executed until some conditions for termination
of the loop are satisfied. A program loop consists of two segments, known as Body of the
loop and 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.
In the entry-controlled loop (Pre-Test), 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 (Post-Test), the test performed at the
end of the body of the loop and therefore the body id executed unconditionally for the
first time.
Entry
False
True
True
False
(a) Entry Control (a) Exit Control
Figure: Loop Control Structures
Page 1 of 10
C Programming
The test conditions should be carefully stated in order to perform the desired number of
loop executions. In 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 Statement.
The FOR Statement.
Sentinel Loops
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:
Counter-Controlled Loops: (or Definite Repetition Loop) We know in advance exactly
how many times the loop will be executed.
Sentinel-Controlled Loops: (or Indefinite Repetition Loop) A sentinel value is used to
change the loop control expression from true to false, EX: -1 and 999 to indicate “End of
Data”. The number of repetitions in not known before the loop begins executing.
The WHILE statement: [An Entry-Controlled Loop]
The simplest of all the looping structures in C is the while statement. The basic format of
the while statement is:
Page 2 of 10
C Programming
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 repetition process 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 a good practice to use braces even
if the body has only one statement.
Example-1:
statement-y;
sum = 0;
n = 1; /* Initialization */
while ( n <= 10 ) /* Testing */
{
sum = sum + n * n ; Loop
n = n + 1; /* loop */
}
printf(“\nSum of N numbers Square = %d”,sum);
Example-2:
statement-y;
character = ‘ ‘;
while ( character != ‘Y’)
{
character = getchar( );
}
statement-x;
Page 3 of 10
C Programming
The DO statement: [An Exit-Controlled Loop]
On some occasions it might be necessary to execute the body of the loop before the test is
performed. Such situations can be handled by the do statement. (Where as in while, the
body of the loop may not be executed if condition is not satisfied at the very first
attempt). The general form of do…while statement is:
or
On reaching the do statement, the program evaluates the body of the loop first. At the
end, 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 and again until the
condition becomes false. The loop will be terminated on false and the control goes to the
statement immediately after the while statement.
Since the test-condition is evaluated at the bottom of the loop, the do…while construct
provides an exit-control loop and therefore the body of the loop is always executed at
least once.
Ex: .....
do
{
clrscr();
printf(“\nEnter only non-zero value for A \n”); loop
scanf(“%d %d %d, &a, &b, &c);
}
while ( a == 0 );
.....
Page 4 of 10
C Programming
The FOR statement: [An Entry-Controlled Loop]
It provides more concise loop control structure. The general form of the for loop is
The execution of the for statement is as follows:
1. Initialization of the control variable is done first, using assignment statements
such as i = 0 and count = 1. (The variables i and count are loop-control variables)
2. The value of the control variable is tested using the test-condition (relational
expression). 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.
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 using an assignment statement (E.g. i = i + 1 or count = count + 1)
This Process continues until the control variable fails to satisfy the test-condition.
Example-1: Generation of N natural numbers
for ( i = 1 ; i <= n ; i = i+1 )
printf(“\n %d”, i );
Example-2: The sum of squares of integers
.....
sum = 0;
for ( n = 1 ; n <= 10 ; n = n + 1 )
{
sum = sum + n * n ;
}
printf(“\n Sum = %d”, sum );
.....
Page 5 of 10
C Programming
An important about FOR loop is that all the three actions ( initialization, test-condition
and increment ) 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 statements are shown below.
FOR WHILE DO
for ( n = 1 ; n <= 10 ; ++n ) n = 1; n = 1;
{ while ( n <= 10 ) do
..... { {
..... ..... .....
} ..... .....
n = n + 1; n=n+1;
} }
while ( n < = 10 );
Table : Comparison of the Three Loops
Additional Features of FOR Loop:
● More than one variable can be initialized at times that are not found in other loop
constructs.
p = 1;
for ( n = 0 ; n < 17 ; ++n ) can be written as for ( p = 1, n = 0 ; n < 17 ; ++n )
● Similarly, the increment section may also have more than one part.
for ( n = 1, m = 50 ; n < m ; n++ , --m )
{
p=m/n;
printf(“%d %d %d”,n ,m, p);
}
● The test-condition may have any compound relation and the testing need not be
limited to the loop control variables.
sum = 0;
for ( i = 1 ; i < 20 && sum < 100 ; ++i )
{
sum = sum + i ;
printf(“\n %d %d ”, i, sum );
}
Page 6 of 10
C Programming
It is also permissible to use expressions in the assignment statement of initialization and
increment sections: for ( x = (m+n) / 2 ; x > 0 ; x = x / 2 )
Another unique aspect is that one or more section cab be omitted, if necessary.
for ( ; m != 100 ; ) /* both initialization and increment sections are skipped */
To cause time delay:
for ( j = 1000 ; j > 0 ; j = j – 1 ) /* executes 1000 times */
; /* null statement */
above can be written as for ( j = 1000 ; j > 0 ; j = j – 1 ) without null statement.
For infinite loop: for( ; ; ) /* body must have break or goto to terminate */
Nested of FOR Loops: Having one for statement within another for statement. Example
for two loops having nested.
The nesting may continue up to any desired level. (ANSI C allows up to 15 levels)
Page 7 of 10
C Programming
Jumps in Loops:
Loops performs a set of operations repeatedly unit the control variable fails to satisfy the
test-condition. The number of times a loop is repeated is required is decided in advanced
and the test condition is written to achieve this. Sometimes, when executing a loop it
becomes desired to skip a part of the loop or to leave the loop as soon as a certain
condition occurs.
Jumping Out of a Loop:
An early exiting from a loop can be accomplished by the break statement or the goto
statement. These can also be used within while, do or for loops.
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. The break
will exit only a single loop when the loops are nested i.e., the loop containing it.
A goto statement transfer the control to any place in a program. Another important use of
goto is to exit from the deeply nested loops when an error occurs. (A simple break
statement would not work here.)
Example: BREAK
Example: GOTO
The use of null (;) statement at the end due to the program should not end with a label.
Page 8 of 10
C Programming
STRUCTURED PROGRAMMING
It is an approach to design and develop good programs by making program’s logic easy
to understand by using the basic three control structures:
● Sequence (Straight-line) Structure: sufficient to meet all the requirements of
programming.
● Selection (Branching) Structure: provides to be more convenient in some
situations.
● Repetition (Looping) Structure: sufficient to meet all the requirements of
programming.
The use of structured programming techniques helps ensure well-designed program that
are easier to write, read, debug and maintain compared to those that are structured.
Structured programming discourages the implementation of unconditional branching
using jump statements such as goto, break and continue. Structured programming is
“goto less programming”. Do not go to goto statement.
Skipping a Part of a Loop:
C supports another statement called the continue statement. Unlike the break which
causes the loop to be terminated, the continue, as the name implies, causes the loop to be
continued with next iteration after skipping any statements in between. The statement
tells the compiler,
“SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
The format of the continue statement is simply continue;
Example:
Bypassing and continuing in loops
In the case of for loop, the increment section of the loop is executed before the
test-condition is evaluated.
Page 9 of 10
C Programming
Avoiding GOTO:
It is a good practice to avoid using goto’s. When it is used, many compilers generate a
less efficient code, makes a program logic complicated and renders the program
readability. In case it is absolutely necessary, it should be documented.
Concise Test Expressions:
We often use test expressions / test-conditions in the if, for, while do statements that are
evaluated and compared with zero for making branching decisions. Since every integer
expression has a true/false value, we need to 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)
Example: Largest of three integers can be concise to,
x = ( a > b : ( a > c : a ; c ) ; ( b > c : b ; c ) ); [more than ten lines of code into one line]
Points o be Remember
● Do not compare floating-point values for equality.
● Avoid using while & for statements for implementing exit-controlled (post-test)
loops. Similarly, do not use do…while for entry-controlled (pre-test) loops.
● The use of break and continue statements in any of the loops is considered
unstructured programming. Try to eliminate the use of these jumps statements, as
far as possible.
● Avoid the use of goto anywhere in the program.
● Indent the statements in the body of loops properly to enhance readability and
understandability.
● Use of blank spaces before and after the loops and terminating remarks are highly
recommended.
Page 10 of 10