CSCI 2310
Fall 2009
Exercises for Quiz 2

  1. The following program fragment is not completely shown. The three dots represent some text that contains no break or return statements. Nothing is printed in the hidden part. It is known that this program fragment prints something. What does it print?

    1. i = 24
    2. i = 25
    3. i = 26
    4. It is impossible to say without more information.
            int i = 100;
            while(i != 25) {
              ...
              i = i + 1;
            }
            System.out.println("i = " + i);    // This line prints what?
    

    Answer

  2. What is the value of variable r when the following program fragment is finished?

            int k = 1;
            int r = 1;
            while(k != 10) 
            {
              if(k % 2 == 0) r = r + r;
              k = k + 1;
            }
    

    Answer

  3. The following loop sets variable m to

    1. 1 + ... + 9
    2. 1 + ... + 10
    3. 1 + ... + 11
    4. 1 + ... + 12
         int m,n;
         n = 0;
         m = 0;
         while(n < 10) {
           n = n + 1;
           m = m + n;
         }
    

    Answer

  4. Assume that variable n, of type int, has already been created and initialized to a positive integer. Write a Java program fragment that creates variable r and stores the sum 1 + 2 + ... + n into r.

    Answer

  5. Suppose that function Math.isPrime(n) is available, which returns true if n is prime and returns false if n is not prime. You do not need to write it. Just use it.

    Suppose that variable v, of type int, has already been created and initialized to a positive number. Write a Java program fragment that creates variable r, of type int, and stores into r the smallest prime number that is greater than or equal to v. For example, if v is 14, store 17 into r, and if v is 19, store 19 into r.

    Answer