Skip to content
Advertisement

Java Staircase is printing in wrong direction (hackerrank)

This solution to the staircase prints the correct output, but in the opposite direction. Any idea how to alter this solution to get the desired result?

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the staircase function below.
static void staircase(int n) {
int counter=0;
    for(int i=0; i<n;i++)
    {
        //for (int k=0; k<n-k-1;k++)
        //  {
        //      System.out.println("");
        //  }
        System.out.print("n");
        System.out.print("#");
        counter++;

        for(int j=0; j<counter-1;j++) 
        {

            System.out.print("#");
        }
    }   
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int n = scanner.nextInt();
    scanner.skip("(rn|[nru2028u2029u0085])?");

    staircase(n);

    scanner.close();
}
}

Input:

6

Expected output:

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

Actual Output:

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

It’s for a hackerrank easy challenge. I just want to be able to use my approach that I discovered instead of a solution I find online. Thanks!

Advertisement

Answer

You simply have to make two changes:

First you have to add a loop that will print spaces. If you start the loop at n and loop until more than or equal to i, while subtracting, this will print the correct amount of spaces.

Second, you need to have the newline at the end of the loop:

static void staircase(int n) {

   int counter=0;
   for(int i=0; i<n;i++)
   {
       counter++;
       for(int k=n; k>= i;k--)
       {
           System.out.print(" "); 
       } 
       for(int j=0; j<=counter-1;j++) 
       {
           System.out.print("#");
       }

       System.out.print("n");
   }
}  

Output:

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

Also just a note on your code. It is bad practice to close System.in. The general rule is that if you did not open a resource, you should not close it.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement