Objective:
This problem focuses on constructing a visually formatted staircase by combining spaces and #
symbols appropriately, Which is a practice problem for loops and string manipulation.
Problem Statement:
You need to write a function that takes an integer n
and prints a staircase of height n. The stairs are right-aligned and consist of #
symbols and spaces.
Input Format:
- A single integer
n
representing the height of the staircase.
Output Format:
- Print a staircase consisting of
n
lines, where each linei
(1 ≤ i ≤ n) containsn-i
spaces followed byi
#
symbols.
Example 1:
Input: n = 4
Output:
#
##
###
####
#####
######
Explanation: It has 4 levels, with each level right-aligned and progressively increasing in the number of #
symbols.
Example 2:
Input: n = 3
Output:
#
##
###
Explanation: It has 3 levels, with each level right-aligned and progressively increasing in the number of #
symbols.
Example 3:
Input: n = 6
Output:
#
##
###
####
#####
######
Explanation: It has 6 levels, with each level right-aligned and progressively increasing in the number of # symbols.
Steps to Solve:
- Loop Through Levels: Use a loop to iterate through the levels of the staircase from 1 to
n
. - Print Each Level: For each level
i
, printn-i
spaces followed byi
#
symbols. - Right-Align Each Level: Ensure that the
#
symbols are right-aligned by preceding them with the correct number of spaces.
Problem Snippet
Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'staircase' function below.
*
* The function accepts INTEGER n as parameter.
*/
public static void staircase(int n) {
// Write your code here
for(int i=0; i<n; i++){
for(int j=n-1; j>=0; j--){
if(j<=i) System.out.print("#");
else System.out.print(" ");
}
System.out.println();
}
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
Result.staircase(n);
bufferedReader.close();
}
}