|
Hello all,
I'm writing a program write now and got stuck on this one code segmet:
How can you write a code segment that will displays the sum of odd integers from 1 to n?
thanks
|
|
|
public class OddSum
{
public static void main(String[] args)
{
System.out.println(getOddSum(12));
}
private static int getOddSum(int n)
{
int sum = 0;
System.out.print("[");
for(int j = 1; j <= n; j++)
{
if(j % 2 == 1)
{
System.out.print(j);
if(j < n-1)
System.out.print(", ");
sum += j;
}
}
System.out.print("]\n");
return sum;
}
}
|
|
|
|
|
|
|
|
|
|