0
0
Cprogramming~5 mins

For loop in C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic structure of a for loop in C?
A for loop in C has three parts inside parentheses: initialization, condition, and update. It looks like: <br>
for (initialization; condition; update) {<br>  // code to repeat<br>}
Click to reveal answer
beginner
What happens if the condition in a for loop is false at the start?
The code inside the for loop does not run at all. The loop ends immediately.
Click to reveal answer
beginner
How can you use a for loop to print numbers from 1 to 5?
You can write:<br>
for (int i = 1; i <= 5; i++) {<br>  printf("%d\n", i);<br>}
This prints numbers 1, 2, 3, 4, 5 each on a new line.
Click to reveal answer
intermediate
Can the update part of a for loop be empty?
Yes, the update part can be empty, but you must update the loop variable inside the loop body to avoid an infinite loop.
Click to reveal answer
intermediate
What is an infinite loop and how can it happen with a for loop?
An infinite loop happens when the loop's condition never becomes false. For example, if you forget to update the loop variable, the loop runs forever.
Click to reveal answer
Which part of the for loop runs first?
ACondition check
BInitialization
CUpdate
DLoop body
What happens if the condition in a for loop is false initially?
AThe loop body runs once
BThe loop runs infinitely
CThe update runs once
DThe loop body never runs
Which of these is a correct for loop header to count from 0 to 9?
Afor (int i = 0; i < 10; i++)
Bfor (int i = 1; i <= 10; i++)
Cfor (int i = 10; i > 0; i--)
Dfor (int i = 0; i <= 10; i--)
What must you do if you leave the update part empty in a for loop?
AAdd a break statement
BNothing, it works fine
CUpdate the loop variable inside the loop body
DUse a while loop instead
What is the output of this code?<br>for (int i = 1; i <= 3; i++) { printf("%d", i); }
A123
B1 2 3
C321
DError
Explain the three parts of a for loop and their roles.
Think about what happens first, what keeps the loop running, and how the loop variable changes.
You got /4 concepts.
    Describe how a for loop can cause an infinite loop and how to prevent it.
    Focus on the condition and updating the loop variable.
    You got /4 concepts.