# Odd Even - For loop

• October 11th, 2010, 02:15 AM
clevel211
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 :rolleyes:

Code Java:

```import java.io.*; public class Prelims2{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int a, b; int al[] = new int[10];   for(b = 0; b < 10; b++){ System.out.print("Input an integer: "); al[b]=Integer.parseInt(br.readLine()); } 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); } } }```
• October 11th, 2010, 08:45 AM
Norm
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.
• October 11th, 2010, 09:09 PM
clevel211
Re: Odd Even - For loop