Rayee
Rayee

Reputation: 1

How to write a While Loop for Simple Increments?

I will need to write a WHILE loop for the following: "hello" is part of the output

8 9 11 14 hello 18

    while(counter < 18 )
    {
        System.out.print(" " + counter);

        counter = counter + 1 ;

        if(counter > 14 && counter < 18){
            System.out.print(" hello ");
        }

    }

The above is my sample code. I am unable to figure out how to increase it by 1, 2 then 3. Can anyone help , please?

Upvotes: 0

Views: 9256

Answers (2)

Yordan Borisov
Yordan Borisov

Reputation: 1652

Try this :

        int counter = 8;
        int inc = 1;
        while ( counter <= 18 )
        {
            System.out.print ( " " + counter );
            if ( counter >= 14 && counter < 18 )
            {
                System.out.print ( " hello " );
            }
            counter = counter + inc;

            inc += 1;
        }

Upvotes: 1

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

You need an additional variable that stores the amount by which you increment. This variable itself has to be incremented by one in each run of the loop.

Upvotes: 4

Related Questions