Try It Yourself: loops

  1. Determine the loop number(s) for the code that is an example of each term below. Note that you may use some of the loop numbers more than once.
    1. count-controlled loop
    2. sentinel-controlled loop
    3. infinite loop
    4. imprecise loop counter
    5. pretest loop
    6. posttest loop
    Loop 1
    Loop 2
    sum = 0;
    x = 4;
    while (x <= 50) {
      sum += x;
      x++
    }
    x = 0;
    while (x < last){
      total *= x;
      x += 5;
    }
    Loop 3
    Loop 4
    x = 0;
    do {
      total += x;
      x = stdin.nextInt();
    } while (x != -1);
    x = 0.33333333;
    while (!(total == target)) {
      total += x;
      count++;
    }
    Loop 5
    Loop 6
    sum = 0;
    x = 10;
    do {
      sum += x;
      x++
    } while (x < 200);
    x = 1;
    while (x <= 10) {
      total += x;
    }


  2. What is the output for the code fragment below.
    	int a = 5, b = 3;
    	for (int i = 0; i < 4; i++) {
    	   a += i;
    	   switch (a % 4) {
    	      case 0:   System.out.println("zero");
    	                break;
    	      case 1:   System.out.println("one");
    	      case 2:   System.out.println("two");
    	                break;
    	      default:  System.out.println("three");
    	                break;
    	   }
    	}
    	
  3. Write a code fragment that prompts a user for an integer until the user enters an integer that is evenly divisible by 4 or 7. You may assume that the variable stdin is a Scanner object.


  4. Write a code fragment that draws the outline of a rectangle with a given number of rows and columns. You may assume that the variables row and col are ints holding the number of rows and columns, respectively. For example, if row = 5 and col = 8, the following should be printed out:
    		********
    		*      *
    		*      *
    		*      *
    		********
    	
  5. Complete the countLower method. This method takes a string as a parameter and returns the number of lower-case letters in the string.
    public static int countLower(String str) {