Bird
0
0

You want to write a script that prints "Even" if a number stored in n is even, and "Odd" otherwise. Which of these is the correct if-then-fi structure to do this?

hard🚀 Application Q15 of 15
Bash Scripting - Conditionals
You want to write a script that prints "Even" if a number stored in n is even, and "Odd" otherwise. Which of these is the correct if-then-fi structure to do this?
Aif [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi
Bif [ $n % 2 == 0 ]; then echo "Even"; else echo "Odd"; fi
Cif (( n % 2 == 0 )) then echo "Even"; else echo "Odd"; fi
Dif [ $n / 2 -eq 0 ]; then echo "Even"; else echo "Odd"; fi
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to check evenness in bash

    We use arithmetic expansion $(( )) to calculate remainder of n divided by 2. If remainder is 0, number is even.
  2. Step 2: Analyze each option's correctness

    if [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi correctly uses [ $((n % 2)) -eq 0 ] with then, else, fi. if [ $n % 2 == 0 ]; then echo "Even"; else echo "Odd"; fi uses invalid syntax inside [ ]. if (( n % 2 == 0 )) then echo "Even"; else echo "Odd"; fi misses semicolon before 'then' causing syntax error. if [ $n / 2 -eq 0 ]; then echo "Even"; else echo "Odd"; fi incorrectly uses division instead of modulo.
  3. Final Answer:

    if [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi -> Option A
  4. Quick Check:

    Modulo with $(( )) inside [ ] and proper if-then-fi = A [OK]
Quick Trick: Use $(( )) for math inside [ ] in if-then-fi [OK]
Common Mistakes:
MISTAKES
  • Using % inside [ ] without $(( ))
  • Using == instead of -eq for numbers
  • Confusing division with modulo

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes