Lesson 6 - Loops

Rust provides three main type of loops: loop, while, and for

A loop repeates indefinitely. To exit, use the break keyword.

let mut count = 0; 

loop { 
  println!("{}", count); 
  
  count += 1; 
  
  if count == 5 { 
    break; 
  } 
}

This would print:

0
1
2
3
4

A while loop runs while a condition remains true.

let mut count = 0; 
while count < 5 { 
  println!("{}", count); 
  count += 1; 
}

This would output the same as the previous program.

A for loop is useful for going through ranges and collections.

for number in 1..6 { 
  println!("{}", number); 
}

This would output the numbers 1-5, as number would range from 1-5, not including 6.

To include 6, we would use the range 1..=6.