Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How many times will the following loops execute? Indicate whether each loop is a

ID: 3811458 • Letter: H

Question

How many times will the following loops execute? Indicate whether each loop is an infinite one:

for (var i = 0; i > 1; i++) { // do something

} _______________________________

for (var i= 1; i % 2 != 0; i = i +2 ) { // do something

}

  

for (var i = 1; i < 1000 ; i = i * (i+1) ) { // do something

}

Express following instructions in code: Given an array:

var myArray = [“the”, “big”, “bad”, “wolf”];
a. Print in the document the number of elements that array myArray contains:

______________________________


b. Change the value of the last two elements of the array with the value “red” “balloon”

c. In one line, print to the document (page) each element of the array from 0 to the end. You don’t need to use loops:

_____________________________________________________

Explanation / Answer

1. The statements inside the loop:

for (var i = 0; i > 1; i++) { // do something

} _______________________________

don't run at all for even once.

As soon as i is initialized with value 0 and the condition ( i > 1 ) is checked, the loop ends as the condition isn't met. This also indicates that it isn't an infite loop.

2. The statements inside the loop

for (var i= 1; i % 2 != 0; i = i +2 ) { // do something

}

run for infinite times.

As, the inital value of i is odd. It checks if the remainder on dividing i by 2 doesn't come to be 0. Since, every time the loop runs, it adds 2 to the value of i, which comes to be odd, and you can never get reaminder as 0 on dividing any odd number by 2, the condition is alway met. And the loop runs for infinity.

3. The loop:

for (var i = 1; i < 1000 ; i = i * (i+1) ) { // do something

}

runs for 4 times.

Let's take each pass in detail:

Pass 1: value for i = 1. Condition meets as 1 < 1000. New value of i = i * (i +1) = 2

Pass 2: value for i = 2. Condition meets as 2 < 1000. New Value of i = 2 * (2 + 1) = 6

Pass 3: value for i = 6, Condition meets as 6 < 1000. New value of i = 6 * (6 + 1) = 42

Pass 4: value fot i = 42, Condition meets as 42 < 1000. New value of i = 42 * (42 + 1) = 1806

After the 4th Pass, the loop exits as the condition doesn't match anymore. This is not an infinite loop.

Hope this helps...

BEST WISHES!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote