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

Edited 6 Years Ago by iSax: n/a

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

Edited 6 Years Ago by JamesCherrill: n/a

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

Edited 6 Years Ago by tong1: n/a

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?

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;)

Edited 6 Years Ago by Xufyan: n/a

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.

Edited 6 Years Ago by tong1: n/a

This article has been dead for over six months. Start a new discussion instead.