Problem with result

I have a little problem with answer, computer is giving answer 2 4 6 8 while I am thinking that answer should be 2 6 only because value of count at start is 1 and after execution it will become 2 after multiplying with 2 and then it is incremented into 3. So next time by multiplying with 2 it should be 6 and loop should be ended because condition is no more true.
Why answer is different than my expectation, am I missing some point about loop mechanism?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
	int count = 1;
	while (count < 5)
	{
		cout << (2 * count) << " ";
		count++;
	}

	system("pause");
	return 0;
}
Last edited on
You're thinking wrong.

This is how the program goes:
First loop -
count = 1.
1 * 2 = 3;

Second loop -
count = 2.
2 * 2 = 4;

third loop -
count = 3
2 * 3 = 6

fourth loop -
count = 4.
4 * 2 = 8.

This runs 4 times, because count is incremented by 1 after each iteration. It starts at 1, runs once, then it becomes 2, runs another 3 times.

Edit: I'd suggest you learn how to debug your programs so you can step by step, line by line see what happens to understand things better.
Last edited on
Thanks #TarikNeaj

I got my point. We are just printing count by multiplying with 2 cout << (2 * count);

And my answer will be only true when we use assignment operator count = 2 * count;

I don't know when we go deep in something then sometime we skip the little points which create a big mess.
Last edited on
And my answer will be only true when we use assignment operator count = 2 * count

Yep^^ well done.
Topic archived. No new replies allowed.