Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Pattern of 1 01 101 0101.........n

0 votes
Write a program to print following pattern (8)
        1

        0 1

        1 0 1

        0 1 0 ….. n
asked by Devanshi (318 points)
retagged by Ranjith

1 Answer

0 votes
 
Best answer

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.

image

Program

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();
        }
    }
}

Sample Output

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 

 

answered by Ranjith (2,683 points)
selected by Devanshi
...