Bird
0
0

How can you modify this code to print all even numbers from 2 to 10 using a while loop?

hard📝 Application Q15 of 15
C - Loops
How can you modify this code to print all even numbers from 2 to 10 using a while loop?
int num = 1;
while (num <= 10) {
    printf("%d ", num);
    num++;
}
AUse a for loop instead of while loop
BInitialize num to 2 and increment by 2 inside the loop
CInitialize num to 0 and increment by 1 inside the loop
DKeep num at 1 and print only if num % 2 == 0 without incrementing
Step-by-Step Solution
Solution:
  1. Step 1: Set starting point and increment for even numbers

    Start num at 2 (first even number) and increase by 2 each time to get only even numbers.
  2. Step 2: Modify loop accordingly

    Change initialization to num = 2 and inside loop do num += 2 instead of num++.
  3. Final Answer:

    Initialize num to 2 and increment by 2 inside the loop -> Option B
  4. Quick Check:

    Start at 2, add 2 each time for evens [OK]
Quick Trick: Start at first even, add 2 each loop to get evens [OK]
Common Mistakes:
  • Not incrementing num causing infinite loop
  • Printing odd numbers by starting at 1
  • Using for loop when question asks for while loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Quizzes