0% found this document useful (0 votes)
18 views

CP1 - Unit 11 - Loops

The document discusses while and do...while loops in C++. It explains that while loops check the condition before executing the loop body, while do...while loops check the condition after executing the loop body. Examples are provided to illustrate how to convert for loops to while and do...while loops. Nested loops are also discussed. The document concludes with an example of using nested while and do...while loops to process student grades over multiple quarters until the user indicates there are no more students.

Uploaded by

Nathaniel Napay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

CP1 - Unit 11 - Loops

The document discusses while and do...while loops in C++. It explains that while loops check the condition before executing the loop body, while do...while loops check the condition after executing the loop body. Examples are provided to illustrate how to convert for loops to while and do...while loops. Nested loops are also discussed. The document concludes with an example of using nested while and do...while loops to process student grades over multiple quarters until the user indicates there are no more students.

Uploaded by

Nathaniel Napay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

while and do…while

UNIT 11: LOOPING ( while and do…while statement)

Introduction

In general, statements are executed sequentially: The first statement in a function is


executed first, followed by the second, and so on. But more often than not your program will
have to choose a certain path and may have to repeat executing some of its statement until a
condition is satisfied. Programming languages provide various control structures that allow for
more complicated execution paths, like, for, while and do…while statement.
A loop statement allows us to execute a statement or group of statements multiple times.
If you do not know in advance how many times a block of codes will be executed then it is not
advisable to use a for loop. You can either use while or do while loop.

Learning Objectives:

After successful completion of this lesson, you should be able to:

1. Apply while and do… while for repeating codes.


2. Know when is the best time to use for, while and do…while statement.

Course Materials:

11.1 while loop - Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.

Syntax:

while (condition) {
// statements/codes to be executed
}

do …while loop - Like a ‘while’ statement, except that it tests the condition at the end
of the loop body.

Syntax:

do {
// statements/codes to be executed
}
while (condition);

89
while and do…while

Let us first convert our examples in the for loop lesson to while and do…while statement.

// prints the number 0 to 5

for ( i = 0; i <= 5; i++) i=0,1,2,3,4,5,6


{
cout << i << endl;
}

//using while statement 0


