Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading