Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Odd Even - For loop

1. ## Odd Even - For loop

I need help with this code, my desired output is supposed to be like this

Input an integer:
1
2
3
4
5
6
7
8
9
0
Even numbers are: 0 2 4 6 8
Odd numbers are: 1 3 5 7 9

But my output with this code is like this:

Input an integer: 1
Input an integer: 2
Input an integer: 3
//and so on
Even numbers are 0
Even numbers are 2
Odd numbers are 1
Odd numbers are 3
//and so on

Here's my code

```import java.io.*;
public class Prelims2{
public static void main(String[] args)throws IOException{
int a, b;
int al[] = new int[10];

for(b = 0; b < 10; b++){
System.out.print("Input an integer: ");
}
for(b = 0; b < 10; b++)
if(al[b]%2==0){
System.out.println("Odd numbers are:" +b);
}
{
for(b = 0; b < 10; b++)
if(al[b]%2!=0)
System.out.println("Even numbers are:" +b);
}
}
}```

2. ## Re: Odd Even - For loop

Move the print out requesting the user to enter an integer outside of the for loop and it will only print once instead of each time around the loop.
You'll need a way to save the even and odd numbers that you detect in the loop.
One way is to have separate arrays to hold the even and the odd numbers as you go around the loop. Then at the end of the loop you can have more loops to print the contents of one array and then the contents of the other array.
Another way is to concatenate the number onto separate Strings (even and odd) to be displayed after the data gathering loop.