80 likes | 235 Views
This guide explores nested for loops in Java, providing examples of how to print patterns based on line numbers. It includes code snippets demonstrating how to print increasing sequences of numbers, as well as more complex designs involving spaces and symbols. The examples start with a simple case where the output reflects the line number and expand to generalized forms that adjust the number of lines printed. Ideal for students and beginners looking to grasp the concept of nested loops and improve their coding skills.
E N D
CSC 1750 Nested for Loops Spring 2013
Nested for loops 1 12 123 1234 12345 123456 Start with 1 On each line print same number of chars as line number for (int i = 1; i <= 6; i++) { for (int k = 1; k <= i; k++) { System.out.print(k); } System.out.println(); }
Nested for loops 1 12 123 1234 12345 123456 Start with 1 On each line print same # of chars as line number for (int i = 1; i <= 6; i++) { for (int k = 1; k <= i; k++) { System.out.print(k); } System.out.println(); } Generalize int lines = 10; for (int i = 1; i <= lines; i++) { for (int k = 1; k <= i; k++) { System.out.print(k); } System.out.println(); }
Generalize int lines = 9; for (int i = 1; i <= lines; i++) { for (int k = 1; k <= lines – i + 1; k++) { System.out.print(k); } System.out.println(); } Nested for loops 123456 12345 1234 123 12 1 for (int i = 1; i <= 6; i++) { for (int k = 1; k <= 6 – i + 1; k++) { System.out.print(k); } System.out.println(); }
Generalize int lines = 9; for (int i = 1; i <= lines; i++) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int k = 1; k <= lines – i + 1; k++) { System.out.print(k); } System.out.println(); } Nested for loops 123456 12345 1234 123 12 1 for (int i = 1; i <= 6; i++) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int k = 1; k <= 6 – i + 1; k++) { System.out.print(k); } System.out.println(); }
Nested for loops – Pattern 1 1 222 33333 4444444 33333 222 1 // 1. declare & init variables int spaces = 3; int symbol = 1; int charsPerLine = 1; // 2. Print current line // inside outer loop //3. Update variables // for next line: if (i < 4) { spaces -= 1; symbol += 1; charsPerLine += 2; } else { spaces += 1; symbol -= 1; charsPerLine -= 2; } Try to generalize!!
Nested for loops – Pattern 3 //3. Update variables // for next line if (i < 3) { lSpaces += 1; mSpaces -=2; symbol1 = i + 1; symbol2 -= 1; } else { lSpaces -= I; mSpaces += 2; symbol1 = ???; symbol2 = ???; } // 1. declare & init variables int lSpaces = 0; int mSpaces = 3; int symbol1 = 1; int symbol2 = 5; 1 5 2 4 3 2 4 1 5 // 2. Print current line // inside outer loop