Sum of even numbers from 0 to 100 script

  1. The problem statement, all variables and given/known data:

Write a shell script that finds and display the sum of even positive integers from 0 to 100. Use the while control structure. Show your script and a sample run.

  1. Relevant commands, code, scripts, algorithms:

Must us a while loop

  1. The attempts at a solution (include all code and scripts):

This is one attempt:

for i in {0..100}
do
        (( b = $i % 2 ))
        if [ $b -ne 0 ]
        then
        echo $i
fi
done

Another attempt, just trying to get somewhere and have it print something, but with this one I was getting a syntax error..

sum=0
while (( i=0; i<=100; i++ ));do
        if (( $i % 2 )); then
        echo $i is odd
else
        echo %i is even
fi
done

Portland Community College, Portland, OR, United States, Shawli Sengupta, CS-140U-0-14858 - Intro to UNIX/Linux
I cannot add the URL to the course because I do not have enough post on this forum.

Hi Nastybutler,
What does this line mean?

echo %i is even

--- Post updated at 11:11 ---

Missing space in this line after ;

while (( i=0; i<=100; i++ ));do

correct string

for ((i=0; i<=100; i++)); do

--- Post updated at 11:21 ---

You just make out your mistakes, do not copy mindlessly please

for i in {0..100}; do
        b=$(( $i % 2 ))
        if [ $b -ne 0 ]; then
                echo $i
        fi
done

Did you read the answers to your other thread attentively? They mentioned the "step" parameter of the for command - you might try to adapt it to your problem?
And, you might want to read the man page of your shell to learn about the correct syntax of the (mandatory to your problem) while statement - as you used it, the shell will issue a "syntax error".

What shell are you using for your class assignment?

What do your class notes, your text book, or the manual page for your shell say is the proper format for a while loop? Since your assignment says you have to use a while loop, that would seem to be a good place to start (especially since neither of your coding attempts contains a while loop that isn't getting a syntax error).

Note that the syntax for a while loop is not the same as the syntax for a for loop. And, the script that you are writing does not need two loops. If you need to use a while loop, you do not need a for loop to get the job you are trying to do done.

As a hint, I would say that if you're using a while loop to solve this problem, anything using {1..100} is probably not going to help. Using that construct does not fit with the syntax of a while loop. And, after reading your other thread, I would comment that when you said you didn't know how to add numbers that weren't supplied as input from a user, you were wrong. The statement in your previous thread:

        sum=$((sum + $n))

did exactly that. Neither sum nor n were provided by a user, but you have a statement that is adding two numbers together when neither of those numbers were typed in by a user. This statement, or one very similar to it, is likely to be needed in your script. It doesn't contain any syntax errors and it does add two numbers together and store the updated results correctly.

2 Likes

Hi Nastybutler...

Your OP suggests you 'must us[e] a while loop', therefore a for loop is not required at this point.
This is pseudocode, see if you can adapt it.

shebang needed to call your shell required

assign_a_COUNTer_to_zero
assign_my_SUM_a_starting_point_of_zero

while test[ing] against the 100 limit
do
    do your arithmetic here which uses both SUM and COUNT
    optional, print each line if you want to here to see how it is doing
    increase your COUNTer by your needed amount
done
print your final value here and should equal the last line of you optional listing

EDIT:
And thoroughly read Don's post...

Instead of incrementing the counter by 1 in the loop and then testing if it even, you could also increment the counter by 2 at every iteration. That way you would not need to test if it is even if the initial value of the counter is even.

We are using this in the bash shell. Sorry I'm very new with this so I don't have the syntax down 100%.

--- Post updated at 07:08 AM ---

After everyones feedback this is what I have so far. Please bare in mind again, I'm still learning and I know it's not perfect.

#!/bin/bash

counter=0
sum=0

while [[ $counter -le 100 ]]
do
        echo -n "$counter"
if ! [ $((counter % 2)) -eq 0 ]
then
        echo "$sum"
        sum=((sum + $counter))

fi
done

I am getting an error message that reads:

./count4.sh: line 14: syntax error near unexpected token `fi'
./count4.sh: line 14: `fi'

Hi Nastybutler...

Take a look at my pseudocode, post #5 again.
Your code; there are numerous minor errors and to go through them all before you have solved your project would mean I would be writing it.
Let's get your logic sorted first. You will see from my CODE section how different you logic is from mine.

These lines are fine:
(Just a note, there is no need for the double brackets [[ ]] for this example, single brackets [ ] would suffice. It will still work with double brackets however.)

#!/bin/bash

counter=0
sum=0

while [[ $counter -le 100 ]]
do
        Important line. "do your arithmetic here which uses both SUM and COUNT"
        Unimportant OPTIONAL print. This can be omitted.
        Important line. "increase your COUNTer by your NEEDED amount"
done
IMPORTANT "print your final value here and should equal the last line of you optional listing"
 

Again read Don's post #4 thoroughly...

Have another go, and if you increase your "counter" by a certain even number then you will see it all fall into place.
And finally, please use CODE tags, the "</>" icon on the tool bar.

Hi wisecracker,
Please don't impose your method of performing this task on Nastybutler. Let Nastybutler choose whatever increment he wants. Either of the obvious choices can yield perfectly fine results for this task and as soon as the syntax error is resolved, the logic errors are likely to reveal themselves very quickly. Infinite loops tend to become obvious quickly when there is an echo inside that loop.

As RudiC said in Nastybutler's other thread, if the goal here was to write efficient code, there would be no requirement for a while loop. It appears that the goal of this assignment is to learn how to correctly write a while loop. Whether or not that while loop contains an if statement isn't the point.

With the error that Nastybutler is currently seeing, there are three likely things that could be causing the problem:

  1. A syntax error in the if statement.
  2. A syntax error in the statement before the fi keyword that wasn't fully diagnosed until the fi was seen.
  3. Or, something like a carriage-return in a DOS line terminating <carriage-return><newline> character pair when a single-character <newline> UNIX line terminator was expected on one of the two lines before the fi .

Like you, I'm guessing that the problem is point #2 above, especially since the shell I use complains about an unexpected "(" two lines before the spot that the shell Nastybutler is using complains about something "near the unexpected token `fi'". But, if adding the missing character to line 12 doesn't solve the problem, #3 above becomes a real possibility.

1 Like