Day 4: Loop Logic
🔁 Day 4: Loop Logic
🧠 Main Concepts Today:
- Understand the logic behind questions.
- Practice concatenation in loops (joining values into a string).
- Implement logic using
while
loops.
🧩 Pattern Practice: Let's Understand These Patterns
We'll write logic for the following patterns:
1) 7,10,8,11,9,12
2) 22,21,23,22,24,23
3) 53,53,40,40,27,27
4) 3,6,9,24,48,96
5) 36,34,30,28,24
6) 8,22,8,28,8,34
7) 120,99,80,63,48
8) 25,10,17,26
✏️ Java Code (Main Focus)
Let’s write Java logic with while
or for
loops and String concatenation
using +
.
🔹 1. Pattern: 7,10,8,11,9,12
int a = 7, b = 10;
for (int i = 0; i < 3; i++) {
System.out.print(a + "," + b + ",");
a++;
b++;
}
Output: 7,10,8,11,9,12,
🔹 2. Pattern: 22,21,23,22,24,23
int x = 22, y = 21;
for (int i = 0; i < 3; i++) {
System.out.print(x + "," + y + ",");
x++;
y++;
}
🔹 3. Pattern: 53,53,40,40,27,27
int i = 53;
while (i >= 27) {
System.out.print(i + "," + i + ",");
i -= 13;
}
🔹 4. Pattern: 3,6,9,24,48,96
int[] first = {3, 6, 9};
for (int num : first) {
System.out.print(num + ",");
}
int val = 24;
while (val <= 96) {
System.out.print(val + ",");
val *= 2;
}
🔹 5. Pattern: 36,34,30,28,24
for (int i = 36; i >= 24; i -= (i % 2 == 0 ? 2 : 4)) {
System.out.print(i + ",");
}
(Simpler version:)
int[] arr = {36, 34, 30, 28, 24};
for (int i : arr) {
System.out.print(i + ",");
}
🔹 6. Pattern: 8,22,8,28,8,34
int fixed = 8, change = 22;
for (int i = 0; i < 3; i++) {
System.out.print(fixed + "," + change + ",");
change += 6;
}
🔹 7. Pattern: 120,99,80,63,48
int[] nums = {120, 99, 80, 63, 48};
for (int n : nums) {
System.out.print(n + ",");
}
🔹 8. Pattern: 25,10,17,26
int[] lastPattern = {25, 10, 17, 26};
for (int n : lastPattern) {
System.out.print(n + ",");
}
🧠 What I Understood
- Before coding, I need to analyze the pattern logic.
- Understand if it's repeating, alternating, or increasing/decreasing.
- Store and combine values with string concatenation.