Shell script to find largest of n numbers

Let's write a shell script to find largest of n numbers.




Algorithm

1. Get N

2. Read N numbers using loop

3. Set first number as max.

4. From number 2 onwards update the max value if the number > max.

5. Display the result




Largest of n numbers - Shell Script

#shell script for largest of n numbers
  
echo "Enter Size(N)"
read N

i=1
max=0

echo "Enter Numbers"
while [ $i -le $N ]
do
  read num
  if [ $i -eq 1 ]  #set first number as max
  then
      max=$num
  else             #from number 2 update max if the num > max.
      if [ $num -gt $max ]
      then
        max=$num
      fi
  fi
  i=$((i + 1))  #increment i by 1
done

echo $max



Output

Enter Size(N)

5

Enter Numbers

123

4

56

78

34

123

Enter Size(N)

5

Enter Numbers

1

2

3

4

5

5


Topics You Might Like