![I am trying to find all the even numbers in the array and add the variable A to them then print it out but I am having problems doing so](https://linux22.com/image/183714/I%20am%20trying%20to%20find%20all%20the%20even%20numbers%20in%20the%20array%20and%20add%20the%20variable%20A%20to%20them%20then%20print%20it%20out%20but%20I%20am%20having%20problems%20doing%20so.png)
#!/bin/bash
declare -i A=2
ADD()
{
declare -a Arr
count=1
MAXCOUNT=4
#declare -a arr
while [ "$count" -le "$MAXCOUNT" ]; do
Arr[$count]=$(( RANDOM % 10 + 1 ))
(( count++ )) || true
done
for i in "${Arr[@]}"; do
if [ $((Arr[i]%2)) -eq 0 ]; then
A+=$(Arr[i])
fi
done
echo "$A"
}
ADD
./math1804262.sh: line 35: Arr[*]: command not found
./math1804262.sh: line 35: Arr[*]: command not found
no
./math1804262.sh: line 35: Arr[*]: command not found
答案1
Code 1 :
#!/bin/bash
declare -i A=2
ADD()
{
start_value=$1
end_value=$2
dynamic_array=()
for (( i=$start_value ; i<=$end_value ; i++ ))
{
rem=$(( $i % 2 ))
if [ $rem -eq 0 ]
then
#echo "Number : $i print's even number"
dynamic_array+=("$i")
else
# echo "Not a even number : $i"
fi
}
# Printing all even numbers
echo ${dynamic_array[@]}
}
ADD 1 7
Output 1: 2 4 6
The code 2 will print the A alternatively , just little bit change made in dynamic array storing
Code 2 :
#!/bin/bash
declare -i A=2
ADD()
{
start_value=$1
end_value=$2
dynamic_array=()
for (( i=$start_value ; i<=$end_value ; i++ ))
{
rem=$(( $i % 2 ))
if [ $rem -eq 0 ]
then
#echo "Number : $i print's even number"
dynamic_array+=("$i A")
else
echo "Not a even number : $i"
fi
}
# Printing all even numbers
echo ${dynamic_array[@]}
}
ADD 1 7
Output 2 :
2 A 4 A 6 A