0

Java Pattern

/* Program to print the following pattern 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 */ public class numpat { public static void main(String[] args) { for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) { //for every odd column print 1 if(j%2==1) { System.out.print(" 1 "); } else { System.out.print(" 0 "); } } System.out.println(); } } } What is wrong in the program? Please correct the code and post it in the comment.

25th Dec 2018, 7:12 PM
AMOL SAMADHAN BHALERAO
AMOL SAMADHAN BHALERAO - avatar
3 Answers
+ 3
Some changes are made may be helpful class NumPattern { public static void main(String s[]) { int i, j; int count = 1; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) { System.out.format("%d", count++ % 2); if (j == i && i != 5) System.out.println(""); } if (i % 2 == 0) count = 1; else count = 0; } } }
25th Dec 2018, 7:14 PM
MsJ
MsJ - avatar
+ 1
The error is in the inner loop .... It will be: for(int j=i;j>=1;j--)
6th Jul 2019, 12:31 PM
mn121
mn121 - avatar
+ 1
To speed up your program processing, you can replace if-else part with: System.out.print(j%2);
6th Jul 2019, 12:32 PM
mn121
mn121 - avatar