0% found this document useful (0 votes)
14 views53 pages

Lecture 4 - Iteration Statements

The document provides an overview of iteration statements in programming, particularly focusing on loops such as while, do while, and for loops. It explains how these loops function, their syntax, and includes examples to illustrate their use in controlling program flow. Additionally, it discusses control statements like break and continue, as well as nested loops.

Uploaded by

leaderatelast
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)
14 views53 pages

Lecture 4 - Iteration Statements

The document provides an overview of iteration statements in programming, particularly focusing on loops such as while, do while, and for loops. It explains how these loops function, their syntax, and includes examples to illustrate their use in controlling program flow. Additionally, it discusses control statements like break and continue, as well as nested loops.

Uploaded by

leaderatelast
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/ 53

Iteration Statements

CSE 4373: Computer Programming and Applications


Ajwad Abrar
Junior Lecturer, CSE
A scenario
● You’ve opened up a bakery

● People are going crazy for your Red

velvet cakes

● You have to increase your production

● But the recipe is the same for each

cake

● You’re baking the same cake over

and over again 2


Iterations
Think about other scenarios where one might have to do the same thing over and
over again in a loop until some condition has been met.

3
Iterating decisions

4
How do we translate this into
programming?

5
Basic thermostat
● It has to keep the temperature fixed in a
certain range
● Assume that the range is between 20
degrees celsius and 25 degrees celsius
If temperature > 25 → Decrease temperature
If temperature < 20 → Increase temperature
Else → Do nothing

6
Basic thermostat
if(t > 25)
// Decrease temperature
else if(t < 20)
// Increase temperature
else
// Do nothing

7
Basic thermostat
● But we can’t check just once
● Must repeat it every 5-10 minutes

Repeat every 5 minutes: → Controlling expression


Check & adjust temperature → Loop body

Is there a stopping condition for this?


8
Iteration statements

9
Iteration statements
● Repeatedly execute some statement → Loop body
● Check the controlling expression each time loop
body is executed
○ If the expression is True (non-zero value), keep
looping
○ If the expression is False (zero value), exit the
loop

10
Logical data in C
Does not have a dedicated boolean datatype

1 True

0 False

Others True

11
Iteration statements
Iteration statements are also
called loops
10 < 13

Types of loops:
● while
● do while 1.3 >= 12
● for

12
while statement

13
while statement
Repeat expressions by testing a controlling expression

while(expression) {statement}

Controlling expression is tested before execution of loop body


If the expression gives Non-zero values, only then the statement will be repeated

int number = 1;
while(number <= 5)
{
printf(“Hello”);
} 14
while statement
int iterator = 1;
while(iterator <= 3) // check this condition every time
{
printf(“%d\n”, iterator); // printing the value in iterator
iterator = iterator + 1; // increasing iterator by 1
}

What does this code do?

15
while statement
int i = 1; i = 1; i is now 1
while(i <= 2) Is i <= 2? Yes. Continue
{ printf() prints i = 1
printf(“%d\n”, i); i = i + 1 i is now 2
i = i + 1; Is i <= 2? Yes. Continue
} printf() prints i = 2
i = i + 1 i is now 3
Is i <= 2? No. Exit loop

16
while statement
The while loop may not be executed at all, since the controlling
expression is checked before execution
int i = 10;
while(i < 5)
{
printf(“Hello\n”);
i++;
}
printf(“We are done.”);
17
Pop Quiz

18
while statement
How to keep a while loop running forever?

19
while statement
How to keep a while loop running
forever?

while(1)
{
// expressions
}

20
while statement
An infinite loop will execute forever unless its body contains a
statement that transfers control out of the loop (break, goto,
return) or calls a function that causes the program to terminate
(exit).

Infinite loops can crash your program or your computer


Try to avoid them unless you want them deliberately

21
Pop Quiz

22
FizzBuzz
Write a program that prints the numbers from 1 to n. But
● for multiples of 3, print ‘Fizz’ instead of the number,
● and for multiples of 5, print ‘Buzz’.
● For numbers that are multiples of both 3 and 5, print
‘FizzBuzz’

This question can be encountered in coding interviews for


big tech companies.

23
do while statement

24
do while statement
This is very similar to the while statement with one simple difference
It executes loop body first, then evaluates controlling expression
do {statement} while(expression);
If value of the expression is nonzero, execute the loop body and check again

