Sunday, March 11, 2012

Shell Programs Sum of n numbers



Ex. No.: 2(b)(i)
Shell Programs
Sum of n numbers


AIM:

            To write a shell script to find the sum of n numbers.

ALGORITHM:

            Step 1: Start the program
           
            Step 2: Enter the value of n

            Step 3: Declare the variables of i and sum and both are initialized to zero.

            Step 4: Perform the addition of n numbers using while loop

            Step 5: Print the sum.

            Step 6 : Stop the program

SCRIPT:

while [ condition ]
           do
                 command1
                 command2
                 command3
                 ..
                 ....
            done
 
            echo "Sum of n natural numbers \n”
echo "Enter the value of n "
read n
i = 0
sum = 0
while[$i –lt $n]
do
sum=’expr $sum + expr $i’
i = ‘expr $i + 1’
done
echo "Sum of n natural numbers are : $sum”

OUTPUT:

            [csestaff@localhost csestaff]$ sh sum.sh

Sum of n natural numbers

Enter the value of n : 3

Sum of n natural numbers are : 6

RESULT:
           
Thus, the shell script to find the sum of n natural numbers is entered and its output was verified.

No comments:

Post a Comment