14 June 2012

Shell Script to find Greatest and Smallest number

3 comments

Q. How do I write shell script to find Smallest and Greatest number in an array


Ans:

#!/bin/bash
echo "enter size of an array"
read n
#taking input from user
for((i=0;i<n;i++))
do
echo " enter $((i+1)) number"
read nos[$i]
done
#printing the entered number
echo "number entered are"
for((i=0;i<n;i++))
do
echo ${nos[$i]}
done
#main loop
small=${nos[0]}
greatest=${nos[0]}
for((i=0;i<n;i++))
do
#logic for smallest number
if [ ${nos[$i]} -lt $small ]; then
small=${nos[$i]}
#logic for greatest number
elif [ ${nos[$i]} -gt $greatest ]; then
greatest=${nos[$i]}
fi
done
#printing smallest and greatest number
echo "smallest number in an array is $small"
echo "greatest number in an array is $greatest"



Output


smallest and greatest number in an array

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

3 comments:

  1. Thanks shaikh ,its a really nice article. I have a doubt since I am newbie to shell scripting, I want to know how I can print the array elements with pair.
    Basically I am looking something (x,y) format. Let's say we have an array such as array1=(5 4 6 2 9 3)
    Find the greatest number from the array and print the biggest array with other elements of the array.
    Output:
    (9,2)
    (9,3)
    (9,4)
    (9,5)
    (9,6)

    ReplyDelete
    Replies
    1. Editing the output of the array:
      (9,2)
      (9,3)
      (9,4)
      (9,5)
      (9,6)
      (6,2)
      (6,3)
      (6,4)
      (6,5)
      (5,2)
      (5,3)
      (5,4)
      (4,2)
      (4,3)
      (3,2)

      Delete
  2. An old article, but still pertinent. This is valid only for positive numbers, if you have negative ones, both the greatest & smallest numbers will be negative.

    ReplyDelete