Bash Script to Find Sum of n Numbers
Use a Bash script that reads n numbers in a loop and adds them using a variable, like
sum=0; for ((i=0; i. Examples
Input3
1
2
3
Output6
Input5
10
20
30
40
50
Output150
Input0
Output0
How to Think About It
To find the sum of n numbers, first get how many numbers you want to add. Then read each number one by one, keep adding it to a total sum. Finally, show the total sum after all numbers are added.
Algorithm
1
Get the number n from the user.2
Set a variable sum to 0.3
Repeat n times: read a number and add it to sum.4
After the loop, print the sum.Code
bash
#!/bin/bash read -p "Enter count of numbers: " n sum=0 for ((i=0; i<n; i++)) do read -p "Enter number $((i+1)): " num sum=$((sum + num)) done echo "Sum of $n numbers is: $sum"
Output
Enter count of numbers: 3
Enter number 1: 4
Enter number 2: 5
Enter number 3: 6
Sum of 3 numbers is: 15
Dry Run
Let's trace the input 3 numbers: 4, 5, 6 through the code
1
Read n
User inputs n=3
2
Initialize sum
sum=0
3
Loop iteration 1
Read num=4; sum=0+4=4
4
Loop iteration 2
Read num=5; sum=4+5=9
5
Loop iteration 3
Read num=6; sum=9+6=15
6
Print sum
Output: Sum of 3 numbers is: 15
| Iteration | Input Number | Sum After Addition |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 5 | 9 |
| 3 | 6 | 15 |
Why This Works
Step 1: Reading the count
We use read to get how many numbers the user wants to add.
Step 2: Adding numbers in a loop
The for loop runs n times, each time reading a number and adding it to sum using $((sum + num)).
Step 3: Displaying the result
After the loop, echo prints the total sum to the screen.
Alternative Approaches
Using while loop
bash
#!/bin/bash read -p "Enter count of numbers: " n sum=0 count=0 while [ $count -lt $n ] do read -p "Enter number $((count+1)): " num sum=$((sum + num)) count=$((count + 1)) done echo "Sum is: $sum"
This uses a while loop instead of for; both are equally readable but while is more flexible for unknown counts.
Sum from command line arguments
bash
#!/bin/bash sum=0 for num in "$@" do sum=$((sum + num)) done echo "Sum is: $sum"
This sums numbers passed as arguments when running the script, no interactive input needed.
Complexity: O(n) time, O(1) space
Time Complexity
The script reads and adds each of the n numbers once, so time grows linearly with n.
Space Complexity
Only a few variables are used regardless of input size, so space is constant.
Which Approach is Fastest?
All approaches run in O(n) time; using command line arguments avoids input prompts but requires all numbers upfront.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop with read | O(n) | O(1) | Interactive input with known count |
| While loop with read | O(n) | O(1) | Flexible looping with interactive input |
| Command line arguments | O(n) | O(1) | Non-interactive, batch input |
Always initialize your sum variable to 0 before adding numbers to avoid errors.
Forgetting to initialize sum to 0 causes incorrect results or errors.