You are on page 1of 6

Lecture 10: Control Structure CS 101: Introduction to Computing

Lecture #10
While Loop

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Control Structure CS 101: Introduction2to Computing
2.7 The while Repetition Structure

Repetition structure
Programmer specifies an action to be repeated while some condition
remains true
Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
while loop repeated until condition becomes false.

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Control Structure CS 101: Introduction to Computing

 The while loop has two important parts:


• an expression that is tested for a true or false value
• a statement(s)
while (condition)
{
statement;
statement;
// Place as many statements
// here as necessary
}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Control Structure CS 101: Introduction4to Computing

2.7 The while Repetition Structure


int product = 2;
while ( product <= 1000 )
product = 2 * product;

• Flowchart of while loop

tru
product <= e product = 2 *
1000 product
false

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Control Structure CS 101: Introduction to Computing

 Counter-controlled repetition
• Loop repeated until counter reaches a certain value.
• Number of repetitions is known
 Example
A class of ten students took a quiz. The grades (integers in the range 0 to
100) for this quiz are available to you. Determine the class average on
the quiz.

 Sentinel value
• Indicates “end of data entry”
• Loop ends when sentinel is inputted
• Sentinel value chosen so it cannot be confused with a regular input
(such as -1 in this case)

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Control Structure CS 101: Introduction to Computing

Examples

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi

You might also like