I am currently trying to figure out how to code this simple while loop based on the instructions.
The instructions:
Given some positive number n, write a while loop that will print the odd numbers from -n to n (inclusive), one number per line. The given number may be even or odd.
My code so far:
int n = 3;
while (n >= -36)
{
System.out.println(n);
n--;
}
What problems are you having?
If n
is 3, then -n
would be -3, not -36.
Alrighty, the loop is a reasonable start.
Three comments:
“print the odd numbers” Where is your logic for checking if a number is odd before you print?
"from -n
to n
", you seem to be going from n
to -n
(decreasing instead of increasing)
Why not use n
in the loop bounds? Or a copy of it?
I don’t know how to create the logic for checking if a number is odd.
How do you check if a number is even or odd on paper?
I guess I would do (n % 2 == 1).
Right. On paper you would see if the number has a remainder when divided by 2. The code you gave n % 2 == 1
checks that same thing.
So would I write
int n = 3;
while (n % 2 == 1 && n >= -36)
{
System.out.println(n);
n++;
}
I suspect that if you try to run this code, it will not do what you want.
Here is how I would describe the instructions
Do you have experience with if
statements?
Would I do something like
if (n % 2 == 1)
{
System.out.println(n);
}
Sure, that would check if a value is odd. But where did the looping go?
I don’t know where to put the looping. Would I put it inside the if statement or outside?
Well,
if (condition1) {
while (condition2) {
}
}
will run a loop if a condition is true.
while (condition2) {
if (condition1) {
}
}
will execute the body of a loop based upon some criteria.
Which is closer to “print only odd numbers in a range”?
Could I do:
int n = 3;
if (n % 2 == 1)
{
while (n >= -36)
{
System.out.println(n);
n++;
}
}
What happens when you run the code? Do you get the output you want?
No, it’s giving me unending numbers. How do I f ix it?
csquare121:
while (n >= -36)
Is this condition ever met?
I think it does. It’s giving me a lot of numbers.
I meant to say, is this condition ever not met? Do you do anything to stop your code from meeting this condition so the loop will stop?
No, I don’t. Would I need a loop control variable?