int i = 10;
do
{
printf(“%d\n”, i); // prints the number in i
i = i - 1; // decrements i by 1
}while(i > 0);

25
do while statement
In case of do while statement, the loop body is execute at least once.

int i = 10; int i = 10;


while(i < 5) do
{ {
printf(“Hello\n”); printf(“Hello\n”);
i++; i++;
} }while(i < 5);
printf(“We are done.”); printf(“We are done.”);

26
Pop Quiz

27
do while statement
Will these produce the same output?

int x = 5; int y = 5;
while(x > 0) do
{ {
printf("%d ", x); printf("%d ", y);
x--; y--;
} }while (y > 0);

28
for statement

29
for statement
● Probably the most used looping statement
● Best for counting variables
for(expr1; expr2; expr3) {statement}

expr1 → initialization step → performed only once before the loop begins
expr2 → controlling expression → continues looping as long as expr2 is nonzero
expr3 → performed every time at the end of each iteration.

30
for statement
Translate a while loop into a for loop

int i = 5; // expr1 int i; // declare i


while(i > 0) // expr2 for(i = 5; i > 0; i--)
{ {
printf(“%d\n”, i); printf(“%d\n”, i);
i--; // expr3 }
}

31
for statement
Count up or down:
● for(i = 0; i < 10; i++) // Count up from 0 to 9
● for(i = 1; i <= 10; i++) // Count up from 1 to 10
● for(i = 10; i >= 0; i--) // Countdown from 10 to 0
● for(i = 10; i > 0; i--) // Countdown from 10 to 1

Focus on the control expression and increment/decrement expression


Initialization step is only needed at the very beginning

32
for statement
int i; i = 1; i is now 1
for(i = 1; i <= 2; i++) Is i <= 2? Yes. Continue
{ printf() prints i = 1
printf(“%d\n”, i); i++ i is now 2
} Is i <= 2? Yes. Continue
printf() prints i = 2
i++ i is now 3
Is i <= 2? No. Exit loop

33
Pop Quiz

34
for statement
Omitting expressions from for loop can have exciting results

int i;
for(i = 1; ; i++) // keeping expr2 empty
{
printf(“Hello\n”);
}

35
for statement
Omitting expressions from for loop can have exciting results

int i;
for(i = 1; ; i++) // keeping expr2 empty
{
printf(“Hello\n”);
}

Results in an infinite loop

36
Loop controls

37
Loop controls
We can use certain keywords to manipulate loops that
are not controlling expressions
● break statement
● continue statement

These are used control exit-points and manipulate


forceful looping

38
break statement

39
break statement
Normal exit-points in loops
● At the beginning
● At the end
To exit the loop at any point in the loop → break statement
int i = 0;
while(1)
{
if(++i == 10) {break;} // breaks out of the infinite loop
}
40
continue statement

41
continue statement
● Forces the loop to iterate once
● Transfers control to a just before the end of the loop body
● Control remains inside the loop
int i;
for(i = 1; i <= 10; i++)
{
if(i % 2 == 0)
{
continue;
}
printf(“%d\n”, i);
}
42
Pop Quiz

43
continue statement
Write a program which takes sum of only positive numbers from the user

int i, num, sum = 0;


for(i = 1; i <= 10; i++)
This one is written
{ without the
scanf(“%d”, &num); continue statement
if(num >= 0)
{sum = sum + num;}
}
44
continue statement
Write a program which takes sum of only positive numbers from the user

int i, num, sum = 0;


for(i = 1; i <= 10; i++)
This one is written
{ using the continue
scanf(“%d”, &num); statement
if(num < 0) {continue;}
sum = sum + num;
}
45
Nested loops

46
Nested loops
● Loops inside loops
● Imagine you’re doing a treasure hunt
● You are given some clues
● Each clue has multiple sub-clues
● Only when you solve every clue, you get the treasure

47
Nested loops
for(i = 0; i < 5; i++) while(i < 5)
{ {
for(j = 0; j < 5; j++) for(j = 0; j < 5; j++)
{ {
printf(“%d %d”, i, j); printf(“%d %d”, i, j);
} }
} i++;
}
Try to trace i & j 48
Pop Quiz

49
Nested loops
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
if(j == 1)
{break;}
}
}

50
Nested loops
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
Only the inner loop
if(j == 1)
will be broken out of
{break;}
}
}

51
Reading Tasks
● C Programming - A Modern Approach | Chapter 6

52
Thank You

53

You might also like