Skip to content

Instantly share code, notes, and snippets.

@bhnascar
Created April 4, 2016 01:02
Show Gist options
  • Save bhnascar/1686f44ae68caaa3327eb773f8c611f1 to your computer and use it in GitHub Desktop.
Save bhnascar/1686f44ae68caaa3327eb773f8c611f1 to your computer and use it in GitHub Desktop.
More loop practice
public class Practice
{
public static void main(String[] args) {
// How can you replace the hard coded numbers
// with a variable and print out the same thing
// as the code below?
//
// There's more than one way to do this.
System.out.println(1);
System.out.println(3);
System.out.println(5);
System.out.println(7);
System.out.println(9);
System.out.println(11);
System.out.println(13);
System.out.println(15);
// How can you use a while loop to print out all multiples of 6
// that are greater than 0 and less than a hundred?
while (...) {
...
}
// How can you use a for loop to do the same thing?
for (...; ...; ...) {
...
}
// Here I'm making an 12 x 12 2D array of zeros.
int[][] arr = new int[12][12];
// How can you set half of the 2D array to ones?
// So it looks something like this (simplified):
// 1 0
// 1 0
// Run the program and check your result:
print2DArray(arr);
// How can you set the top right quarter of the 2D array to ones?
// So including the changes from the previous question, it should
// look something like this (simplified):
// 1 1
// 1 0
// Run the program and check your result:
print2DArray(arr);
// Okay I'm a new 12 x 12 array of zeros.
int[][] arr2 = new int[12][12];
// How can you create a checkerboard pattern?
// A simplified example:
// 1 0 1 0
// 0 1 0 1
// 1 0 1 0
// Run the program and check your result:
print2DArray(arr2);
}
/* Pretty-prints a 2D array of integers to the screen. */
public static void print2DArray(int[][] arr) {
System.out.println("\n\nPrinting 2D array...");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment