Home > Software design >  Implementing a staircase within a C program
Implementing a staircase within a C program

Time:11-04

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!

CodePudding user response:

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;
}

CodePudding user response:

I see three issues here:

  1. You're printing newlines (\n) instead of spaces ( ).
  2. Why print the single space character?
  3. You're printing the "@" before (what should be) the spaces.
  4. Print a newline after the spaces and the @.

Also... the staircase's width is always equal to its height; it's just the line you're printing that's advancing... that's a bit confusing.

CodePudding user response:

#include <stdio.h>

int main(void)
{
    int height = 5;
    for(int i=0; i<height; printf("%*s\n",   i, "@"));
}

Output:

Success #stdin #stdout 0s 5572KB
@
 @
  @
   @
    @
  • Related