Урок 5

Операторы цикла


 

Пример 1. Пример цикла while

class While {
    public static void main(String args[]) {
        int n = 10;

        while (n > 0) {
            System.out.println("tick " + n);
            n--;
        }
    }
}

Пример 2. Пример цикла while

class NoBody {
    public static void main(String args[]) {
        int i, j;

        i = 100;
        j = 200;

        // find midpoint between i and j
        while (++i < --j) ; // no body in this loop

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

Пример 3. Пример цикла do-while

public class DoWhile {
    public static void main(String[] args) {
        int n = 10;
        do {
            System.out.println("tick " + n--);
        } while (n > 0);
    }
}

Пример 4. Пример цикла for

public class ForTick {
    public static void main(String args[]) {
        for (int i = 10; i > 0; i--) {
            System.out.println("tick " + i);
        }
    }
}

Пример 5. Пример цикла for

public class Comma {
    public static void main(String[] args) {
        for (int i = 1, j = 4; i < j; i++, j--) {
            System.out.println("i = " + i);
            System.out.println("j = " + j);
        }
    }
}

Пример 6. Пример цикла for-each

// Use a for-each style for loop.
class ForEach {
    public static void main(String args[]) {
        int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int sum = 0;

        // use for-each style for to display and sum the values
        for (int x : nums) {
            System.out.println("Value is: " + x);
            sum += x;
        }

        System.out.println("Summation: " + sum);
    }
}

Пример 7. Пример цикла for-each для двухмерного массива

// Use for-each style for on a two-dimensional array.
class ForEach3 {
    public static void main(String args[]) {
        int sum = 0;
        int nums[][] = new int[3][5];

        // give nums some values
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 5; j++)
                nums[i][j] = (i + 1) * (j + 1);

        // use for-each for to display and sum the values
        for (int x[] : nums) {
            for (int y : x) {
                System.out.println("Value is: " + y);
                sum += y;
            }
        }
        System.out.println("Summation: " + sum);
    }
}


0 comments
Leave your comment: