I am a newbie in Java programming. There're one question requesting us to construct an algorithm to sum up all the odd numbers from 0 to 100.

Is this consider an algorithm?

• Start
• set sum to 0
• set number counter to 1
• while number counter <= 100
• add 2 to the number counter
• sum = sum + number counter
• Print “sum”
• End

Recommended Answers

All 9 Replies

I say "yes". Would be an even better algorithm if you replaced "100" by "n" thus making it general

Note: order of execution in loop body has been altered.

Use psuedo code to express the algorithm:

• set sum to 0
• set number_counter to 1

• while number counter <= 100 do the following loop:
sum = sum + number_counter
add 2 to the number_counter

• Print sum
• End

Note: order of execution in loop body has been altered.

why?

Thx James =]
But if I change to n, will it not suitable for the title?

And tong, whats mean by order of execution in loop body has been altered?

If I were your prof I'd prefer to see the general case "n", but it may be safer for you to do exactly what he asks.

ok, thanks alot James! =]

set the value to 1 and increment the value with two in a loop, you'll get the desired result,

for(int i=1; i<100; i=i+2;)

I mean that in the loop body, one should do the "sum = sum + number_counter;" first.
Otherwise the odd number 1 would be missing, and also the number 101 would be incorrectly included in the sum. In iSax's Algorithm, to do the updating on number_counter first, thus the odd number 1 was missing, and the odd number 101 is also incorrectly included in the sum.

Yes, you're right. Well spotted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.