Sum Numbers 1-10 in Linux For Loop

In Linux, you can use a for loop and a variable to output the sum of numbers from 1 to 10. Here is an example script:

#!/bin/bash

sum=0

for ((i=1; i<=10; i++))
do
  sum=$((sum + i))
done

echo "1到10的和是:$sum"

You can save the above code as a shell script file (e.g. sum.sh) and then run it in the terminal.

bash sum.sh

This will output the sum of 1 to 10 as 55. You can modify the start and end values of the loop as needed to calculate the sum of different ranges.

bannerAds