Pattern of 1 01 101 0101.........n
A nested loop will be used to print the pattern. Given input n, the pattern consists of n lines. The outer loop with loop variable i ranging from 1 to n will be used to keep track of the line number. Line i contains i. The inner loop has its loop counter j ranging from 1 to i. Now, we need to find a relationship between the values i, j and the digit (0 or 1) that is printed. If (i+j) is an even number, 1 is printed, else 0 is printed. This relation is shown below.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scanner.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if ((i + j) % 2 == 0) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println();
}
}
}
Output Result:
Enter n: 7
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
No comments:
Post a Comment