Bird
0
0

You have a Bash array nums=(1 2 3 4 5). How do you print only the even numbers using a loop?

hard🚀 Application Q8 of 15
Bash Scripting - Arrays
You have a Bash array nums=(1 2 3 4 5). How do you print only the even numbers using a loop?
Afor n in ${nums[@]}; do if [ $n % 2 -eq 0 ]; then echo $n; fi; done
Bfor n in "${nums[@]}"; do if [ $n % 2 == 0 ]; then echo $n; fi; done
Cfor n in "${nums[@]}"; do if (( n % 2 == 0 )); then echo $n; fi; done
Dfor n in ${nums[@]}; do if (( n % 2 )); then echo $n; fi; done
Step-by-Step Solution
Solution:
  1. Step 1: Use correct arithmetic test syntax

    Bash arithmetic evaluation uses (( )) and == for comparison.
  2. Step 2: Loop over array with quotes to preserve elements

    Using "${nums[@]}" ensures each number is treated correctly.
  3. Final Answer:

    for n in "${nums[@]}"; do if (( n % 2 == 0 )); then echo $n; fi; done -> Option C
  4. Quick Check:

    Use (( )) for arithmetic tests in Bash = B [OK]
Quick Trick: Use (( )) for math tests and quote arrays when looping [OK]
Common Mistakes:
MISTAKES
  • Using [ ] with arithmetic operators incorrectly
  • Not quoting array expansion causing word splitting
  • Wrong condition logic in if statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes