-1

I can write code for Christmas Tree using for loop. Now, I want to write that code with while loop. I just can't figure out what I'm doing wrong.

public static void main(String[] args) {
             int i = 0;
             int j =0;
             int k =0;
             while(i<10){
                 while(j<10-i){
                     System.out.print(" ");
                     j++;

                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;

                 }
                 ++i;
                 System.out.println("");

             }
}

I expect the output of code to be like the christmas tree. But, the actual output is:

          *
**
**
**
**
**
**
**
**
**
  • Did you try debugging your code? – Amongalen May 28 '20 at 13:33
  • check this https://stackoverflow.com/questions/30723247/creating-a-christmas-tree-using-for-loops – maha May 28 '20 at 13:34
  • 1
    Does this answer your question? [Creating a Christmas Tree using for loops](https://stackoverflow.com/questions/30723247/creating-a-christmas-tree-using-for-loops) – maha May 28 '20 at 13:34

1 Answers1

1

You just need to put the loop indices j and k into the outer loop, such that they are reset to 0 in each iteration.

public static void main(String[] args) {
             int i = 0;
             while(i<10){
                 int j = 0;
                 int k = 0;
                 while(j<10-i){
                     System.out.print(" ");
                     j++;
                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;
                 }
                 ++i;
                 System.out.println("");
             }
}

Then it will print the following tree:

          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
Karlheinz
  • 56
  • 3