Chapter 5: Patterns (Part 1) - Java With DSA
Introduction to Nested Loops
In Java, nested loops are essential when working with patterns, especially for creating shapes and designs like pyramids, squares, or character patterns. As the name suggests, a nested loop is a loop inside another loop. When working with two-dimensional patterns, the outer loop typically handles the rows, while the inner loop deals with the columns or the number of elements in each row.
For example, when printing a simple star pattern:
*****
*****
*****
*****
*****
You can see that it has 5 rows and 5 columns. Here’s how we can achieve this in Java using nested loops:
public class StarPattern {
public static void main(String[] args) {
// Outer loop for rows
for (int i = 1; i <= 5; i++) {
// Inner loop for columns
for (int j = 1; j <= 5; j++) {
System.out.print("*");
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
The outer loop controls the number of rows.
The inner loop controls how many stars to print in each row.
After printing one row of stars,
System.out.println()
moves the cursor to the next line.
i) Inverted Star Pattern
An inverted star pattern reverses the usual pyramid shape. For example, this inverted pattern:
*****
****
***
**
*
Here’s the Java code to print this pattern:
public class InvertedStarPattern {
public static void main(String[] args) {
// Outer loop for rows
for (int i = 5; i >= 1; i--) {
// Inner loop for columns
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
The outer loop starts from 5 and decrements with each iteration, which controls the number of stars printed in each row.
The inner loop runs only up to
i
, ensuring that the number of stars decreases as you move down the rows.
ii) Half Pyramid Pattern
A half-pyramid pattern is one of the simplest patterns. For example:
*
**
***
****
*****
Here’s the code to print the half-pyramid:
public class HalfPyramidPattern {
public static void main(String[] args) {
// Outer loop for rows
for (int i = 1; i <= 5; i++) {
// Inner loop for columns
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
The outer loop runs from 1 to 5 (for 5 rows).
The inner loop runs up to
i
, meaning the number of stars increases with each row.
iii) Character Pattern
In addition to stars, we can also print characters. For example, this character pattern:
A
A B
A B C
A B C D
A B C D E
To print this pattern, we need to understand the ASCII values of characters. Java treats characters as integers when working with loops. Here’s the code for the pattern:
public class CharacterPattern {
public static void main(String[] args) {
// Outer loop for rows
for (int i = 1; i <= 5; i++) {
// Inner loop for columns
for (int j = 1; j <= i; j++) {
System.out.print((char)('A' + j - 1) + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
The outer loop controls the number of rows.
The inner loop controls how many characters are printed in each row.
The
char
conversion(char)('A' + j - 1)
ensures that we print characters starting from 'A'. Asj
increments, the character advances in the alphabet.
What's Next?
In the upcoming chapter, we will learn about functions and methods in Java, and we will use these concepts to build more advanced patterns. Functions allow us to write more efficient, modular, and reusable code. This will be especially useful when working on complex patterns as we can encapsulate repetitive tasks within functions.
By the end of the next chapter, we’ll be able to:
Break down complex problems into manageable functions.
Create reusable methods to generate patterns dynamically.
Work on advanced pattern creation using recursion.
Stay tuned for the next chapter on Functions and Methods!
Follow my journey through the Java with DSA series as we explore more exciting concepts!
Related Posts:
You might be interested in exploring more detailed topics in my ongoing series:
- Full Stack Java Development: A comprehensive guide to becoming a full stack Java developer.
Connect with me:
Your feedback and engagement are invaluable. Feel free to reach out with questions, comments, or suggestions. Happy coding!
Rohit Gawande
Full Stack Java Developer | Blogger | Coding Enthusiast
Subscribe to my newsletter
Read articles from Rohit Gawande directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rohit Gawande
Rohit Gawande
🚀 Tech Enthusiast | Full Stack Developer | System Design Explorer 💻 Passionate About Building Scalable Solutions and Sharing Knowledge Hi, I’m Rohit Gawande! 👋I am a Full Stack Java Developer with a deep interest in System Design, Data Structures & Algorithms, and building modern web applications. My goal is to empower developers with practical knowledge, best practices, and insights from real-world experiences. What I’m Currently Doing 🔹 Writing an in-depth System Design Series to help developers master complex design concepts.🔹 Sharing insights and projects from my journey in Full Stack Java Development, DSA in Java (Alpha Plus Course), and Full Stack Web Development.🔹 Exploring advanced Java concepts and modern web technologies. What You Can Expect Here ✨ Detailed technical blogs with examples, diagrams, and real-world use cases.✨ Practical guides on Java, System Design, and Full Stack Development.✨ Community-driven discussions to learn and grow together. Let’s Connect! 🌐 GitHub – Explore my projects and contributions.💼 LinkedIn – Connect for opportunities and collaborations.🏆 LeetCode – Check out my problem-solving journey. 💡 "Learning is a journey, not a destination. Let’s grow together!" Feel free to customize or add more based on your preferences! 😊