A little help with for statement

Started by
4 comments, last by Makoy 19 years, 10 months ago
I got this code from Problem solving with C++ by Walter Savitch. I''m confused with the second output 4 8 12 16! I mean how did a for (i=0;i<10;i=i+2) cout<<<""; got an out put of 0 4 8 12 16? int i, temp[10] for (i=0;i<10;i++) temp=2*i; for (i=0;i<10;i++) cout<<temp<<""; cout<<end1; for (i=0;i<10;i=i+2) cout<<temp<<""; output 0 2 4 6 8 10 12 14 16 18 0 4 8 12 16 </i> <b>Flamers are worst than Newbies<b>
Flamers are worst than Newbies
Advertisement
Uh... Could you please add code or source tags to your post? The code you posted is pretty unreadable otherwise
Sorry bout that. Here it is.
int i, temp[10]for (i=0;i<10;i++)temp[i]=2*i;for (i=0;i<10;i++) cout<<temp[i]<<"";for (i=0;i<10;i=i+2) cout<<temp[i]<<'''';


The output of the code is:
0 2 4 6 8 10 12 14 16 18
0 4 8 12 16

I''m confused with the second output. I mean, how did the second output produced a 0 4 8 12 16?




Flamers are worst than Newbies
Flamers are worst than Newbies
int i, temp[10]for (i=0;i<10;i++) temp[i]=2*i; 

This sets temp to 0,2,4,6,8,10,12... and so on
for (i=0;i<10;i++) cout<<temp[i]<<""; cout<<endl; 

Just output temp
for (i=0;i<10;i=i+2) cout<<temp[i]<<""; 

Output every other element from temp (since i is increased by two each iteration.)

[edited by - TomasH on May 26, 2004 7:25:58 AM]
quote:Original post by Makoy
int i, temp[10]for (i=0;i<10;i++)temp[i]=2*i;for (i=0;i<10;i++) cout<<temp[i]<<"";for (i=0;i<10;i=i+2) cout<<temp[i]<<'';//The output of the code is:0 2 4 6 8 10 12 14 16 180 4 8 12 16


I'm confused with the second output. I mean, how did the second output produced a 0 4 8 12 16?

The first two for loops run from 0 to 9 with a step of one (i++). So you get 0,1,2,3,4,5,6,7,8,9

The last for loop increases i by 2. So you get 0,2,4,6,8 and it executes the cout for each value.

[edited by - Fidelio66 on May 26, 2004 7:28:08 AM]
Yup, don''t forget that you''re outputting what''s stored in the i''th element in the "temp" array and not the iterator i itself.

for (i=0;i<10;i=i+2)
cout<<<'''';

So you''re outputting the contents of temp[0], temp[2], temp[4], temp[6], and temp[8], which is 0, 4, 8, 12, 16 respectively.
"Learn as though you would never be able to master it,
hold it as though you would be in fear of losing it" - Confucius

This topic is closed to new replies.

Advertisement