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?

Recommended Answers

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 << …
Jump to Post

All 2 Replies

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.

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.