What will the following program segment display?

hey guys,

I'm looking at this program here:

int count = 1, number = 1, limit = 4;
do
{
number +=2;
count ++;
}
while(count < limit);
cout << number << "," << count << endl;

After plugging in the program the output that is displayed is 7,4

I am not sure if this is correct an I am kind of lost on how 7 and 4 appeared.

Can someone plug this is an see what is displayed and how the output numbers are 7,4 if they are?

thanks guys



number = 1 + 2
count = 1 + 1
while ( 2 < 4 )

number = 3 + 2
count = 2 + 1
while (3 < 4)

number = 5 + 2
count = 3 + 1
while(4 < 4) -> here loop stops , so number = 7 and count = 4
Last edited on
Hi,

You could put a std::cout statement inside the loop to see what is happening for each iteration.

Failing that, you could check what happens by writing down the values of the variables (with pen & paper) for each iteration.

Although the best idea is to learn how to use a debugger. If you are using an IDE, it should have one built in, if not it is a little harder but not impossible to use the command line version.

Hope all is well :+)

Edit: Please always use code tags - use the <> button on the format menu

1
2
3
4
5
6
7
8
9
unsigned int count = 1;
unsigned int number = 1;
unsigned int limit = 4;
do
{
number +=2;
count ++;
} while(count < limit);
std::cout << number << "," << count << "\n";
Last edited on
Topic archived. No new replies allowed.