In this tutorial, we will learn about for loops in Rust. We will cover the basics of iterative execution using for loops.
A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.
The syntax for the for loop in Rust is:
for item in iterable {
// Code block to be executed
}
The for loop iterates over each item in the iterable object (such as an array, vector, or iterator) and executes the code block for each item.
fn main() {
for i in 1..=10 {
print!("{} ", i);
}
}
1 2 3 4 5 6 7 8 9 10
fn main() {
let n = 5;
let mut factorial = 1;
for i in 1..=n {
factorial *= i;
}
println!("Factorial of {} is {}", n, factorial);
}
Factorial of 5 is 120
fn main() {
let arr = [1, 2, 3, 4, 5];
let mut sum = 0;
for &num in &arr {
sum += num;
}
println!("Sum of the elements in the array is {}", sum);
}
Sum of the elements in the array is 15