Write a method header on line two with the following specs:
Returns: an integer Name: sumEvenToX Parameters: an integer called "x" Purpose: calculate the sum of the EVEN integers from 1 to x (including x) |
Examples:
- sumEvenToX(5) ==> 6 sumEvenToX(8) ==> 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class Main {
public static int sumEvenToX(int x) {
int sum=0;
for(int i=1;i<=x;i++) {
int temp=(i%2==0?i:0);
sum+=temp;
}
return sum;
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(sumEvenToX(5)); //6
System.out.println(sumEvenToX(8)); //20
}
}
|
반응형