Looping Through Numbers: A Shell Script for Even and Odd Detection
Understanding how to manipulate numbers and identify their properties is fundamental in programming. This article will guide you through writing a simple shell script to loop through numbers from 0 to 100, determine if each number is even or odd, and print the results.
The Problem: We want to automate the process of identifying whether a range of numbers are even or odd, rather than manually checking each number.
The Solution: We can use a loop to iterate through the numbers, and a simple conditional statement to determine if each number is divisible by 2 (even) or not (odd).
The Shell Script
#!/bin/bash
for i in $(seq 0 100); do
if (( i % 2 == 0 )); then
echo "$i is even"
else
echo "$i is odd"
fi
done
Explanation:
#!/bin/bash
: This line indicates the script is to be run with the bash interpreter.for i in $(seq 0 100); do
: This line initiates a loop that iterates through numbers from 0 to 100.seq 0 100
generates a sequence of numbers from 0 to 100.for i in ...
assigns each number from the sequence to the variablei
for each iteration.
if (( i % 2 == 0 )); then
: This line checks if the current numberi
is divisible by 2 with no remainder.i % 2
calculates the remainder wheni
is divided by 2.== 0
checks if the remainder is equal to 0, signifying an even number.
echo "$i is even"
: This line prints the numberi
and "is even" if the condition is true.else
: This line executes if the previous condition is false (meaning the number is odd).echo "$i is odd"
: This line prints the numberi
and "is odd" if the condition is true.fi
: This line marks the end of theif
statement.done
: This line marks the end of thefor
loop.
Running the Script:
- Save the code in a file named
even_odd.sh
. - Make the script executable using
chmod +x even_odd.sh
. - Run the script by typing
./even_odd.sh
.
Output: The script will print a list of numbers from 0 to 100, indicating whether each number is even or odd.
Key Insights
- Modulus operator (
%
): The modulus operator is crucial for determining even/odd numbers. It returns the remainder after a division operation. - Shell Scripting: Shell scripts are powerful tools for automating repetitive tasks, such as this even/odd check.
- Conditional Statements (
if
andelse
): These statements allow us to execute different actions based on specific conditions.
Additional Resources:
- Bash scripting tutorials: https://www.gnu.org/software/bash/manual/bash.html, https://linuxhint.com/bash_scripting_tutorial/
- Shell script examples: https://www.shellscript.sh/
Conclusion:
By understanding the basics of looping and conditional statements in shell scripting, you can easily automate tasks like identifying even and odd numbers within a range. This script demonstrates a fundamental application of these concepts, which can be further expanded to tackle more complex problems.