Write an algorithm find out the sum of first n odd numbers?

1 answer

Answer

1127291

2026-04-17 16:25

+ Follow

Algorithm: sum_even

Input: an integer, n, such that n>0

Output: the sum of all even integers within the open range (1:n)

sum := 0

val := 2

while (val < n) do

{

sum := sum + val

val := val + 2

}

return sum

Note that you explicitly specified between 1 and n, which literally means both 1 and n should be excluded from the sum. 1 would be excluded anyway since it is not an even number, however if we wish to include n, then use the following algorithm instead:

Algorithm: sum_even

Input: an integer, n, such that n>0

Output: the sum of all even integers within the half-open range (1:n]

sum := 0

val := 2

while (val <= n) do

{

sum := sum + val

val := val + 2

}

return sum

ReportLike(0ShareFavorite

Related Questions

Copyright © 2026 eLLeNow.com All Rights Reserved.