I'm trying to write a program that outputs the following while using a do-while or while loop:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
16 is even
17 is odd
18 is even
19 is odd
20 is even
My code currently looks like this:
public class Objective7Lab3 {
public static void main(String[] args) {
int counter = 1;
counter = counter 1;
do {
if (counter % 2 == 0) {
System.out.println(counter " is even");}
else if (counter % 2 != 0)
System.out.println(counter " is odd");
} while (counter <= 20);
}
}
All I'm getting in return is "2 is even" repeating. Where am I going wrong?
CodePudding user response:
Your counter is outside the loop, so it will never be incremented, what you can do is passing the counter to inside your do/while loop:
public class MyClass {
public static void main(String args[]) {
int counter = 1;
do {
if (counter % 2 == 0) {
System.out.println(counter " is even");
} else if (counter % 2 != 0) {
System.out.println(counter " is odd");
}
counter ;
} while (counter <= 20);
}
}
CodePudding user response:
You were real close. All you need to do is:
remove counter = counter 1;
and
prepend
to your counter in the while loop. -> while ( counter <= 20);
Note: you didn't need to check for odd parity since if the number isn't even, it must be odd.
And for your edification, here is a different way.
- using a for loop, iterate from 1 to 20
- print the value followed by even or odd as appropriate.
The above uses the ternary operator (?:
) which says for a ? b : c
, if a
is true, evaluate and return b
, else c
.
for (int i = 1; i <= 20; i ) {
System.out.printf("%d is %s%n",
i, i % 2 == 0 ? "even" : "odd");
}
prints
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
16 is even
17 is odd
18 is even
19 is odd
20 is even
See also System.out.printf