Bird
0
0

You want to write a bash script that prints all even numbers from 2 to 10 using a while loop. Which script correctly does this?

hard🚀 Application Q15 of 15
Bash Scripting - Loops
You want to write a bash script that prints all even numbers from 2 to 10 using a while loop. Which script correctly does this?
Anum=1 while [ $num -le 10 ]; do if [ $((num % 2)) -eq 0 ]; then echo $num; fi num=$((num + 1)) done
Bnum=2 while [ $num -le 10 ]; do echo $num num=$((num + 1)) done
Cnum=2 while [ $num -lt 10 ]; do echo $num num=$((num + 2)) done
Dnum=0 while [ $num -le 10 ]; do echo $num num=$((num + 2)) done
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to print even numbers from 2 to 10 inclusive.
  2. Step 2: Check each option's logic

    num=2 while [ $num -le 10 ]; do echo $num num=$((num + 1)) done starts at 2 and increments by 1 up to 10, printing 2 3 4 5 6 7 8 9 10 - incorrect.
    num=1 while [ $num -le 10 ]; do if [ $((num % 2)) -eq 0 ]; then echo $num; fi num=$((num + 1)) done starts at 1, increments by 1, and prints only if even - correct.
    num=2 while [ $num -lt 10 ]; do echo $num num=$((num + 2)) done stops before 10, missing 10.
    num=0 while [ $num -le 10 ]; do echo $num num=$((num + 2)) done starts at 0, which is even but outside requested range (2 to 10).
  3. Step 3: Choose the best option

    Only the script using modulo to explicitly check evenness prints exactly 2,4,6,8,10.
  4. Final Answer:

    num=1 while [ $num -le 10 ]; do if [ $((num % 2)) -eq 0 ]; then echo $num; fi num=$((num + 1)) done -> Option A
  5. Quick Check:

    Check even with modulo inside loop [OK]
Quick Trick: Use modulo inside loop to print even numbers [OK]
Common Mistakes:
MISTAKES
  • Stopping loop before 10
  • Starting from 0 when 2 is required
  • Not checking evenness explicitly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes