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>
usingnamespace 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;
}
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.
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/