Implementing a staircase within a C program

I just started with C programming and have some difficulty implementing a program which is giving a staircase with ‘Height’ amount of steps.

#include <cs50.h>
#include <stdio.h>

int main(void)

{
  int height;

    do
    {
        height = get_int("Height: ");
    }
    while(height > 8 || height == 0 || height < 0);

  int width = 0;
  int length = height;

  while(width < height)
  {
    printf(" ");
    printf("@");
    for(width = 0; width < height; width++)
      {
        printf("\n");
      }

  }
}

The first lines with the Height are working, but I have difficulties with actually writing a staircase. I wanted something like this or similar to this.

Height: 3
@
 @
  @

I just want to learn how to implement something like this if I face a problem like this in the future. If somebody could help me further I would really appreciate it!

>Solution :

This works:

#include <stdio.h>

int main() {
    // gets height input - replace with your get_int method
    int height;
    printf("Height: ");
    scanf("%i",&height);
    // loop over all the steps: 0 - height
    for (int i = 0; i < height; i++) {
        // add a space i number of times (where i is our current step number and so equal to width)
        // notice that if we take top left as (0,0), we go 1 down and 1 right each time = current step
        for (int j = 0; j < i; j++) {
            printf(" ");
        }
        // finally, after the spaces add the character and newline
        printf("@\n");
    }
    return 0;
}

Leave a Reply