-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumOddRange.java
More file actions
65 lines (44 loc) · 2.05 KB
/
SumOddRange.java
File metadata and controls
65 lines (44 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*********************************************************************************************************************
Sum Odd
=======
Write a method called isOdd with an int parameter and call it number. The method needs to return a boolean.
Check that number is > 0, if it is not return false.
If number is odd return true, otherwise return false.
Write a second method called sumOdd that has 2 int parameters start and end, which represent a range of numbers.
The method should use a for loop to sum all odd numbers in that range including the end and return the sum.
It should call the method isOdd to check if each number is odd.
The parameter end needs to be greater than or equal to start and both start and end parameters have to be greater than 0.
If those conditions are not satisfied return -1 from the method to indicate invalid input.
Example input/output:
sumOdd(1, 100); → should return 2500
sumOdd(-1, 100); → should return -1
sumOdd(100, 100); → should return 0
sumOdd(13, 13); → should return 13 (This set contains one number, 13, and it is odd)
sumOdd(100, -100); → should return -1
sumOdd(100, 1000); → should return 247500
TIP: use the remainder operator to check if the number is odd
NOTE: Both methods needs to be defined as public static like we have been doing so far in the course.
NOTE: Do not add a main method to solution code.
**********************************************************************************************************************/
public class SumOddRange {
public static boolean isOdd(int number){
if (number<=0)
return false;
else if (number%2!=0)
return true;
else
return false;
}
public static int sumOdd(int start ,int end){
int sum=0;
if (end<start || start<0 || end<0)
return -1;
for (int i=start;i<=end;i++){
if (isOdd(i))
{
sum+=i;
}
}
return sum;
}
}