Today we learn loop, do a task repeatly
What is loop
loop is used to repeat a block of code multiple times
we need to set when to start, how many times it repeats or condition to end loops
a loop never ends is called infinite loop
Three ways to loop
- for loop Iterates over a specified range of values. The loop variable takes each value in the range one by one
// Forward for loop
for i = 1 to 5 do
printfn "Jim has run %d laps" i
// Reverse for loop
for i = 5 downto 1 do
printfn "Days until birthday: %d days left" (i - 1)
- while loop Repeatedly executes the block of code as long as the condition remains true
let mutable counter = 1
while counter <= 5 do
printfn "Jim has run %d laps" counter
counter <- counter + 1
- recursive function Calls itself with updated parameters
syntax: let rec funcName
let rec recursiveLoop n =
if n > 0 then
printfn "Jim run 1 lap: %d laps left" (n - 1)
recursiveLoop (n - 1)
recursiveLoop 5
Understanding recursive function:
Imagine you have a set of Russian dolls, where each doll contains a smaller doll inside it
To find the smallest doll, you would:
- Open the current doll
- Check if there is another smaller doll inside
- If there is, repeat the process with the smaller doll
// Pseudocode
let findSmallestDoll doll =
if doll contains no smaller doll then
return doll
else
let innerDoll = open(doll) // smaller doll inside
findSmallestDoll(innerDoll)
How to choose
- for loop is simple and easy to understand when iterating over a known range of values
- while loop is useful when the number of iterations is not known beforehand
- recursive function making code more expressive and often easier to reason about
exercises:
- 1 + 2 + 3 + ... + 99 + 100 = ?
- 1 + 3 + 5 + ... + 97 + 99 = ?
answers:
question 1
- for
let mutable sum = 0
for i = 1 to 100 do
sum <- sum + i
printfn "Sum using for loop: %d" sum
- while
let mutable sum = 0
let mutable counter = 1
while counter <= 100 do
sum <- sum + counter
counter <- counter + 1
printfn "Sum using while loop: %d" sum
- recursive function
let rec sumRecursive n acc =
if n = 0 then acc
else sumRecursive (n - 1) (acc + n)
printfn "Sum using recursive function: %d" (sumRecursive 100 0)
question 2
- for
let mutable sum = 0
for i = 1 to 100 do
if i % 2 <> 0 then
sum <- sum + i
printfn "Sum using for loop: %d" sum
- while
let mutable sum = 0
let mutable counter = 1
while counter <= 100 do
if counter % 2 <> 0 then
sum <- sum + counter
counter <- counter + 1
printfn "Sum using while loop: %d" sum
- recursive function
let rec sumOddRecursive n acc =
if n = 0 then acc
else
let newAcc = if n % 2 <> 0 then acc + n else acc
sumOddRecursive (n - 1) newAcc
printfn "Sum using recursive function: %d" (sumOddRecursive 100 0)
Top comments (0)