Hybrid Grid of Numbers and Stars
This program prints a grid alternating numbers and stars.
Problem Statement
Write a Java program that prints a 6x6 grid alternating numbers and stars.
Source Code
| 1 | public class HybridGridNumbersStars { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 6, num=1; |
| 4 | for(int i=0; i<n; i++) { |
| 5 | for(int j=0; j<n; j++) { |
| 6 | if((i+j)%2==0) System.out.print(num++ + " "); |
| 7 | else System.out.print("* "); |
| 8 | } |
| 9 | System.out.println(); |
| 10 | } |
| 11 | } |
| 12 | } |
Program Output
1 * 2 * 3 * * 4 * 5 * 6 7 * 8 * 9 * * 10 * 11 * 12 13 * 14 * 15 * * 16 * 17 * 18
Explanation
The checkerboard condition (i+j)%2==0 decides whether a cell prints the next sequential number or a star, so numbers and stars alternate in a checkerboard pattern across the grid.