Programming Challenge #3: Staircase

The Task: Implement a function that will
print out a staircase of desired length.

Example: If I call some function print_staircase(6), I should get something like this:

     #
    ##
   ###
  ####
 #####
######

Tips:

  • The language you use is your choice.
  • Think about spacing.

This activity is taken from Harvard’s CS50 pset1.

2 Likes
def print_staircase(length): print "\n".join([str("#"*i).rjust(length) for i in range(length+1)])

E: Now actually a function.

5 Likes

Brevity ftw! You really are a god xD

2 Likes

Attempt at a python one liner… hard not to use str.join() like Joe_Schmoe, but different innards


def stairs(x): print '\n'.join((' '*(x-i)+'#'*i for i in range(1,x+1)))

Here’s a go in C:

#include <stdio.h>

void stairs(int x)
{
    int i, j, k;
    for (i = 1; i < x+1; i++)
    {
        j = x - i;
        k = i;
        
        while(j > 0)
        {
            printf(" ");
            j--;
        }
        
        while (k > 0)
        {
            printf("#");
            k--;
        }
        
        printf("\n");
    }
}

int main(void)
{
    int x = 0;
    while ((x < 1) || (x > 100))
    {   // avoiding that buffer overflow!
        printf("\nEnter an integer(1-100): ");
        scanf("%d", &x);
    }
    stairs(x);
    return 0;
}

Buffer Overflow incoming

2 Likes

Ok, I bit. I think I’ve taken care of that.

May have bugs, but they seem to work.

A Perl version

#!/usr/bin/perl

sub print_staircase
{
  for ($i = 0; $i < $_[0] + 1; $i++)
  {
    printf "%*s", $_[0] + 1, ("#" x $i) . "\n";
  }
}
print_staircase(6);

As a one-liner function

sub print_staircase{for($i=0;$i<$_[0]+1;$i++){printf "%*s",$_[0]+1,("#"x$i)."\n";}}

A C version abusing for syntax:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int print_staircase (int n)
{
  int  i;
  char *p = malloc (n);
  memset ((void*)p, ' ', n);

  for (i = 0, p[n -1] = 0, p[n - i - 1] = '#'; 
       i < n; 
       p[n - i - 1] = '#', i++, (printf ("%s\n", p)));


}

int main (void)
{
  print_staircase (6);
}

Yeah that C program is definitely an abuse of fors.

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.