Home > Net >  Nested loop in while
Nested loop in while

Time:02-21

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("");
     }

}

Please guide me..Thanks

CodePudding user response:

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("");
     }
    }
}

CodePudding user response:

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("");
}
  • Related