Search code examples
javanested-loops

Java: How can I fix this nested loops


Integer inputNum is read from input. For each number from 1 to inputNum, output the number followed by the number's value of hashtag characters ('#'). End each output with a newline.

Ex: If the input is 5, then the output is:

1# 2## 3### 4#### 5#####

This is what I tried but the problem is that I don't know how to fix it so in the output, the character (in this case "#") is applied as many times as the number.

for instance, for input 5, my output was:

1##### 2##### 3##### 4##### 5#####

import java.util.Scanner;

public class LoopPatterns {
   public static void main (String[] args) {
      Scanner scnr = new Scanner(System.in);
      int inputNum;
      int i;
      int j;

      inputNum = scnr.nextInt();
  
      for (i = 1; i <= inputNum; ++i){
         System.out.print(i);
      for (j = inputNum; j >= 1; --j){
      System.out.print("#");
      }
      System.out.println();
      }

   }
}

Solution

  • The inner loop should count down from i. Like,

    for (i = 1; i <= inputNum; ++i) {
        System.out.print(i);
        for (j = i; j >= 1; --j) {
            System.out.print("#");
        }
        System.out.println();
    }