Back to all lessons


Lesson 5

For, while, do-while

Make your code executing forever

Introduction

Read snippets below and complete task 0.

public class IncrementingClass {
    public static void main(String[] args) {
        int myVariable = 1;
        System.out.println(myVariable);
        myVariable++;
        System.out.println(myVariable);
        myVariable--;
        System.out.println(myVariable);
    }
} 
public class AddingClass {
    public static void main(String[] args) {
        int myVariable = 10;
        
        // first way:
        myVariable = myVariable + 10;

        // another way:
        myVariable += 10;
    }
}
Task 0

Try to multiply (character "*") an variable using code from AddingClass.

Using loops

Execute code below. What is the result? Next, complete task 1 and 2.


public class WhileClass {
    public static void main(String[] args) {
        
        int i = 0;
        while (i < 10) {
            System.out.println(i);
            i++;
        }

    }
}
Task 1

Count from 10 to 1.

Task 2

Write numbers from [10, 20], which are multiplication of 3.

Using for-loops

Execute code below. What is the result? Next, complete task 3 and 4.


public class ForClass {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }

    }
}
Task 3

Compare results of for-loop and while-loop. Are they working in the same way?

Task 4

Read two variables from user (using scanner). Create a program, that will count in range set by input.

Using do-while-loops

Execute code below. What is the result? Next, complete task 5.


public class DoWhileClass {
    public static void main(String[] args) {
        boolean strangeCondition = false;
        do {
            System.out.println("Am I visible?");
        } while (strangeCondition);

    }
}
Task 5

Write a program, that shows difference between while and do-while.

Task 6

Using System.out.print create a program, which prints stars for n-lines, where n is a given integer.

// when n = 5:
*
**
***
****
*****