Count and Sum [1/8]
Count and Sum
The fourth statement of this program increases the value of variable b by 6.
After running the program, add an additional statement that multiplies the value of variable b by 3. Then output the value of variable b.
Here are four different ways to increase the value of a variable by 1.
All the given statements that change the value of a variable are statements of assignment.
Here are some other forms of the statement of assignment. They are used to modify the value of a variable.
This program prints out the first 10 odd numbers.
After running the program, modify it so that it outputs every third number starting from number 10.
After that, modify the program so that it outputs every third number starting from number 22 and ending at 61.
After that, modify the program so that it also outputs the value of variable i on each iteration.
After that, modify the program so that it outputs the first 12 positive whole numbers which are divisible by 6 (6, 12, 18, 24, ...).
This program calculates the sum of the first 10 natural numbers.
What is the sum of the first 100 natural numbers?
This program calculates the sum of squares of the first 9 natural numbers.
Important:
a variable introduced inside a statement block gets removed
when the statement block has completed the execution.
In this example, the variable x,
which is introduced inside a statement block,
is not available outside the statement block.
The loop control variable i
is also not available outside the loop.
This program rolls the dice 15 times and counts how many times it got a 6.
After running and examining the program, add a new variable named countFives with an initial value of 0 to the beginning of the source code.
Modify the program so that it also counts how many times the number 5 was rolled, by using the variable countFives. After the loop, output the value of variable countFives.
Exercise:
Reload the original source code by pressing a key F5, or by using a key combination Ctrl-R, or by using your browser's 'Reload' button on the toolbar.
Modify the program so that it rolls two dice 15 times. It should count how many times it got doubles.
Solution
... #num dice1 = rn(6); #num dice2 = rn(6); println "Dice roll: ", dice1," ",dice2; if dice1=dice2 ...
This program calculates the sum of 9 random numbers.
After running and examining the program, modify it so that it sums up only those numbers that are smaller than 10. To accomplish that, use an if statement.
Solution
... if x<10 { sum += x; println " Sum so far: ", sum; } ...
<< F2:Prev - - F4:Next >>