Shell program to find sum of n numbers

Let's write a shell program to find sum of n numbers.




Algorithm

1. Get N (Total Numbers).

2. Get N numbers using loop.

3. Calculate the sum.

4. Print the result.




Sum of n numbers using while loop - Shell Script

#shell script to find sum of n numbers
  
echo "Enter Size(N)"
read N

i=1
sum=0

echo "Enter Numbers"
while [ $i -le $N ]
do
  read num           #get number
  sum=$((sum + num)) #sum+=num
  i=$((i + 1))
done

echo $sum



Output

Enter Size(N)

5

Enter Numbers

1

2

3

4

5

15


Enter Size(N)

3

Enter Numbers

10

20

30

60




Sum of n numbers using for loop- Shell Script

#shell script to find sum of n numbers using for loop
  
echo "Enter Size(N)"
read N

sum=0

echo "Enter Numbers"
for((i=1;i<=N;i++))
do
  read num           #get number
  sum=$((sum + num)) #sum+=num
done

echo $sum



Output

Enter Size(N)

5

Enter Numbers

1

2

3

4

5

15


Enter Size(N)

3

Enter Numbers

10

20

30

60


Topics You Might Like