For Loop
Part of the Fundamentals section of Coddy's R journey — lesson 38 of 78.
Sometimes you need to repeat an action multiple times. Instead of writing the same code over and over, you can use a for loop to execute code repeatedly.
A for loop iterates through a sequence of values, running the code inside the loop once for each value:
for (i in 1:3) {
print(i)
}Output:
[1] 1
[1] 2
[1] 3The variable i takes on each value in the sequence 1:3 (which means 1, 2, 3). For each value, the code inside the curly braces { } runs once.
You can use any variable name and perform any operations inside the loop:
for (num in 1:4) {
print(num * 2)
}Output:
[1] 2
[1] 4
[1] 6
[1] 8The loop multiplies each number by 2 before printing it. This is the power of loops - write the logic once, and it applies to every value in your sequence.
Challenge
EasyRead a number n from input and use a for loop to print the squares of all numbers from 1 to n.
Each square should be printed on its own line using print().
For example, if the input is 4, the output should be:
[1] 1
[1] 4
[1] 9
[1] 16Cheat sheet
A for loop executes code repeatedly by iterating through a sequence of values:
for (i in 1:3) {
print(i)
}The variable i takes on each value in the sequence 1:3. The code inside the curly braces { } runs once for each value.
You can use any variable name and perform operations inside the loop:
for (num in 1:4) {
print(num * 2)
}Output:
[1] 2
[1] 4
[1] 6
[1] 8Try it yourself
# Read input
con <- file("stdin", "r")
n <- as.integer(suppressWarnings(readLines(con, n = 1)))
# TODO: Write your code below
# Use a for loop to print the square of each number from 1 to nThis 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