Lecture 9: Loops I: for |
For loop |
for (startI;
testC;
stepI)
instruction; |
with startI and stepI
general instructions and testC a
Boolean condition. This will repeat the instructions instruction
and stepI until the test
condition
results in "false".
The
instruction
is repeated a number of times, determined by the control instructions startI
and stepI and the test condition
testC.
The control instructions startI
and
stepI
can be any instruction or even combination of instructions (separated
by
commas).
The startI instruction is only executed at the beginning of the loop and only executed once. Immediately after that, the condition testC is evaluated. If this results is "false" (0), the loop is immediately exited. Hence it is possible with the for loop that the instruction is not even executed a single time (contrary to the do .. while loop as we will see in the next lecture). If the result of the condition is "true" (!=0), the instructions instruction and stepI are executed. |
This program is doing the following
|
Just like with the if ... else ... structure, we
can also group instructions together with {..} in
loops:
for (i = 1; i<5; i++) { printf("Ola\n"); printf("It is a nice day\n"); } |
output
Ola It is a nice day Ola It is a nice day Ola It is a nice day Ola It is a nice day |
Compare this with
for (i = 1; i<5; i++) printf("Ola\n"); printf("It is a nice day\n"); |
output
Ola Ola Ola Ola It is a nice day |
Good code:
|
Bad code:
|
program code
for (i=1; i<5; i++) printf("%d Ola", 2*i-1); |
output
1 Ola 3 Ola |
Nested loops
|
|
|
||||
|
|
Fibonacci numbers are numbers that follow the following
rules:
F1 =1 F2 = 1 Fn = Fn-1 + Fn-2 |
The program below implements this. The user is asked to give the number of Fibonacci numbers to calculate (n) and then, in a for-loop, the next Fibonacci number is calculated, until there are enough numbers.
main()
/* program to calculate the first n Fibonacci
numbers
using the algorithm
F(1) = 1, F(2) = 1 and F(i)
= F(i-1) + F(i-2) */
{
int i, n, fi, fi1, fi2;
// first ask the user for the
number
of Fibonacci numbers to calculate
printf("How many Fibonacci numbers
do you want to see?\n");
scanf("%d", &n);
fi1 =
1;
// variables to store F(i-1) and F(i-2)
fi2 =
1;
// initialize them to their starting value
printf("1 1
");
// print the first 2 Fibonacci numbers
// we are going to do something in
a countable way, so we will use
// the for-loop structure:
for (i=3; i<=n; i++)
// print the rest
{
fi = fi1 +
fi2; // calculate the next number
fi2 =
fi1;
// calculate the new F(i-1) and F(i-2)
fi1 = fi;
printf("%d
", fi); // print the result
}
}
Later we will learn a much more elegant way to calculate Fibonacci
numbers using recursive programming.