Quiz

Q1

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

The for loop shown above is not valid as it does not have the initialization block.

true false It is not required for the 'for' loop to have an initilization block

Q2

public class ForLoopDemo{
    public static void main(String[] args){

        for(int i=0; i<10;){
            System.out.println(i);
            i++;
        }
    }
}

The for loop shown above is not valid as it has no update block.

true false It is not required for the 'for' loop to have an update block as long as the conditional section ends with a semicolon. However to ensure that you do not have an infinite loop which never ends, you have to ensure that the conditional becomes false after some interations through an update inside the loop body or you should add a break statement inside the loop body which ends the loop after some interations.

Q3

public class ForLoopDemo{
    public static void main(String[] args){

        for(int x=0; x<10;){
            System.out.println(x);
            x++;
        }
    }
}

The for loop shown above is not valid as it has 'int x= 0' instead of 'int i = 0'

true false You can name the variable used for representing number of interations what ever you want. While it is recommended that most other variables should have meaningful names, this is one of the few times where you are allowed to use typical single alphabets like i, n, m, x, y, z etc.. to represent the number of interations.

Q4

If the conditional is false, the do-while loop still executes the body of the loop once.

true false Yes, in a do-while loop, the conditional is evaulated after the loop body is executed once. This is not true in a while loop however. In a while loop the loop body is never executed if the conditional is false.

Q5

public class InfiniteWhileLoopDemo{
    public static void main(String[] args){

        while(true){
            // loop body statements go here
        }
    }
}

The above while loop should have a conditional break statement in the body of the loop, otherwise it will become a run away infinite loop.

true false Yes, although you can use while(true) construct, you should ensure that the loop ends after it hits a conditional which has a break statement which stops the loop from executing further.

results matching ""

    No results matching ""