You are on page 1of 24

Chapter 5

More control Flow

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 2

Chapter Contents
This chapter introduces:

 while... Loop

 for... Loop

 do... while loop

 Summary

 Exercises

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 3

Loops
 Loops break the serial execution of the program.

 A group of statements is executed a number of times.

 There are three kinds of loops in C:

while
for
do … while

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 4

while – Flow Diagram


while

test true execute


expression loop body

false (expression equals zero)

skip loop body and


continue the serial execution
of the program
The value of the tested expression must change, otherwise an
infinite loop occurs.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 5

While – Loop
 Syntax:

while (expression) or while (expression)


Statement;
{Statements;}

 The loop continues to iterate as long as the value of expression


is true (expression differs from zero).

 Expression is evaluated each time before the loop body is


executed.

 The braces { } are used to group declarations and statements


together into a compound statement or block, so they are
syntactically equivalent to a single statement.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 6

Example: while1.c
1 /* while1.c
2 This program illustrates the while loop.
3 The characters from 'a' to 'z' are printed */
4
5 #include <stdio.h>
6 #define LOW_BORDER 'a'
7 #define HIGH_BORDER 'z'
8
9 void main(void)
10 {
11 char ch = LOW_BORDER; /* declare a character and
12 initialize it to hold the ASCII of 'a'*/
13 printf ("Here are the English letters :\n");
14 /* loop as long as the value of ch is lower or
15 equal to the ASCII of 'z' */
16 while(ch <= HIGH_BORDER)
17 {
18 putchar(ch); /*print the character whose ASCII is in ch
*/
19 ch++; /* increase the value of ch by one */
20 }
21 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 7

Example: while2.c
1 /* while2.c
2 This program illustrates the while-loop.
3 The user is requested to enter a digit, the digit is read from
4 The keyboard using getchar() and printed to the screen */
5 #include <stdio.h>
6
7 void main(void)
8 {
9 char dig ='a'; /* declare a character and initialize
10 it to hold the ASCII of 'a', which is not a digit*/
11 /* loop until a legal input is entered (a digit) */

12 while( dig < '0' || dig > '9' )


13 {
14 printf("\nEnter a digit (0 - 9) => ");
15 dig = getchar();
16 getchar(); /* What is the purpose of this getchar()
?*/
17 }
18 printf ("%c\n", dig);
19 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 8

for Loop Flow Diagram

expr1

F
test
expr2

T
loop body

expr3

continue program
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 9

for - Loop
 Syntax:

for (expr1 ; expr2 ; expr3)


statement;

or
for (expr1 ; expr2 ; expr3)
{
statements;
}
 Is equivalent to:
expr1;
while (expr2)
{
{statements;}
expr3;
}

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 10

Elements of the for Loop

expr1 Initializing the loop variable.

expr2 Condition for continuing the loop.

statements The loop body, expressions and statements.

It is executed after the loop body


expr3 (statements) in every loop iteration. usually,
the loop variable is changed within expr3.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 11

Example: for.c
1 /* for.c
2 This program illustrates the for loop.
3 The characters from 'a' to 'z' are printed. */
4
5 #include <stdio.h>
6
7 #define LOW_BORDER 'a'
8 #define HIGH_BORDER 'z'
9
10 void main(void)
11 {
12 char ch;
13 printf ("Here are the English letters :\n");
14
15 for (ch = LOW_BORDER ; ch <= HIGH_BORDER ; ch++)
16 {
17 printf("%c ", ch); /* the loop body - print ch.
*/
18 }
19 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 12

for Loop Example - Explanations


 ch is initialized with the ASCII of 'a' (LOW_BORDER).
This happens only once - the first time the loop is executed
(exp1).

1. ch is evaluated. If it is lower or equal to the ASCII of 'z'


(UPPER_BORDER), the loop body will execute (exp2).

2. Loop body: print the character whose ASCII is the value of ch.

3. ch is increased by one (exp3).

4. ch is evaluated for re-entering the loop body and so on...

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 13

for Loop – Flexibility


 exp3 can be any mathematical operation.
int i;
for(i = 30 ; i > 0 ; i /= 2)
 Count by any number (int, char, double etc.).
char ch;
for(ch = 'a' ; ch <= 'z' ; ++c)
 Expressions 1 and 3 can be any legal ones, and even more
than one - using the comma operator to separate expressions.
double i, j;
for(i=11.1,j=22.2;i < j && j >= 15; i *= 2,--
j)
 Can leave one or more expressions blank.
int i = 100;
for( ; i >= 0 ; )
{
printf("%d ", i);
i /= 4;
} © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 14

Comma Operator
 The comma operator ( the operator with the lowest precedence)
is most often used in the for statement. It expands the flexibility
of the for loop, by allowing more than one initialization (expr1)
or more than one update (expr3).

 Example:

int i,j;
for(i=0, j=0; i<5; i++, j--)
printf("i=%d j=%d\n", i,j);

 Generally, if we have: exp1,expr2 the following happens:


expr1 is evaluated (if containing an assignment it is executed).
Then the value of expr1 is discarded, and expr2 is
evaluated. This will be the value of the whole expression.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 15

Example:
Try to write a program to print following

11
2112
321123

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 16

do while Loop
 Syntax:

do
{
Statements;
}while (expression);

 The condition expression for looping is evaluated only after the


loop body had executed.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 17

do while Flow Diagram

loop
body statements

expression test True


to test cond.

False
 The value of the expression tested should change within the loop
body, otherwise the loop is infinite.

 The loop body is executed at least once, unlike the other looping
methods, where the condition is evaluated before entering the loop
body.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 18

Example: do-while.c
1 /* do_while.c
2 This program illustrates the do while loop.
3 The characters from 'a' to 'z' are printed */
4 #include <stdio.h>
5 #define LOW_BORDER 'a'
6 #define HIGH_BORDER 'z'
7
8 void main(void)
9 {
10 char ch = LOW_BORDER; /* declare a character and
11 initialize it to hold the ASCII of 'a' */
12 printf ("Here are the English letters :\n");
13
14 /* in a do while loop, the condition is checked AFTER each
15 iteration. This means that there is at least one iteration
*/
16 do
17 {
18 printf("%c ", ch); /* print the character
19 whose ASCII is in ch */
20 ch++; /* increase ch by 1 */
21 }while(ch <= HIGH_BORDER);
22 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 19

break Statement
 We have seen how to use the break statement within the switch
statement.

 The break statement has another use as well.

 A break statement within a loop sends control to the first


statement following that loop. this means that the execution of
the loop is stopped.

 Obviously, if there is a break statement in a loop, it should be


wrapped by an if statement.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 20

Example: break.c
1 /* break.c
2 This program chooses a random number(0-10),and the user
3 will try to guess it */
4

5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <time.h>
8

9 void main(void)
10 {
11 int num; /* the random number */
12 int guess = -1; /* the user’s guess,
13 initialized to -1 (Why ?) */
14
15 srand(time(0)); /* initialize the mechanism of
16 random numbers*/
17 num = rand() % 11; /* choose a random number
18 and limit it’s range */
19 printf ("A random number(in the range 0-10) "
20 "was chosen. Try to guess it.\n");

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 21

Example: break.c – cont’d


21 while (guess != num) /* loop as long as the user
22 didn’t guess right */
23 {
24 printf("Enter your guess (enter -1 if you
want"
25 " to stop guessing) : ");
26 scanf ("%u", &guess);
27 if(guess == -1) /* the user chose to stop trying
*/
28 break; /* terminate the loop */
29 }
30 printf ("The answer was %u. Thank you.\n", num);
31 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 22

continue Statement
 In some situations, you might want to skip to the next iteration of
a loop without finishing the current iteration.

 The continue statement allows you to do that.

 When encountered, continue skips over the remaining


statements of the loop, but continues to the next iteration of
the loop.

Example:
Suppose we want to print the values of the expression
y = 1/(x-3) for all the values of x (integer) from 1 to 10.
for (x = 1 ; x <= 10 ; ++x)
{
if (x==3)
continue; /* avoid division by zero */
printf("%d %f\n", x, 1/(x-3) );
}

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 23

Summary
 Loops break the serial execution of commands.

 A group of statements is executed a number of times.

 There are three kinds of loops in C :


while...
for...
do... while

 The value of the tested expression must change, or an infinite


loop occurs.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 24

Summary – cont’d

while for do
do
while(exp) for(exp1; exp2; {
{ exp3) statements;
statements; { } while(exp);
} statements;
}

while exp is true while exp2 is true while exp is true


exp is evaluated exp2 is evaluated
exp is evaluated
before the loop before the loop
after the loop body.
body. body.

loop body is
loop body might not loop body might not
executed at least
be executed at all. be executed at all.
once.

© Copyright: Spymek Software Pvt. Ltd.

You might also like