Originally Posted by
Bamaboy53
Here's the answer I came up with:
What is the output of the following code segment?
for(int m=1; m <= 4; m++)
cout << (m*2);
In the above for loop m is initialize to 1
1st time m = 1 and it is less than equal to 4 so cout prints at the screen (1 * 2) = 2
2nd time m = 2 and it is less than equal to 4 so cout prints at the screen (2 * 2) = 4
3rd time m = 3 and it is less than equal to 4 so cout prints at the screen (3 * 2) = 6
4th time m = 4 and it is less than equal to 4 so cout prints at the screen (4 * 2) = 8
5th time m = 5 and it is NOT less than equal to 4 so for loop exited
Output screen will show all the above numbers together
2468
I hope that I got it right:)
You sure did.
On a side-note, in C++ they tried to make it standard to use the pre-increment operator and the != operator instead of <= operator because that logic is more readable to humans because we think that way.
++3 evaluates to 4, where as
3++ evaluates to 3. In the case of your for-loop, variable
m isn't incremented until the line
cout << (m*2); is executed.
It's not essential, just style.
[code="C++"]
for(int m = 1; m != 5; ++ m)
cout << (m*2);
[/code]
I'm programming in Objective-C now, and that is quite different from C++ in some respects. If you're interested in programming and this isn't just an assignment you want to get over with, I suggest you check it out.