i=-1; -1 0 1 2 3 4 5 1
2
while ( i < 5){ 3
i = i + 1; 4
5
cout << i << endl;

//using while statement


i=0; 0 1 2 3 4 5 6
while ( i <= 5){
cout << i << endl;
i = i + 1;
}

// find the sum of the 1 to 5


1
2
total = 0;
3
for ( i = 1; i <= 5; i++){ 4
cout << i << endl; 5
total = total + i; Sum: 15
}
cout << “Sum: “ << total;

int total =0;


int i = 0;
If int i = 1, how will
while( i < 5) { you construct your
i = i + 1; while loop?
cout << i << endl;
total = total + i;
}
cout << “Sum: “ << total;

90
while and do…while

int total =0;


int i = 0; If int i = 1, how will
you construct your
do { while loop?
i = i + 1;
cout << i << endl;
total = total + i;
} while ( i < 5);
cout << “Sum: “ << total;

// find the average grade of students in the class

How many students in the class: 5


Enter grade of student #1: 90.76
Enter grade of student #2: 86.52
Enter grade of student #3: 78.10
Enter grade of student #4: 82.45
Enter grade of student #5: 93.60

Average grade in the class: 86.286

// using while loop

int noStud = 0, total = 0, i= 0;


float grade = 0.0, aveGrd = 0.0;

cout << “How many students in the class: “;


cin >> noStud; //5
while (i< noStud) {
i=i +1;
cout << “\nEnter grade of student #” << i << “: “;
cin >> grade;
total += grade; //total = total + grade;
}
aveGrd = total / noStud;
cout << “\n\nAverage grade in the class: “ << aveGrd;

91
while and do…while

// using the do while loop

int noStud = 0, total = 0, i=0;


float grade = 0.0, aveGrd = 0.0;

cout << "How many students in the class: ";


cin >> noStud;
do {
i = i + 1;
cout << "\nEnter grade of student #" << i << " ";
cin >> grade;
total += grade;
} while (i< noStud);
aveGrd = total / noStud;
cout << "\n\nAverage grade in the class: " << aveGrd;

Note: the counter or variable i in the for loop needs to be incremented inside the while
and do while loop to reach the maximum needed value. You can use another variable name for
the counter. There is also NO semicolon at the end of the while loop but, there is one at the end
of do… while loop.

We can also use the while loop in validating our data entry. For example, the only valid
entries are the numbers 1 – 5. Instead of just issuing cin >> number; we can add while or
do…while loop so the program will keep on asking the user to enter another number if a
number outside 1 – 5 was entered.

Choice [1-5]: 9
Invalid Input. Try again!
Choice[1-5]: 7
Invalid Input. Try again!
Choice[1-5]: 3
OK

int choice=0;

cout << "Choice [1-5]: ";


cin >> choice;

//test if choice is valid


while (choice < 1 || choice > 5) {
cout << "Invalid input. Try again. \n\n";
cout << "Choice [1-5]: ";
cin >> choice;

92
while and do…while

}
cout << "OK";
// if choices are letters from A to E. Small letters a to e are considered invalid in the code
below:

char choice=' ';

cout << "Choice [A-E]: ";


cin >> choice;
choice=toupper(choice); // convert permanently to capital letter
//test if choice is valid
while (choice < 'A' || choice > 'E') {
cout << "Invalid input. Try again. \n\n";
cout << "Choice [A=E]: ";
cin >> choice;
}
cout << "OK";

// to include small letters ( a to e ) as valid entries add the function toupper()in your
condition. This will convert temporarily the entry to capital letter.

while (toupper(choice) < 'A' || toupper(choice ) > 'E')

// If the choice or values to be entered are not in sequence. Example, gender ‘M’ for
male and ‘F’ for female

char gender=' ';


cout << "Gender [M or F]: ";
cin >> gender; x
//test if choice is valid
while (toupper(gender) != 'M' && toupper(gender) != 'F') {
cout << "Invalid input. Try again. \n\n";
cout << "Gender [M or F]: ";
cin >> gender;
}
cout << "OK";

93
while and do…while

11.2 Nested while loop

while (condition) {
while (condition) {
// statement(s) of inside loop
}
// statement of outer loop
}

Nested do…while loop

do {
do {
// statement of inside loop
}while(condition);
// statement of outer loop
} while(condition);

Note: there can be any type of loop nested inside any type and to any level

do{
while(condition) {
for (statement1; statement2; statement3) {
//statement inside for loop
}
// statement of inside while loop
}
// statement of outer do…while loop
} while(condition);

Example: Assuming you don’t know how many students to process. Enter their grades for each
quarter compute and display their average and then count and display how many students
passed and failed in the class.

# include<iostream>
using namespace std;

int main(){

int i=0, j=0;


int pass=0, fail=0;
char more = ' ';

94
while and do…while

float total = 0.0, grade= 0.0, average = 0.0;

do {

i++;
total = 0.0;
cout << "\n Enter quarterly grades of student #" <<i <<endl;

for (j=1; j <= 4; j++){


cout << "\n Quarter #" << j << ":";
cin >> grade;
total += grade; // total =total + grade;
}

average = total/4;
cout << "\n\n Average grade: " << average;
if (average >= 75) {
pass++; //pass =pass + 1;
cout << "\n PASSED\n";
}
else {
fail++; // fail =fail + 1;
cout << "\n FAILED\n";
}

cout << "\n\n More students to process ? [Y/N]: ";


cin >> more;
while (toupper(more)!='Y' && toupper(more)!='N'){
cout << " Invalid entry!";
cout << "\n\n More students to process ? [Y/N]: ";
cin >> more;
}
} while (toupper(more) == 'Y');

cout << "\n\n No. of students who passed: " << pass;
cout << "\n No. of students who failed: " << fail;

return 0;
}

95
while and do…while

Activities

Examine the following code. What will the code display in the monitor?

1. int count = 0;
while ( count <= 6 )
{
cout << count;
count += 2;
}

2. int count = 7;
while ( count >= 4 )
{
cout << count;
count -= 2;
}

3. int count = 1;
while ( count < 5 )
{
cout << count;
}

4. Convert the following statements using while and do while.

sum = 0;

for (I = 0 ; I <= 100; I+=2) {

sum = sum + I;

cout << I << endl;

cout << endl << sum;

5. Using while statement ask the user to input a character, accept only characters ‘Y’ or ‘N’,
if other characters were inputted ask the user to enter another character again. Sample
Screen below:

Do you want t try again [Y or N ] ? M

96
while and do…while

Invalid entry! Only characters Y or N are accepted.

Do you want t try again [Y or N ] ? Y

Thank you. You may now proceed.

Programming Exercises

Write a program that will incorporate while or do…while statements to do the following:

- Enter total monthly income of families in a barangay


- Ask if there is a PWD or a Senior Citizen in a family
- Ask how many members for each family.
- Determine if a family can avail of the SAP worth Php 8000.00
o Conditions - there is a PWD or senior citizen or
Monthly income less than 10,000 and family members > 4

Family Monthly Income: __35000_____________

How many members of the family? ___5____

Is there a PWD or senior citizen in the family ( Y / N )? __Y___

SAP Php 8,000.00: Approved

More Entry [Y/N] ? __Y_

Family Monthly Income: __15000_____________

How many members of the family? ___2____

Is there a PWD or senior citizen in the family ( Y / N )? __N___

SAP Php 8,000.00: Disapproved

More Entry [Y/N] ? __Y_

97
while and do…while

Online References

https://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm/

https://www.cprogramming.com/tutorial/lesson3.html

http://www.cplusplus.com/doc/tutorial/control/

98

You might also like