if is an expression, it can be used for instance in let statement
a condition must be of type bool, a boolean.
the values potentially resulting from each arm of the if expression must be the same type
fn main() {
let condition = true;
let number = if condition { 8 } else { 6 }; // both 5 and 6 must be of the same type
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else {
println!("number is not divisible by 4 or 3");
}
}
the case in which the function calls itself with a smaller/simpler input
the recursive function must contain a condition to stop calling itself
fn main() {
let number: u32 = 5;
let result: u32 = factorial(number);
println!("Factorial of {number} is {result}.");
}
// recursive function returning factorial for given parameter
fn factorial(a: u32) -> u32 {
if a == 0 {
1
} else {
a * factorial1(a-1)
}
}
fn main() {
let number: u32 = 5;
let result: u32 = factorial(number);
println!("Factorial of {number} is {result}.");
}
// function with while loop returning factorial for given parameter
fn factorial(a: u32) -> u32 {
let mut result: u32 = 1;
let mut i: u32 = 1;
while i <= a {
result *= i;
i += 1;
}
result
}
executes a block of code for each element in an iterator (range of values)
ranges:
1..5: A (half-open) range. It includes all numbers from 1 to 4. It doesn’t include the last value, 5.
1..=5: An inclusive range. It includes all numbers from 1 to 5. It includes the last value, 5.
1..: An open-ended range. It includes all numbers from 1 to infinity (well, until the maximum value of the integer type).
..5: A range that starts at the minimum value for the integer type and ends at 4. It doesn’t include the last value, 5.
..=5: A range that starts at the minimum value for the integer type and ends at 5. It includes the last value, 5.
//using an array as an iterator
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a { //using a collection
println!("the value is: {element}");
}
}
//using reversed range as iterator
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
fn main() {
let number: u32 = 5;
let result: u32 = factorial(number);
println!("Factorial of {number} is {result}.");
}
// function with for loop returning factorial for given parameter
fn factorial3(a: u32) -> u32 {
let mut result: u32 = 1;
for i in 1..=a {
result *= i;
}
result
}