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;
      inputBox.getInteger();
    } 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. You may assume that the variable outputBox is an OutputBox object.
    	int a = 5, b = 3;
    	for (int i = 0; i < 4; i++) {
    	   a += i;
    	   switch (a % 4) {
    	      case 0:   outputBox.printLine("zero");
    	                break;
    	      case 1:   outputBox.printLine("one");
    	      case 2:   outputBox.printLine("two");
    	                break;
    	      default:  outputBox.printLine("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 inputBox is an InputBox 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 variable outputBox is an OutputBox object and 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:
    		********
    		*      *
    		*      *
    		*      *
    		********