0% found this document useful (0 votes)
2 views7 pages

While looop

Uploaded by

trish200382
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)
2 views7 pages

While looop

Uploaded by

trish200382
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/ 7

While loop

 With the while loop we can execute a


set of statements as long as a condition
is true.

Looping for a known number of times.

Things to note
 # the starting position
 # the termination condition
 # increment the loop
Example
 Print variable as long as it is less than 5

 Remember to
increment i, or else
the loop will continue

 In this example we need to define an indexing


variable, i, which we set to 1.
The break condition
 A way of stopping the execution even if
the termination condition is not yet met.

 Our termination condition is (i < 5).

 With the break statement we can stop


the loop at i==1,2,3 or 4.

 E.g.
The continue condition
 Also a way of stopping the current iteration
from being executed even if the
termination condition is not yet met.

 With the continue, we can stop the current


iteration, and continue with the next, until
the termination condition is met.
The else condition
 What the program does when the
termination condition is no longer true.
Looping for an unknown number of times
 For all the previous examples we have
looked at so far,
 we knew in advance the number of
times we were going to loop,
 just like in the for loop, i.e. for
something in range (certain range).

 Sometimes, we need to repeat


something, but we don’t know in
advance exactly how many times it has
to be repeated.

 E.g., a game keeps going until someone


wins.,
Example 1: Temperature converter
program.
Write a program where a user enters a
temperature in degrees and the program
coverts it to Fahrenheit.
The program should stop when a user
enters a stopping input like -1000.
Formula to convert is 1 F = 9/5*temp+32

You might also like