Sayyed Mustafa
Sayyed Mustafa

Reputation: 1

how to find sum of even no till 100 in linux

what should be condition for while before adding while loops it prints even no upto 100 but I need to print sum of even numbers

#!/bin/bash
 sum=0
   for((n=2;n<=100;n=n+2))
   do
      echo $n
      while [[$n  0]]   # what should be condition for while loop
      do
         sum= `expr sum + $n`
      done
    echo "sum is $sum "
   done

Upvotes: 0

Views: 568

Answers (3)

Barmar
Barmar

Reputation: 781814

You shouldn't have the while loop at all. You're already iterating with the for loop.

#!/bin/bash
sum=0
for((n=2;n<=100;n=n+2))
do
    echo $n
    ((sum+=n))
done
echo "sum is $sum "

Upvotes: 0

k=0;
 for i in {1..100}; do 
    if [[ $(( i % 2 )) == 0 ]]; then
       let k=k+i
           fi ; done
echo $k

Prints

2550

or this:

k=0; for i in {1..100}; do 
    if (( i % 2 == 0 )); then 
         (( k=k+i ))  ; fi ; done ; echo $k

Upvotes: 0

Kent
Kent

Reputation: 195209

Does this count ^_* :

kent$ seq -s + 2 2 100|bc
2550

Upvotes: 3

Related Questions