4.8. Coding Practice with Loops

Rewrite the following code so that it uses a for loop instead of a while loop to print out all the integers from 5 to 1 (inclusive).

Answer: In a for loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the for loop as shown below.

Rewrite the following code to use a while loop instead of a for loop to print out the numbers from 1 to 10 (inclusive).

Rewrite the following code so that it uses a for loop instead of a while loop to print out all the integers from 5 to 15 (inclusive).

Rewrite the following code to use a while loop instead of a for loop to print out the numbers from 10 to 100 by 10’s (inclusive).

The following code should print the values from 1 to 10 (inclusive) but has errors. Fix the errors so that the code works as intended. If the code is in an infinite loop you can refresh the page in the browser to stop the loop and then click on Load History and move the bar above it to see your last changes.

The following code should print the values from 10 to 5, but it has errors. Fix the errors so that the code works as intended.

The following code should print the values from 10 to 1, but it has errors. Fix the errors so that the code works as intended.

Finish the code below to print a countdown from 100 to 0 by 10’s using a for or while loop.

Finish the code to print the value of x and " is even" if x is even and " is odd" if it is odd for all values from 10 to 1.

Finish the code below to print the values for 10 * x where x changes from 0 to 10 using a loop.

Finish the following code so that it prints a string message minus the last character each time through the loop until there are no more characters in message. The loop condition should test the length of the message. The loop body should print the message and then use substring to create a new message without the last character.

Finish the code to loop printing the message each time through the loop and remove an x from the message until all the x’s are gone.

Write a loop below to print the number of x’s in the string message. Use the indexOf and substring methods.

Write the code below to print a rectangle of stars (*) with 5 rows of stars and 3 stars per row. Hint: use nested for loops.

Write the code below to print a rectangle of stars (*) with 3 rows of stars and 5 stars per row.

Write the code below to print 55555, 4444, 333, 22, 1 with each on a different line.

You have attempted of activities on this page