Sunday, July 12, 2009

I need help on a C++ nested loop?

Hello -





I am trying to write a nested loop that produces:


$


$$


$$$


$$$$


$$$$$





I am really struggling because I am new at this. This is what I have coded:


#include %26lt;stdio.h%26gt;





int main(void)


{


const int ROWS = 5;


const int CHARS = 5;


int row;


int ch;





for (row = 0; row %26lt; ROWS; row++)





{


for (ch = ('$' - row); ch %26lt; ('$' + CHARS); ch++)


printf("%c", ch);


printf("\n");


}





return 0;





}





but the output looks like this:


$%%26amp;'%26lt;


#$%%26amp;'%26lt;


"#$%%26amp;'%26lt;


!"#$%%26amp;'%26lt;


!"#$%%26amp;'%26lt;





I have been at this for hours....can anyone please point out what I am doing wrong?





thanks so much

I need help on a C++ nested loop?
I have no idea what the previous two answerers are doing. You only need to know how many rows you want to publish, since the number of characters and the number of rows are the same.





You then nest your for loops so that the number of characters put out on each row equals the number of the row: e.g., row 1 has 1 character; row 2 has two characters, etc., and row 5 has five characters.





int main(void)


{


const int CHARS = 5;


int row;


int ch;





for (row = 0; row %26lt; CHARS; row++) {


for (ch = 0; ch %26lt;= row; ch++) {


printf("$");


}


printf("\n");


}





return 0;





}
Reply:The problem is in your inner loop.





change





for (ch = ('$' - row); ch %26lt; ('$' + CHARS); ch++)


printf("%c", ch);


printf("\n");





to





for (ch = 0; ch%26lt;=row; ch++)


printf("$");


printf("\n");





will solve your problem.





Edited:





If you get one row of "$"s, it means that you have coded something like this,





for (ch = 0; ch%26lt;=row; ch++)


{


printf("$");


}


printf("\n");





The below is the full solution which you can copy and paste and notice that i have only change the portions in the inner loop.





int main(void)


{


const int ROWS = 5;


const int CHARS = 5;


int row;


int ch;





for (row = 0; row %26lt; ROWS; row++)





{


for (ch = 0; ch%26lt;=row; ch++)


printf("$");


printf("\n");


}





return 0;





}

pokemon cards

No comments:

Post a Comment