Sum of N Numbers in Shell Script
In this shell script, we will learn to write:
-
sum of n numbers in shell script
SUM OF N NUMBERS ALGORITHM:
Given below is algorithm for shell script to find sum of n numbers:
STEP 1: START THE PROGRAM
STEP 2: TAKE INPUT A NUMBER ( >=1). AND STORE IT IN A VARIABLE ( SUPPOSE ‘DIGIT’)
STEP 3: DECLARE A VARIABLE AND INITIALIZE IT WITH 1 ( suppose ‘temp’)
STEP 4: DECLARE ANOTHER VARIABLE (LET’S SAY ‘TOTAL’ WHICH SHOULD BE INITIALIZED WITH ZERO ) WHICH WILL HELP US TO ADD UP TO DIGIT
STEP 5: PERFORM WHILE LOOP FROM 1 TO ‘DIGIT’
STEP 6: WRITE THIS LINE INSIDE THE WHILE LOOP -> total=`expr $ total + $temp`
STEP 7: WHILE PERFORMING LOOP, EVERYTIME INCREASE ‘DIGIT=$DIGIT+1’
STEP 8: AT LAST PRINT ‘TOTAL’
STEP 9: STOP THE PROGRAM
SUM OF N NUMBERS IN SHELL SCRIPT
To find sum of n natural numbers in shell script is shown below:
clear
echo "---------SUM OF N NUMBERS IN SHELL SCRIPT-----------"
echo -n "Enter nth number's value:"
read digit
t=1
total=0
while test $t -le $digit
do
total=`expr $total + $t`
t=`expr $t + 1`
done
echo "SUM OF $DIGIT: $total "
OUTPUT
Enter nth number's value: 5
SUM OF : 15
CODE IMAGE:
Write a shell script to calculate sum of n numbers in shell script:
OUTPUT IMAGE:
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Feb 07,2021