user759630
user759630

Reputation: 679

Incomplete output with while loop

I am supposed to give this output

* * * * *
 * * * * *
* * * * * *
 * * * * *

so on and so forth 5 itirations but it only shows the first 2 output

here's my code

public class itiration {

    public static void main( String args[]){

        int counter1 = 1;
        int counter2 = 1;
        int counter3 = 1;

        while(counter1<=5)
        {

                while(counter2<=5)
                {
                    System.out.print("* ");
                    System.out.print(" ");
                    counter2++;
                }

            System.out.println();

                while(counter3<=5)
                {
                    System.out.print(" ");
                    System.out.print("* ");
                    counter3++;
                }


            System.out.println();

            counter1++;
        }

    }

}

this is not a homework

Upvotes: 0

Views: 494

Answers (3)

Andrew Cooper
Andrew Cooper

Reputation: 32596

You're not resetting counter2 and counter3 for each iteration of the main loop. Try this:

    int counter1 = 1;
    while(counter1<=5)
    {        
        int counter2 = 1;
        int counter3 = 1;

Upvotes: 1

Mat
Mat

Reputation: 206861

You need to reset counter2 and counter3 in the loop (after counter1++ for example), otherwise they'll stay at value 5 after the first run of the loop, and the inner loops will not run any more.

Upvotes: 2

Amir Afghani
Amir Afghani

Reputation: 38551

Have you tried stepping through this program with a debugger?

HINT: After the outer loop executes its first iteration, what are the values of counter2 and counter3?

Upvotes: 3

Related Questions