7. For Loops Flashcards
1
Q
incrementing and decrementing variable values
A
use ++ or –
2
Q
++
A
increment operator
x++ is equivalent to x = x + 1
3
Q
–
A
decrement opereator
x– is equivalent to x = x - 1
4
Q
syntax of for loop example
A
for (i = 1; i <= n; i++) {
..
..
}
can also initialise i in the () brackets
5
Q
eg. do something 100 times
A
for (int i = 0; i < 100; i ++)
6
Q
general form of for statement
A
for (initial statement; loop condition; update statement) {
statement(s)
}
7
Q
infinite loops
A
infinite loops should also be avoided like for while loops
8
Q
while vs for loops
A
use FOR when problem can be formulated as:
- for each integer from i to k
- for each element in list
- for each entry in array
use WHILE if FOR doesn’t fit the bill
9
Q
Nested loops
A
we freq need to nest one loop inside another