2008年6月9日 星期一

Homework 6-02-2008

2. (30)

Write a complete Java program that uses a for loop to compute the sum of the even numbers and the sum of the odd numbers between 1 and 50.



public class Sum {
public static void main ( String [] args )
{
int sum_even = 0;
int sum_odd = 0;
int number = 1;

for (int i = 1; i <= 50; i++)
{
if(number % 2 == 0){
sum_even = sum_even + number;
}
if(number % 2 == 1){
sum_odd = sum_odd + number;
}
number ++;
}

System.out.println("Sum of even = " + sum_even);
System.out.println("Sum of odd = " + sum_odd);
}
}



3. (20) Rewrite the following for loop using a while expression.

int Sum=0;
for(i=0; i<=10; i++)
Sum=Sum+i;



public class SumUsingWhile {
public static void main ( String [] args )
{
int sum = 0;
int i = 0;
while (i <= 10)
{
sum = sum + i;
i++;
}
System.out.println("sum = " + sum);
}
}

沒有留言: