Monday, May 24, 2010

How do I do a for loop in C++ that will give me an output of 1-2-3-4-5-6-7-8-9-10. Mine is only giving me 10.?

#include %26lt;iostream%26gt;


using namespace std;





void main ()


{//begin main





//declare and initialize











int counter = 1;


int counter2 = 1;


int counter3 = 1;





//Process and Output








//For Loop: //test before


{





for(counter = 1; counter %26lt;= 10; counter++);


cout %26lt;%26lt; "Loop counter is at " %26lt;%26lt; counter %26lt;%26lt; endl;


counter = counter +1;





}





//While Do Loop: //test before








while (counter2 %26lt;= 10)


{





cout %26lt;%26lt; "Loop counter2 is at " %26lt;%26lt; counter2 %26lt;%26lt; endl;


counter2 = counter2 +1;


}





//Do While loop: //test after











do


{//begin loop





cout %26lt;%26lt; "Loop counter3 is at " %26lt;%26lt; counter3 %26lt;%26lt; endl;


counter3 = counter3 +1;





}//end loop


while (counter3 %26lt;= 10);





}

How do I do a for loop in C++ that will give me an output of 1-2-3-4-5-6-7-8-9-10. Mine is only giving me 10.?
In addition to the extra semi-colon (;), you are incrementing counter twice, so the output would be 1, 3, 5, 7, 9 for the for loop.





for(counter = 1; counter %26lt;= 10; counter++);


cout %26lt;%26lt; "Loop counter is at " %26lt;%26lt; counter %26lt;%26lt; endl;


counter = counter +1;





}





Should be


for(counter = 1; counter %26lt;= 10; counter++)


{


cout %26lt;%26lt; "Loop counter is at " %26lt;%26lt; counter %26lt;%26lt; endl;


}


Or


for(counter = 1; counter %26lt;= 10;)


{


cout %26lt;%26lt; "Loop counter is at " %26lt;%26lt; counter %26lt;%26lt; endl;


counter = counter +1;





}








Also, I would recommend getting in the habit of using counter++; instead of counter = counter + 1;


It looks better and is more efficient.
Reply:for(counter = 1; counter %26lt;= 10; counter++);





Is your culprit. By having the ; at the end. the loop does nothing. Remove the ; and the body of the loop will be run correctly.





Enjoy!


No comments:

Post a Comment