How to remove the 101 that keeps showing on the code result? I was tasked to print the odd and even numbers from 0 - 100 but when I run my code, the number 101 keeps showing both at the end of Odd and Even results.
Here's my code so far;
public class act1 {
public static void main(String[] args) {
int start = 0;
int end = 100;
System.out.println("List of EVEN numbers");
int evenNums = evenNumbers(start, end);
System.out.println(evenNums);
System.out.println("\nList of ODD numbers");
int oddNums = oddNumbers(start, end);
System.out.println(oddNums);
}
static int oddNumbers(int start, int end) {
for (start = 0; start <= 100; start ) {
if (start % 2 != 0) {
System.out.print(start " ");
}
}
return start;
}
static int evenNumbers(int start, int end) {
for (start = 0; start <= 100; start ) {
if (start % 2 == 0) {
System.out.print(start " ");
}
}
return start;
}
}
CodePudding user response:
Remove those two : System.out.println(oddNums);
, System.out.println(evenNums);
.
It's printing 101 because when you return return start;
, it will return the last index, which is the one on which the loop will break, which with this condition start <= 100
will always be 101.
So here's the function with the edit already made :
public class act1 {
public static void main(String[] args){
int start = 0;
int end = 100;
System.out.println("List of EVEN numbers");
evenNumbers(start, end);
System.out.println("\nList of ODD numbers");
oddNumbers(start, end);
}
You don't need to get the return of the two functions, you can just call those like this.
CodePudding user response:
Reconsider how a for-loop works:
for (int n=0; n<=3; n ) {
System.out.println(n);
}
- n==0, so n<=3 is true, enter the body and print out "0", n so n==1
- n==1, so n<=3 is true, enter the body and print out "1", n so n==2
- n==2, so n<=3 is true, enter the body and print out "2", n so n==3
- n==3, so n<=3 is true, enter the body and print out "3", n so n==4
- n==4, so n<=3 is false, terminate the loop
Now the value of n==4...