Course of Raku / Essentials / Loops / Exercises / Division via subtraction
Solution: Division via subtraction
The division is repeated subtraction. The program has a while
loop that reduces $a
by the value of $b
and repeats it while the current value of $a
is not less than $b
. The variable $n
counts the number of iterations, and it is also the result that we need.
Code
Here is the full program:
my $a = 175;
my $b = 25;
my $n = 0;
while $a >= $b {
$a -= $b;
$n++;
}
say $n;
🦋 Find the program in the file division-via-subtraction.raku.
Output
Run the program a few times. Start with the given values which give an exact integer:
$ raku exercises/loops/division-via-subtraction.raku
7
Also try, for example, to change $b
to 20
and confirm that the result is correct:
$ raku exercises/loops/division-via-subtraction.raku
8
Next exercise
Course navigation
← Conditional checks / Ternary operator | Data type conversion →
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська