0

number1 = 0;
number2 = 0;
while(number1 < 5)
number1 ++;
number2 += number1;

Question#1 : what is the value of number1 when the loop exits?
Question#2 : what is the value of number2 when the loop exits?
Question#3 : if the statement number1++ is changed to ++number1, what is the value of number1 when the loop exits?
Question#4 : what could you do to force the value of number2 to be 15 when the loop exits?

3
Contributors
2
Replies
17
Views
3 Years
Discussion Span
Last Post by AndrisP
1

You've very nearly written all the code you need to answer those questions.

#include <iostream>

int main()
{
 int number1 = 0;
 int number2 = 0;
 while(number1 < 5)
 {
   number1 ++;
   number2 += number1;
 }
 std::cout << "number1 = " << number1 << std::endl;
 std::cout << "number2 = " << number2 << std::endl;
}

That answers your first two questions. Now you do the rest.

0

In your example, there is no difference "++" pattern before or after the "number1", but if you change your code to:

#include <iostream>

int main()
    {
    int number1 = 0;
    int number2 = 0;
    while(number1 < 5)
        {
        number2 += number1++;
        }
    std::cout << "number1 = " << number1 << std::endl;
    std::cout << "number2 = " << number2 << std::endl;
    }

than will first be counted (number2 + number1) and than number1 will be increased by 1, but if you change number2 += ++number1; than first number1 will be increased by 1 and after counted (number2 + number1)

Edited by AndrisP

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.