Learn how to create a Java program to display triangle binary pattern using nested loops. In this example, the program prints alternating 1s and 0s in a triangular format. The user enters the number of rows using the Scanner class, and the pattern is generated using conditional statements.
Code Explanation (Step-by-Step)
- Create a Scanner class object to accept user input.
- Read the number of rows using the sc.nextInt() method.
- Use nested for loops to generate the triangle pattern.
- The outer loop controls the number of rows.
- The inner loop prints the pattern for each row.
- If j % 2 == 0, print 0; otherwise, print 1.
- Print a new line after completing each row.
import java.util.Scanner;
public class BinaryPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int row = sc.nextInt();
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0) {
System.out.print("0");
} else {
System.out.print("1");
}
}
System.out.println();
}
sc.close();
}
}
Output :-
enter the number of rows: 7
1
10
101
1010
10101
101010
1010101
Java 8 Program to Display a Triangle Binary Pattern
import java.util.Scanner;
import java.util.stream.IntStream;
public class BinaryPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int row = sc.nextInt();
IntStream.rangeClosed(1, row).forEach(i -> {
IntStream.rangeClosed(1, i)
.forEach(j -> System.out.print(j % 2 == 0 ? "0" : "1"));
System.out.println();
});
sc.close();
}
}
Here are some Java-related programs that will help you understand Java concepts better: