Reputation: 311
I don’t really understand much about arrays, but I need to know how to find and print the largest and smallest values of an array. The array is predefined by a read command, and the user will be prompted to enter n amount of integers.
How would I assign the read input to an array and find and display the largest and smallest values of the array?
Is there a way to test the array elements to see if they are all integers?
#!/bin/bash
read -a integers
biggest=${integers[0]}
smallest=${integers[0]}
for i in ${integers[@]}
do
if [[ $i -gt $biggest ]]
then
biggest="$i"
fi
if [[ $i -lt $smallest ]]
then
smallest="$i"
fi
done
echo "The largest number is $biggest"
echo "The smallest number is $smallest"
Upvotes: 6
Views: 49189
Reputation: 10314
You could sort the array, then the first and last elements will be your min and max values:
sorted=($(IFS=$'\n'; sort -n <<< "${integers[*]}"))
echo "The largest number is ${sorted[-1]}"
echo "The smallest number is ${sorted[0]}"
To test if an array is all integers, you could use the following bash function:
is_int_array() {
for e in "$@"; do
[[ "$e" =~ ^-?[0-9]+$ ]] || return 1
done
return 0
}
To use the function:
is_int_array "${integers[@]}" && echo 'is int array' || echo 'not all integers'
is int array
is_int_array 'a' 1 2 3 && echo 'is int array' || echo 'not all integers'
not all integers
is_int_array 1 2 3 -4 && echo 'is int array' || echo 'not all integers'
is int array
Upvotes: 0
Reputation: 133
Here is the code to find maximum and minimum values from an array of n integers.
#author@Pratham
declare -a arr
echo "How many numbers you want to enter?"
read n
echo "Enter the Array Elements"
for(( i=0 ; i<$n ; i++))
do
read array_elements
arr[$i]="$array_elements"
done
echo "The Array Elements are :"
echo -e "${arr[@]}"
max=${arr[0]}
min=${arr[0]}
for i in "${arr[@]}"
do
if [[ $i -gt $max ]];
then
max=$i
fi
if [[ $i -lt $min ]];
then
min=$i
fi
done
echo "Maximum element in the array is: $max"
echo "Manimum element in the array is: $min"
Upvotes: 0
Reputation: 185025
Try this if you need to compare (signed or not) INTegers :
#!/bin/bash
arr=( -10 1 2 3 4 5 )
min=0 max=0
for i in ${arr[@]}; do
(( $i > max || max == 0)) && max=$i
(( $i < min || min == 0)) && min=$i
done
echo "min=$min
max=$max"
OUTPUT
min=-10
max=5
EXPLANATIONS
arr=( )
is the declaration of the array((...))
is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression[[
is a bash keyword similar to (but more powerful than) the [
command. See http://mywiki.wooledge.org/BashFAQ/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals Unless you're writing for POSIX sh, we recommend [[
foo || bar
runs bar when foo fails: [[ -d $foo ]] || { echo 'ohNoes!' >&2; exit 1; }
cmd1 && cmd2
: cmd1 is executed, and then if its exit status was 0 (true), cmd2 is executed. See http://mywiki.wooledge.org/BashGuide/TestsAndConditionalsUpvotes: 6
Reputation: 46823
A funny way using sort:
if you have an array of integers, you can use sort
to sort it, then select the first and last elements to have the min and max elements, as in:
{ read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n)
So if you want to prompt user for say 10 integers, check that the user entered integers and then sort them, you could do:
#!/bin/bash
n=10
array=()
while ((n));do
read -p "[$n] Give me an integer: " i
[[ $i =~ ^[+-]?[[:digit:]]+$ ]] || continue
array+=($i)
((--n))
done
# Sort the array:
{ read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n)
# print min and max elements:
echo "min=$min"
echo "max=$max"
Upvotes: 3
Reputation: 47267
The general idea is to iterate through the array once and keep track of what the max
and min
seen so far at each step.
Some comments and explanations in-line (prefixed by #
)
# This is how to declare / initialize an array:
arrayName=(1 2 3 4 5 6 7)
# Use choose first element of array as initial values for min/max;
# (Defensive programming) - this is a language-agnostic 'gotcha' when
# finding min/max ;)
max=${arrayName[0]}
min=${arrayName[0]}
# Loop through all elements in the array
for i in "${arrayName[@]}"
do
# Update max if applicable
if [[ "$i" -gt "$max" ]]; then
max="$i"
fi
# Update min if applicable
if [[ "$i" -lt "$min" ]]; then
min="$i"
fi
done
# Output results:
echo "Max is: $max"
echo "Min is: $min"
Upvotes: 10