L04: Repetition Flashcards
What are the 3 types of loops?
while, do-while, for
Describe a while loop.
While a condition is true, the statement is executed repeatedly.
What happens when a condition is always true in a while loop?
Infinite loop.
Describe a do-while loop.
The statement is executed before the condition is evaluated.
What’s the main difference between while and do-while?
The do-while loop executes the statement at least one time.
Describe the 4 elements in a for loop.
initialization A. condition B. statement C. update D
for (A; B; D)
C;
Are expressions in a for loop optional?
Yes, any part can be omitted, however the semi-colons must remain.
ex. for (int j=0; ; j++)
When should we use while vs for.
while is used when we don’t know how many times we want to execute a statement. for is used when we know how many times we want to execute a loop body.
for (i=0, sum=0; i<10; sum+=i,i++);
Is this valid syntax?
Yes, the for loop is executed however, no statement is executed.
If we want multiple expressions in a for loop what can we use?
Commas separating each expression can be used.
ex. for(i=0, j-1; i<=10; i++, j*=2) –> VALID