Course of Raku / Addendum 🆕 / Flow and functions / Control flow and logic / Exercises / Sum until over a hundred

Solution: Sum until over a hundred

Here is a possible solution to the task.

Code

my $sum = 0;
my $n   = 0;

loop {
    $n++;
    $sum += $n;
    last if $sum > 100;
}

say "reached $sum after adding 1..$n";

🦋 You can find the source code in the file sum-until.raku.

Output

reached 105 after adding 1..14

Comments

  1. A bare loop { } repeats forever; the last if $sum > 100 is what ends it, as soon as the total crosses the threshold.

  2. 1 + 2 + … + 14 is 105, the first partial sum over 100, so the loop stops with $n at 14.

Course navigation

Sum until over a hundred   |   Subroutines and functional style