'Nested loop in while

I created a nested loop using For, here is the program code and the ouput, then I tried the while loop and get the different result:

  • For:
    public class ForBersarang {
    public static void main(String[] args){
        int a = 5;
        for(int i = 0; i<=a; i++){
            for(int j = 0; j<=i; j++){
                System.out.print("*");
            }
            System.out.println("");
        }
    }
  • While
    public class WhileBersarang {
    public static void main(String[] args){
        int i = 0;
        int a = 5;
        int j = 0;
         while (i<=a) {
             while (j <= i) {
                 System.out.print("*");
                 j++;
             }
             i++;
             System.out.println("");
         }
    }


Solution 1:[1]

Your problem is where you define j:

public class MyClass {
    public static void main(String args[]) {
      int i = 0;
      int a = 5;
    
      while (i<=a) {
         //here
         int j = 0;
         while (j <= i) {
             System.out.print("*");
             j++;
         }
         i++;
         System.out.println("");
     }
    }
}

Solution 2:[2]

In the inner while loop when j > i and you break out you must then re-assign j = 0; otherwise, j will always equal i.

int i = 0;
int a = 5;
int j = 0;
while (i <= a) {
    while (j <= i) {
        System.out.print("*");
        j++;
    }
    i++;
    j = 0;    //  re-assign j back to 0. 
    System.out.println("");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hous
Solution 2