Skip to Content
Learn
Loops
while Loop

When repeating code we may not have a range or defined collection to dictate the number of loops we need to execute. In this case, we can rely on a while loop which repeats code as long as a specified condition is true. If we revisit the animation in the first exercise, we can see that Codey uses a while loop to hike until time is no longer less than 17.

A while loop is similar to an if expression because it tests a condition and when the condition is true a body of code is executed. The main difference is the while loop will complete the body of code, check the condition, and repeat the code if the condition is still true. If the condition is false, the while loop is done and the program moves on:

var myAge = 16 while (myAge < 20) { println("I am a teenager.") myAge += 1 } println ("I am not a teenager.")

In this example the while loop condition myAge < 20 initially evaluates to true. The loop body is executed which outputs some text and myAge is incremented. The loop repeats until myAge equals 20 at which point the loop exits and continues running code outside the loop:

I am a teenager. // myAge is 16 I am a teenager. // myAge is 17 I am a teenager. // myAge is 18 I am a teenager. // myAge is 19 I am not a teenager. // myAge is 20

If myAge wasn’t incremented inside the loop body the loop condition would always be true and repeat forever. This is known as an infinite loop. Infinite loops lead to application crashes or other unwanted behavior so it is important that they are avoided.

When a while loop condition never evaluates to true, the entire block of code is skipped:

var myAge = 11 while (myAge > 12 && myAge < 20) { println("I am a teenager.") myAge += 1 } println ("I am not a teenager.")

Since we’ve set the value of myAge to 11 and the condition will only be true once the value is between 12 and 20, the code block is skipped and the final println() gets executed:

I am not a teenager. // myAge is 11

Instructions

1.

Create a while loop that:

  • repeats as long as the variable counter is less than 5.
  • uses println() in the loop body to output the variable counter.
  • increments the variable counter by 1 in the loop body.
2.

A while loop condition can also check the elements of a collection. You’ll use another counter variable, index, to access the collection’s elements.

Implement a second while loop that:

  • has the condition, schoolGrades[index] != "6th".
  • uses println() in the loop body to output the current element value of schoolGrades.
  • increments the variable index by 1 in the loop body.

When you’re done, you’ll see that the while loop exits once the element “6th” is the current one.

Folder Icon

Take this course for free

Already have an account?