Loops
We can use loops when we want to execute a part of code a certain number of times.
Here's an example:
for (initializing_variable; checking_condition; changing_variable_value)
{
//instructions to perform
}
See a 'for' loop example:
This example, for comparison purposes, shows two ways of printing ten numbers. It's obvious that loops greatly reduce the number of lines in the code: from ten we now have just two!
Look at the parenthesis in the first line of the loop:
- int i = 1
A variable with the initial value of 1 was declared because we want to display the numbers from one (if you want to start from ten, it's enough to write int i = 10 in the same place).
You can name your variable any way you want but by convention it is 'i'” : you will for sure keep seeing it while reading about loops.
- i <= 10
Next, there is a condition check: in our case we check if the „i” variable is less or equal 10 (because we want to print numbers including ten).
- i++
We change the value of the variable. '++' is an increment operator: it makes the value bigger by one. In the same place we could write the full operation: i = i + 1; it would also be correct. The effect would remain the same. But usually the shorthand is used.
Next, between the curly brackets, we write the instruction to be executed: we will print the 'i' variable incremented by one up to 10.
Tasks
Task 2
You can also count backwards. In that case the contents of the parentheses in the 'for' loop changes slightly: you enter the value to start from and where the loop must stop working. To illustrate it, code a New Year countdown: from 10 to 1 and then display the "Happy New Year!" message.
Example of the loop counting down::
The countdown starts from 20. We count until 'i' is greater than 9 (that is, to 10), by decrementing the value of 'i' by one (similarly to how i++ was incrementing by one).
Go to the second task:
Task 3
Write a loop that executes seven times. Declare an int type variable with a value of 10. With each iteration the loop is to add 100 to that variable.
Go to the third task: