Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

A little help with for statement

This topic is 5110 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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[i]=2*i; for (i=0;i<10;i++) cout< Flamers are worst than Newbies

Share this post


Link to post
Share on other sites
Advertisement
Uh... Could you please add code or source tags to your post? The code you posted is pretty unreadable otherwise

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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 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?


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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!