for my homework I need to make a pattern using for nested loops. It needs to look like this: pattern for 5 rows and 7 columns
However, when I was writing my code I could not figure out what to do make columns, if an odd number, to appear. I figured I needed to add another If/else statement. Here is my code:
public class PatternMaker {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Declaration
int numrows = 5;
int numcols = 7;
String str1= "XX";
String str2 = "OO";
String sep = "***";
if (numcols % 2 == 0) { // if columns is even
// for each row
for (int i = 1; i <= numrows; i++) {
// for each column
for (int k = 0; k < numcols/ 2; k++) {
if ( i % 2 == 1) { // for odds
if(k > 0) {
System.out.print(sep + str1 + sep+ str2);
}
else
System.out.print(str1 + sep + str2);
}
else { // for evens
if(k > 0) {
System.out.print(sep + str2 + sep + str1);
}
else
System.out.print(str2 + sep + str1);
}
}
System.out.println();
}
}
else { // if columns is odd
// for each row
for (int i = 1; i <= numrows; i++) {
// for each column
for (int k = 0; k < (numcols/ 2); k++) {
if ( i % 2 == 1) { // for odds
if(k > 0) {
System.out.print(sep + str1 + sep+ str2);
}
else
System.out.print(str1 + sep + str2);
}
else { // for evens
if(k > 0) {
System.out.print(sep + str2 + sep + str1);
}
else
System.out.print(str2 + sep + str1);
}
}
System.out.println();
}
}
Here you are :
// Declaration
int numrows = 5;
int numcols = 7;
String str1 = "XX";
String str2 = "OO";
String sep = "***";
for (int i = 0; i < numrows; i++) {
for (int j = 0; j < numcols; j++) {
if (j != 0) {
System.out.print(sep);
}
if (i % 2 == 0) {
if (j % 2 == 0) {
System.out.print(str1);
} else {
System.out.print(str2);
}
} else if (j % 2 == 0) {
System.out.print(str2);
} else {
System.out.print(str1);
}
}
System.out.println("");
}