I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working. Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i ) {
isOdd(i);
}
System.out.println(i);
}
CodePudding user response:
Your attempt #1 is closer to your goal ;)
- you are right that you can use
while
andfor
(and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now) - your
println
(orprint
) should be within the loop because you want to print more than just one number. - in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if
inside your loop where you check the result of isOdd(number)
and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100
) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number 2;
), your program will only need half the time - and you could even skip the isOdd
check ;-)
CodePudding user response:
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for
-loops are just syntactic sugar for special while
-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for
-loop.
for
-loop
for (int i = 1; i < 100; i )
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i
as int
in the for
-loop initializer.
Now, we may translate this to an equivalent while
-loop:
while
-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i ;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if
inside the loop body); the first even number (2
) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd
here. You're unconditionally printing i
after the loop has terminated, which will always be 100
.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i = 2)
System.out.println(i);