6

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"
2
  • what are the attempts that you have made yet? Commented Nov 29, 2012 at 21:04
  • This question can be answered looking at the documentation, see tldp.org/LDP/abs/html/arrays.html . Or do you have more specific problem? Some sample code would not hurt. Commented Nov 29, 2012 at 21:09

5 Answers 5

10

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"
Sign up to request clarification or add additional context in comments.

5 Comments

how would i do this with an array thats elements are declared by the user?
@user1864478 you would need to provide a lot of missing details regarding that (and other aspects of your problem) in an edit to your question. Right I'm only providing a very generalize example of how to use arrays in bash since there's a lack of context.
@user1864478 Change for i in ${integers[0]} to for i in ${integers[@]}; big difference between 0 and @ =)
would there be a way to test if the elements of the array are all integers?
@BobbyT28 This answer includes a bash function that solves the test for all integers piece.
6

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

2 Comments

what happens when arr=(-1 -2 -3 -4)? ;)
Try arr=(-1 -2 -3 -4) with your edited version for integers: it gives min=-4 max=0. There's a small gotcha with your min/max initialization.
3

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"

4 Comments

Nothing relevant to a beginner... (IMHO)
@sputnick yeah but at least it works, unlike your solution ;-)
I think you have not tested it to say this... Works well.
0

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"

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.