PIC10A Lecture5

Reading

p66-72. p57

while loop

while (condition) {
     statement1;
     statement2;
     .............
     statement_last;
}

How it works?

Example

#include<iostream>
using namespace std;

int main() {
    int countDown;

    cout << "How many greetings do you want? ";
    cin >> countDown;

    while(countDown > 0) {
        cout << "Hello ";
        countDown--;
    }

    cout << endl;
    cout << "That's all!\n";

    return 0;
}

Sample output

How many greetings do you want? 3
Hello Hello Hello
That's all!


How many greetings do you want? 0

That's all!


do-while loop

do {
    statement1;
    statement2;
    ..........
    statement_last;
} while (condition);

Don't forget the final semicolon!!!

How it works?

#include<iostream>
using namespace std;

int main() {
    int countDown;

    cout << "How many greetings do you want? ";
    cin >> countDown;

     do {
        cout << "Hello ";
        countDown--;
     } while(countDown > 0);

    cout << endl;
    cout << "That's all!\n";

    return 0;
}

Sample Output

How many greetings do you want? 3
Hello Hello Hello
That's all!


How many greetings do you want? 0
Hello
That's all!

Example2

/*
Enter your score (within 0 to 100).
The program will find out your grade.
A: 90-100
B: 80-90
C: 65-80
D: 50-65
*/
#include<iostream>
using namespace std;

int main() {
    double score;
    char again; // y or n
       do {
        cout << "Please enter your score: ";
        cin >> score;
        if(score> 100 || score < 0) {
            cout << "Invalid score.\n";
            cout << "Please check the score again.\n";
        } else if (score >= 90) {
            cout << "Your grade is A.\n";
        } else if (score >= 80) {
            cout << "Your grade is B.\n";
        } else if (score >= 65) {
            cout << "Your grade is C.\n";
        } else if(score >= 50) {
            cout << "Your grade is D.\n";
        } else {
            cout << "You fail!\n";
        }
        cout << "Continue(y/n)? ";
        cin >> again;
    } while (again=='y' || again=='Y');
    return 0;
}

Sample Ouput

Please enter your score: 53
Your grade is D.
Continue(y/n)? y
Please enter your score: 78
Your grade is C.
Continue(y/n)? y
Please enter your score: 120
Invalid score.
Please check the score again.
Continue(y/n)? y
Please enter your score: 92
Your grade is A.
Continue(y/n)? n

Difference between while and do-while

Pitfall : Using = in place of ==

Question:

What is the output of the following program if I enter 20 ?
Notice that I use age=21 instead of age==21
#include<iostream>
using namespace std;

int main() {
    int age;
    cout << "How old are you? ";
    cin >> age;
    if(age=21) {
        cout << "You are 21.\n";
    } else {
        cout << "You are not 21.\n";
    }
    return 0;
}


Output

How old are you? 20
You are 21.

What's wrong?