For Over Series
Part of the Fundamentals section of Coddy's Rust journey. Lesson 37 of 75.
Sometimes when programming it's necessary to perform same or almost the same operation a couple of times.
To prevent writing the same thing over and over again we can use Loops.
The for loop has the following syntax
for element in range {
code
}A range expression defines how many times the loop should run, typically written as start..end (which runs from start to end-1) or start..=end (which runs from start to end, including end).
For example, a loop from 0 to 5 (not including):
for i in 0..5 {
println!("{}", i);
}It will execute the print statement 5 times:
0
1
2
3
4Loops have many use cases. For example, let's sum all the numbers from 1 to 100:
let mut sum_numbers = 0;
for i in 1..=100 {
sum_numbers += i;
}
println!("{}", sum_numbers);This will first loop through all numbers between 1 to 100 (including 100 because of ..= sign) and sum all of them, then it will print the sum_numbers variable
If for some reason you want to create a loop without using a variable (i), you should add underscore at the start of the name: _i. This will tell the compiler that it is okay that it is not used, and it will prevent the program to produce a warning:
for _i in 0..5 {
println!("Hello!");
}Challenge
BeginnerRead an integer n (the starter code already does this). Use a for loop to print "Hello Coddy: " and the i value for every number from 3 to n, both included.
For example, if n is 6, the output is:
Hello Coddy: 3
Hello Coddy: 4
Hello Coddy: 5
Hello Coddy: 6If n is 27, the loop prints 25 lines, from Hello Coddy: 3 to Hello Coddy: 27.
Try it yourself
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
// Write your code below
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic InputPractice on your own: Online Rust compiler