Lesson 5: while statement

In last lesson, we looked into using the if selection and for loop to make a program more dynamic. We also tried writing a program to print the first 10 Fibonacci numbers.

Challenge 1

Can you modify what you have written to print out a certain number of Fibonacci numbers according to the user input?

while statement

In this lesson, we will study another loop function. while loop is used when you do not know how many repetitions you are going to make. The general usage is

while (true) {
    //do the code block until condition is false

For example, you may want to continue adding scores until you run out of scores. Then you want to compute the average. Study the code below:

    int sum = 0, mark = 0;
    while (std::cin >> mark) {
        sum += mark;
    std::cout << sum << std::endl;
  1. Before you type in the code, what do you think this code does?
  2. How does the condition std::cin >> mark in the while statement work?

Now type this code and run it. How do you end the standard input? If you are on a Mac, press and hold Control-D. If you are using Windows, press and hold Control-Z.

Does the code do what you expect? Now, try stepping into the code line by line for three inputs, 5, 7, 3. What is the output?

Challenge 2

You can use the while statement to make a program runs until you quit. As an example, let us try to write a program to that accepts a name until the user decides to quit. When the user quit, the program will print out the number of names entered.

Tip: You need a counter variable to count the name number. Also, you may try to write the algorithm using pseudocode. In other words, write your solution in plain English using MS Word.

Challenge 3

Using a while statement, write a program to compute the factors of an integer.


One Comment

  1. Stanley Sim said:

    Post your code here if you are done with Challenge 3.

    September 1, 2015

Comments are closed.