Search Java Programs

Monday, January 11, 2010

Odd and Even Numbers Logics in Java Programs

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/


package javaapplication2;

import java.io.*;

public class TrianglePrintingio {
public static void main(String a[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Number : ");
int n = Integer.parseInt(br.readLine());
int odd[] = new int[2];
int eve[] = new int[2];
int o = -1, e = -1;
StringBuffer sb = new StringBuffer();
for(int i=1; i<=n; i++) {
if(i%2==0) {
e++;
eve[e] = i;
}
if(e==1) {
sb.append(eve[0] + " " + eve[1] + ", ");
e = -1;
}
if(i%2!=0) {
o++;
odd[o] = i;
}
if(o==1) {
sb.append(odd[0] + " " + odd[1] + ", ");
o = -1;
}

}
System.out.println(sb.delete(sb.length()-2, sb.length()-1).toString());
}

}
Output

Enter Number : 20
1 3, 2 4, 5 7, 6 8, 9 11, 10 12, 13 15, 14 16, 17 19, 18 20

No comments:

Post a Comment

Post a Comment

Website Design by Mayuri Multimedia