In: Computer Science
2 Write a Java program called Pattern that prints an 8-by-8 checker box pattern using an if loop.
Using Applet:
package demos;
import java.awt.*;
import java.applet.*;
// Extends Applet Class
public class Pattern1 extends Applet {
static int N = 10;
// Use paint() method
public void paint(Graphics g)
{
int x, y;
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
// Set x coordinates of rectangle
// by 20 times
x = row * 20;
// Set y coordinates of rectangle
// by 20 times
y = col * 20;
// Check whether row and column
// are in even position
// If it is true set Black color
if ((row % 2 == 0) == (col % 2 == 0))
g.setColor(Color.BLACK);
else
g.setColor(Color.WHITE);
// Create a rectangle with
// length and breadth of 20
g.fillRect(x, y, 20, 20);
}
}
}
}
Using console:
public class Pattern2 {
public static void main(String args[]) {
int i,j;
for(i=0;i<8;i++) {
for(j=0;j<8;j++) {
if((i+j)%2==0)
System.out.print('*');
else
System.out.print(' ');
}
System.out.println();
}
}
}
Hope this helps.