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] 3The 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] 15This 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
EasyRead 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] 15This 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] 15While 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)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values