0% found this document useful (0 votes)
7 views8 pages

Understanding the While Loop Basics

Uploaded by

Dani Tanoli
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)
7 views8 pages

Understanding the While Loop Basics

Uploaded by

Dani Tanoli
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

while Loop

❑ General format of the while loop

while (expression)

{
do this;
and this;
and this also;
}

Lecture# 18 - while loop | 3


while Loop – How it works

while (expression)
statement;

❑ expression is evaluated
➢ if true, then statement is executed, and expression is evaluated again
➢ if false, then the loop is finished and program statements following statement
execute

Lecture# 18 - while loop | 4


while Loop – Flowchart

Lecture# 18 - while loop | 5


while Loop – Example

Lecture# 18 - while loop | 6


while Loop – Example (Line 9-13)

Lecture# 18 - while loop | 7


while Loop – Example

Lecture# 18 - while loop | 8


while Loop is a Pretest Loop
expression is evaluated before the loop executes. The following loop
will never execute:

int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}

Lecture# 18 - while loop | 9


while Loop – Careful with Infinite Loop
❑ The loop must contain code to make expression become false
❑ Otherwise, the loop will have no way of stopping
❑ Such a loop is called an infinite loop, because it will repeat an infinite
number of times

int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}

Lecture# 18 - while loop | 10

You might also like