Confused little bit at some point in C++ program.

I now the output is 1024 and 10, and also know that second number is base 2 log of first number, but I am still confused that how this program is working. Can you help me to explain.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
	int n = 1024;
	int log = 0;

	for (int i = 1; i < n; i *= 2)
	{
		log++;
	}
	cout << n << " " << log << endl;

	system("pause");
	return 0;
}
Try adding an extra cout statement inside the loop.
5
6
7
8
9
10
11
12
13
    int n = 1024;
    int log = 0;

    for (int i = 1; i < n; i *= 2)
    {
        cout << "i = " << i << "   log = " << log << '\n';
        log++;
    }
    cout << n << " " << log << endl;

Output:
i = 1   log = 0
i = 2   log = 1
i = 4   log = 2
i = 8   log = 3
i = 16   log = 4
i = 32   log = 5
i = 64   log = 6
i = 128   log = 7
i = 256   log = 8
i = 512   log = 9
1024 10


Can you see how it works now?
Edit: The best answer someone can give you is to learn how to debug. It would benefit you so much if you would take the time to learn how to debug. Then you wouldn't need to not understand small logical programs like these. And it would help you solve most mysterys. Adding std::cout statements like @Chervil did also works well in this case.

The first output is 1024, which is obvious because all it does is output n.

When it comes to the log part. It's outputting 10 because the for-loop runs 10 times. Each time it increments "log".

i = 1;
After each round/iteration, "i" is multiplied by 2.

First loop:
i starts with the value 1.

Second loop: i = i * 2; // which is 2, because 1 * 2 is 2.

third loop: i = i * 2; // now it's i = 2 * 2, which is 4.

fourth loop: i = i * 2; // now it's 8, because 4 * 2 is 8.

fifth loop: i = i * 2; // 8 * 2 is 16.
...
....
...

until a point where i = 1024; and that is when the program stops. This is basically 2^10.
Last edited on
Another part of making sense of the code comes from understanding how the loop works. Often when starting out, constructions such as the for loop are used as a kind of magical incantation without knowing step by step how it works. The tutorial page on control structures may help with that.
http://www.cplusplus.com/doc/tutorial/control/
Thanks All.
Topic archived. No new replies allowed.