Learning How To Analyze Code

Am I doing this correctly?

My assignment is pretty much to answer certain codes manually.

1
2
3
4
5
6
int i = 0;
while (i < 7 )
{
   cout << 2 * i;
   ++i;
}


Does this code read as
2 * 0 = 0
2 * 1 = 2
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12

How about the ++i part?
the value that cout will use is the evaluated expression, which means that it will write the result of the multiplication only.

++i is the pre-increment operator, in this case all it does is increment the variable by one. This isn't too related to your question, but I figured I'd mention that there's a small (although important) difference between the pre-increment: ++i operator, and the post-increment: i++ operator: http://stackoverflow.com/questions/17366847/what-is-the-difference-between-pre-increment-and-post-increment-in-the-cycle-fo
Last edited on
So,
0
2
6
8
10
12

Thank you for the help.
Sorry, I forgot to mention it in my first reply, but the output would actually be

02681012

with no spaces or line breaks, since the only thing you're giving cout to display is the value.
The correct output:

026


The loop ends when the condition becomes false.
The loop ends when the condition becomes false.

The condition is (i < 7 ) , not ((2 * i) < 7).

Also, why is everyone skipping over the output for when i is 2?

The output will be:

024681012
Last edited on
@MikeyBoy

Ooops ! + *facepalm* (On my part)

That's really embarrassing - good thing there are people who DO know what they are talking about!!

Cheers
No worries - if I had a penny for every little slip I've made in my career as a C++ developer, I would be rich enough to no longer need to have that career :)
Topic archived. No new replies allowed.