java lab16

profilesalansari95
cps_150_lab_project_16.docx

CPS 150 Lab Project 16: The while Loop

Lab 16.1

Loops provide a mechanism for repeating a block of code called the loop body.  We begin this lab by experimenting with while loops, the simplest form of loop code.  Many loops are controlled with a single variable, which we will refer to as the loop control variable or the loop index

Consider the code below.  What is the output the program produces?  Try changing the assigned value (6) of the limit variable to various integer values (e.g., 10, 100, 0, -10).  What happens?  

/**

   A simple program that prints a loop control variable.

*/

public class SimpleLoop

{

   public static void main(String[] args)

   {

      int i = 0;

      int limit = 6;

      while (i < limit)

      {

         System.out.println("i = " + i);

         i++;

      }

   }

}

 

Lab 16.2

Consider the code below again.  What happens if you comment out the line that increments i (line 13)?  Will the program ever stop looping?

 

/**

   A simple program that prints a loop control variable.

*/

public class SimpleLoop

{

   public static void main(String[] args)

   {

      int i = 0;

      int limit = 6;

      while (i < limit)

      {

         System.out.println("i = " + i);

         i++; // line 13

      }

   }

}

 

Lab 16.3

Manipulating the loop control variable is a critical skill in learning to write code with loops.  Modify the program in Lab 16.1 so that it produces the following output:

 

i = 6

i = 8

i = 10

i = 12

i = 14

i = 16

i = 18

...

i = 98

 

What Do I Hand In?

Once you are done, submit your answers for Lab 16.1 and Lab 16.2, and upload the completed source code file (i.e., .java file) for Lab 16.3.