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:
Step 1: Understand the goal
We want to print even numbers from 2 to 10 inclusive.
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).
Step 3: Choose the best option
Only the script using modulo to explicitly check evenness prints exactly 2,4,6,8,10.
Final Answer:
num=1
while [ $num -le 10 ]; do
if [ $((num % 2)) -eq 0 ]; then echo $num; fi
num=$((num + 1))
done -> Option A
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
Master "Loops" in Bash Scripting
9 interactive learning modes - each teaches the same concept differently