Home > OS >  Unable to control a variable in a loop
Unable to control a variable in a loop

Time:12-15

I can't seem to understand why this part of code doesn't work, despite it being very straightforward. The program supposed to do this, 1. Input: ask the user to insert a number (value is stored in height), 2. Output: The program will then return " " (spaces) which decrements in each rows.

This is the example of the outcome I want: (I use F instead of spaces)

input: 4

output:

FFFF
FFF
FF
F

this is what I'm getting:

input: 4

output:

FFFF
FFFF
FFFF
FFFF

        for (int r = 0; r <= height; r  )        // first loop, does the columns
      { int space = height;

        space -= 1;                             // decrements space value by 1 for each loop

        while (space != 0)                      // list out the correct spaces in each row
        {   
                                  
            printf (" ");
            space--;    
        }

CodePudding user response:

In each iteration of the outer loop you reinitialize space to height, so you get the same output on each iteration.

An easier approach would be to use the loop variable as the number of columns and iterate over it backwards:

for (int r = height; r > 0 ; r--)
{
    for (int space = 0; space < r;   space)
    {
        printf("F");
    }
    printf("\n");
}

CodePudding user response:

Within the for loop

    for (int r = 0; r <= height; r  )        // first loop, does the columns
  { int space = height;

    space -= 1;                             // decrements space value by 1 for each loop

    while (space != 0)                      // list out the correct spaces in each row
    {   
                              
        printf (" ");
        space--;    
    }

the variable space is always set to the same value height - 1

     int space = height;

    space -= 1;

You can output the pattern you showed the following way

for ( ; 0 < height; --height )
{
    for ( int i = 0; i < height; i   )
    {
        putchar( 'F' );
    }

    putchar( '\n' );
}
  • Related