Review Exercises - Class 6

  1. Answer questions about the following code segment. Try and answer these questions by tracing the code by hand.
        int i, n, result;    
        i = 0;
        n = StdIn.readInt();
        result = 1;
        
        while (i < n) {
           result = result * 2;
           i = i + 1;
        }    
        StdOut.println(result);    
    
    1. If the user entered 10 what would the output be?
    2. If the user entered 0 what would the output be?
    3. For any non-negative integer n what does the code segment compute?
    4. Does the program "work" if the user enters a negative number? That is, is it consistent with your previous answer in part c?
  2. The factorial of an integer n, written n!, is 1·2·3···n-1·n. For example, 5! is 120. Write a Java program that asks for an integer from the user and computes the factorial of that integer.
  3. What is the output of the following program? Trace the program by hand and then check your answer by cutting and pasting the code into DrJava.
        int x, y;
    
        y = 0;    
        while (y < 5) {
         
          y = y + 1;
          x = 0;
    
          while (x < 6) {
            x = x + 1;
            StdOut.print('*');
          }
          StdOut.println();
        }
    
  4. Modify the program above so it produces the following output
    1
    12
    123
    1234
    12345