Issue
hey everyone I am trying to write a script in bash that will take a user-defined number and run its multiples up then check which of those multiples are even and print those only in a user-defined range. and the script seems to be working when an even number is selected as the value but when an odd number is selected it only prints out half of the numbers you wish to see. I think I know why it happens it is to do with my while statement with the $mult -le $range but I am not sure what to do to fix this or how to get it to show the full range for both even and odd based numbers. Any help is appreciated thanks.
code
#!/bin/sh
echo "Please input a value"
read -r val
echo "Please input how many multiples of this number whose term is even you wis>
read -r range
mult=1
while [ $mult -le $range ]
do
term=$(($val*$mult))
if [[ $(($term % 2)) -eq 0 ]]
then echo "$term"
fi
((mult++))
done
echo "For the multiples of $val these are the $range who's terms were even"
output even based number
$ ./test3.sh
Please input a value
8
Please input how many multiples of this number whose term is even you wish to see
4
8
16
24
32
For the multiples of 8 these are the 4 whose terms were even
output odd based number
$ ./test3.sh
Please input a value
5
Please input how many multiples of this number whose term is even you wish to see
10
10
20
30
40
50
For the multiples of 5 these are the 10 whose terms were even
Solution
Your current while
condition assumes that the number of even multiples of the number val
less than or equal to val * range
is at least range
. In fact, for even numbers, there are precisely range
even multiples which are less than or equal to val * range
. This is not the case for odd numbers - as you've encountered.
You'll need to introduce a new variable to solve this problem - one that keeps track of the number of even multiples you have encountered thus far. Once you reach the desired number, the loop should terminate.
So, you could set a counter initially
count=0
and check this in your while loop condition
while [ $count -lt $range ]
You would increment count
each time you enter the body of the if
- i.e. whenever you encounter an even multiple.
This should give you the desired behavior.
Answered By - costaparas