CS 101 - Lab 8: Loops

Due at the end of lab seesion during the 9th week

 

Last week, you were working with the if statement in JavaScript.  This week, you will work with loops.  There are three basic types of loops: the for loop, the while loop and the do-while loop.  The book focuses on the for loop.  However, we will focus on the while loop first.  The syntax of the while loop is:

 

while ( cond )

                statement

where:

while

a keyword of the language

 

cond

the conditional expression which will be evaluated to either true or false.  The loop ends once this expression evaluates to false.

 

statement

the other statement(s) that will get execute repeatedly while the conditional expression evaluates to true.  Rarely is this a single statement, but normally a block of statements enclosed in curly braces.

 

The while loop has a potential problem called an infinite loop.  This is cause when the conditional expression is always true (it never evaluates to false).  This problem is the main reason why the book focuses on the for loop.  The statement(s) in the body of the while loop must somehow cause the conditional expression to evaluate to false after some number of executions.  The following is a JavaScript loop that keeps prompting for a value until an integer is given (assuming result and intResult are variables).

 

result = prompt ("Enter an integer value:", "")

parsedResult = parseInt (result)

 

while ( isNan(parsedResult))

                {

                  result = prompt ("Previous entered value of " + result + " is not an integer.\n" +

                                                   "Please enter an integer value:", "")

                  parsedResult = parseInt (result)

                }

 

The for loop is normally used when you wish to loop for a known number of times.  The for loop adds two elements to the while loop: an initialization clause and an increment clause.  The for loop normally has a "loop variable" that keep tracks of the number of times the code has gone through the loop.  The syntax of the for loop is:

 

for ( init ; cond ; incr )

                statement

 

where:

for

a keyword of the language

 

init

the initialization clause which will assign the initial value to  the loop variable

 

cond

the conditional expression which will be evaluated to either true or false.  The loop ends once this expression evaluates to false.

 

 incr

the increment clause which will specify how the loop variable will change each time through the loop

 

statement

the other statement(s) that will get execute repeatedly while the conditional expression evaluates to true.  Rarely is this a single statement, but normally a block of statements enclosed in curly braces.

 

The following example of a for loop will add together 100 random integers from 1 to 10:

 

sum = 0

 

for (count = 0 ; count < 100 ; count ++ )

                {

                   sum = sum + Math.floor (Math.random() * 10) + 1)

                }

 

The do-while loop is very similar to the while loop except the conditional expression is checked after the execution of the statements instead of before the statements.  This makes only a small bit of difference between the two.  A while loop can execute its statements zero or more times.  A do-while loop must execute its statements one or more times.  The syntax of the do-while loop is:

 

do           {

                    statement

}  

while ( cond )

 

where:

do

a keyword of the language

 

while

a keyword of the language

 

cond

the conditional expression which will be evaluated to either true or false.  The loop ends once this expression evaluates to false.

 

statement

the other statement(s) that will get execute repeatedly while the conditional expression evaluates to true.  The curly braces are required when using the do-while loop whether there is one or more statements in the body of the loop.

 

The above example for the while loop might requires the prompt statement to be executed at least once, so it is a good candidate for a do-while loop instead. Note that in this version there is not a different prompt message for the first prompt.

 

do           {

                  result = prompt ("Please enter an integer value:", "")

                  parsedResult = parseInt (result)

}

while ( isNan(parsedResult))

 

Lab Assignment

 

Create a JavaScript program that does decimal to binary conversion.  You will need 2 text fields and one button.  The first text field will hold the positive decimal value that the user will enter.  The second text field will hold the binary value that is created.  The button will create the binary value when clicked.  The binary value that is created is to be a character string and not a numeric result.  The conversion will require the use of integer division.

 

An integer division gives both an integer quotient and an integer remainder (this is the method most people are taught when they first learn division).  The slash operation "/" will perform real division.  To get the integer division result, we need to remove the decimal portion.  The floor() method of  the Math object will do this for us.  The modulus operation "%" gives us the remainder from an integer division.  If we were to perform integer division of 13 by 5, we would get an integer quotient of 2 and an integer remainder of 3.  In JavaScript,

 

 

To convert a decimal number X to binary, we perform the following steps:

 

While X is not zero:

1.             X % 2 gives us the next lowest binary digit

2.             Replace X with X/2 (the integer division quotient)

 

Look at the conversion of 25 to binary (the division being done must be integer division).

 

    25 % 2 -->  1  (the lowest binary digit)  ----------

    25 / 2 --> 12                                       |

    12 % 2 -->  0  (the second binary digit)  --------  |

    12 / 2 -->  6                                     | |

    6 % 2 -->  0  (the third binary digit)   ------  | |

    6 / 2 -->  3                                   | | |

    3 % 2 -->  1  (the fourth binary digit)  ----  | | |

    3 / 2 -->  1                                 | | | |

    1 % 2 -->  1  (the fifth binary digit)   --  | | | |

    1 / 2 -->  0                               v v v v v

            -->        Finished with result of : 1 1 0 0 1

 

This conversion would loop 5 times, each time producing one binary digit.  Since the number of times through the loop depends on the value we are converting, the while loop is the best to use for this.

 

To convert to other bases, you only have to change to value of the divisor used in the division and modulus operations.  I.E. To create a decimal to octal converter, the divisor is 8.