Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's R journey — lesson 39 of 78.

While a for loop iterates through a predefined sequence, a while loop keeps running as long as a condition remains TRUE. This is useful when you don't know in advance how many times you need to repeat something.

count <- 1
while (count <= 3) {
  print(count)
  count <- count + 1
}

Output:

[1] 1
[1] 2
[1] 3

The loop checks the condition count <= 3 before each iteration. When count becomes 4, the condition is FALSE, and the loop stops.

Important: You must update the variable inside the loop. Without count <- count + 1, the condition would always be TRUE, creating an infinite loop that never ends.

total <- 0
num <- 1
while (num <= 5) {
  total <- total + num
  num <- num + 1
}
print(total)

Output:

[1] 15

This example adds numbers 1 through 5, resulting in 15. The while loop is ideal when the stopping point depends on a condition rather than a fixed sequence.

challenge icon

Challenge

Easy

Read a number n from input. Use a while loop to calculate and print the sum of all numbers from 1 to n.

Start with a variable to track your running total and another variable as your counter. Keep adding to the total while your counter is less than or equal to n, incrementing the counter each iteration.

After the loop completes, print the final sum using print().

For example, if the input is 5, the output should be:

[1] 15

This is because 1 + 2 + 3 + 4 + 5 = 15.

Cheat sheet

A while loop runs as long as a condition remains TRUE:

count <- 1
while (count <= 3) {
  print(count)
  count <- count + 1
}

The loop checks the condition before each iteration. When the condition becomes FALSE, the loop stops.

Important: Always update the variable inside the loop to avoid infinite loops:

total <- 0
num <- 1
while (num <= 5) {
  total <- total + num
  num <- num + 1
}
print(total)  # Output: [1] 15

While loops are ideal when the stopping point depends on a condition rather than a fixed sequence.

Try it yourself

# Read input
con <- file("stdin", "r")
n <- as.integer(suppressWarnings(readLines(con, n = 1)))

# Initialize variables
total <- 0
counter <- 1

# TODO: Write your while loop below to calculate the sum from 1 to n


# Print the result
print(total)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals