7.3k views
2 votes
Write a short java method that takes an integer n and returns the sum of all the odd positive integers less than or equal to n.

1 Answer

5 votes
public int add2n( int n )
{
int total;
if( n % 2 == 0 )
total = n--;

while( n > 0 )
{
total += n;
n -= 2;
}
return( total );
}

User Royal
by
6.8k points