Home > database >  Why won't my for loop work correctly (C)?
Why won't my for loop work correctly (C)?

Time:03-07

hello im writing a program that draws different shapes with for loops and printf. the last shape is a diamond and the only one that isn't working correctly. the user inputs an odd integer between 1 and 10 which is the amount of characters in the middle row. I split the code into two parts, for the top and the bottom. The bottom part of the diamond is the only part not working if user inputs 7, the output should be:

  hhhhh
   hhh
    h

But, the code only outputs one line:

   hhhhh

besides declaring variables heres my code for the bottom half:

        space = 1;
        dots = diamond - 2 ;

        for( j = 0; j < diamond/2 ; j  ){

            for(i = 0; i < space; i  ){
                 printf(" ");
            }
        
            for(j = 0 ; j < dots ; j  ){
                 printf("h");
            }
           
            dots = dots - 2;
            space  ;
            printf("\n");

        } 
         
      
             

any ideas?

CodePudding user response:

You are using j twice.

for( j = 0; j < diamond/2 ; j  )
/* ...*/
for(j = 0 ; j < dots ; j  ){

After the second use, the condition for the first loop is not met anymore,
which is why it is only exectuted once.
With consistent indentation you more likely would have spotted that.

I get the desired output for "7", when I replace the j in the second inner loop with i.

  • Related