Trick to master Pattern problems in programming

Trick to master Pattern problems in programming

ยท

7 min read

Introduction

Hey folks ๐Ÿ‘‹! In this article, we will master a trick with which you can solve most of the pattern problems very easily. In pattern problems, the programmer has to print a pattern. Pattern problems are important from the point of view of technical job interviews. All around the internet, you can find number of logic to solve pattern problems. Memorizing the logic for each pattern problem can be difficult and not suggested way. So in this article, we will learn a technique with which you can solve many pattern problems using one logic only.

Prerequisites

  1. Understanding of programming fundamentals

  2. Data types, conditional statements, and loops in any programming language

  3. Functions

I will use the C language for demonstration, but if you understand the core concept, you can implement it in your programming language. If you are comfortable with all the prerequisites, let's jump to the central concept:-

Basic structure of any pattern problem

In programming, to do the repeated tasks, we use loops. If I want to print * * * * * I will use for loop as

for(int i=1 ; i<=5; i++)
     printf("*")

So in patterns like this

* * * * *
* * * * *
* * * * *
* * * * * 
* * * * *

There are 5 rows and 5 columns. So we need to use two for loops for printing the pattern. The first for loop is used for rows and in each row, the inner for loop will print 5 columns.

Code snippet:-

for(int i=1;i<=5;i++)
{
   for(int j=1;j<=5;j++)
       {
         printf("*");
       }
}

I hope you get the basic idea of printing of pattern.

Before moving to hard problems, we need to learn two very basic patterns that will help us in solving complex problems.

Basic triangle patterns

1. Increasing Triangle

1..png

In this pattern, the number of stars increases with the number of rows. So we can say that each column should be up to the value of the row. Code:-

#include<stdio.h>
int main(){
int n=5;
for(int row=1;row<=n;row++)
    {
     for(int col=1;col<=row;col++)
          {
            printf("* ");
           }
     printf("\n");
    }
return 0;
}

2. Decreasing triangle

1. (1).png

Now let's have look at this pattern. In this pattern, with every increase in a row, number of stars decreases. So if we try to look at the relationship between rows and columns, we see that

No of columns= Total number of rows - row index ( current row number)

The code will be like this:-

#include<stdio.h>
int main(){
int n=5;
for(int row=1;row<=n;row++)
    {
     for(int col=row;col<=n;col++)
          {
            printf("* ");
           }
     printf("\n");
    }
return 0;
}

If the column starts from the row number i.e row number =2, the columns will be from 2-5, which means four columns. Thus four stars are printed.

Now you have an understanding of basic patterns, let's have a look at how can we solve complex patterns using these basic patterns.

Level-1 Problem

3.png

There can be various logic to solve this problem directly, but for a beginner, it would be difficult to get that logic in less time. So we will look at how can we solve this problem using the increasing - decreasing triangle concept. Have a look at this picture:-

4.png

Yellow area represents decreasing triangle , Stars represents increasing triangle

So we will use two for loops inside the row loop:-

#include<stdio.h>
int main(){
int n=5;
for(int row=1;row<=n;row++)
    {
      for(int col=row;col<n;col++)    // Decreasing triangle 
          {
            printf("  ");                             // printing spaces
           }
     for(int col=1;col<=row;col++)          // Increasing Triangle
          {
            printf("* ");
           }
     printf("\n");
    }
return 0;
}

Congratulations! You have come so far. You cleared the level 1 of understanding pattern problems.

Level-2 Problem

5.png

This is a star pyramid pattern. Let's visualise how can we split this pyramid into increasing and decreasing triangles:-

1. (2).png

So now we have an idea of how many increasing and decreasing triangles are in the pyramid, it is very easy to write code for this. Just write for loops according to the triangles

#include<stdio.h>
int main(){
int n=5;
for(int row=1;row<=n;row++)
    {
      for(int col=row;col<n;col++)           // Decreasing triangle 
          {
            printf("  ");                                 // printing spaces
           }
     for(int col=1;col<row;col++)          // Increasing Triangle
          {
            printf("* ");
           }
     for(int col=1;col<=row;col++)          // Increasing Triangle
          {
            printf("* ");
           }
     printf("\n");
    }
return 0;
}

In the middle for loop, we have written for(int col=1; col<row;col++) so that a peak can be formed, otherwise we have two stars from both sides. Try to run this code on your own and play around with it.

Similar to this problem, we have another pattern, but it includes spaces at alternate positions. 6.png

So the code is exactly the same as the previous, but we just need to maintain a boolean value with which we print the spaces at alternate positions.

#include<stdio.h>
#include <stdbool.h>
int main ()
{
  int n = 5;

  for (int row = 1; row <= n; row++)
    {
      bool printValue = true;
      for (int col = row; col < n; col++)    // Decreasing triangle 
    {
      printf (" ")        // printing spaces
    }
      for (int col = 1; col <= row; col++)    // Increasing Triangle
    {
      // conditional statement - if printValue is true print * , else print space
      printValue ? printf ("*") : printf (" ");

      //toggling the boolean value
      printValue = printValue ? false : true;
    }

      for (int col = 1; col <= row; col++)    // Increasing Triangle
    {
      printValue ? printf ("*") : printf (" ");
      printValue = printValue ? false : true;
    }
      printf ("\n");
    }
  return 0;
}

Level 2 cleared ๐ŸŽŠ๐ŸŽŠ๐ŸŽŠ Let's take this learning ride to hard level

Level 3 Problem

After understanding this pattern problem, you will solve most of the pattern problems easily.

8.png This pattern is known as butterfly ๐Ÿฆ‹ pattern.

Like we do previously, we will visualise this pattern in terms of increasing and decreasing triangles.

9.png

Splitting row and column-wise and then adding space area in all quadrants.

In this problem, we need to use two for loops for rows and inside each row-for loop, we will write loops for columns accordingly.

#include<stdio.h>
int main ()
{
  int n = 5;
  for (int row = 1; row <= n; row++)        // rows from 1-5
    {

      for (int col = 1; col <= row; col++)    // Increasing Triangle
        printf ("* ");

      for (int col = row; col < n; col++)    // Decreasing triangle 
        printf ("  ");    // printing spaces

      for (int col = row; col < n; col++)    // Decreasing triangle 
        printf ("  ");    // printing spaces

      for (int col = 1; col <= row; col++)    // Increasing Triangle
        printf ("* ");

      printf ("\n");
    }
  for (int row = 1; row <= n - 1; row++)    // rows from 6-9  
    {
      for (int col = row; col < n; col++)    // Decreasing triangle 
        printf ("* ");        

      for (int col = 1; col <= row; col++)    // Increasing Triangle
        printf ("  ");

      for (int col = 1; col <= row; col++)    // Increasing Triangle
        printf ("  ");

      for (int col = row; col < n; col++)    // Decreasing triangle 
        printf ("* ");        


      printf ("\n");
    }
  return 0;
}

If n=5, then number of rows=9 (2n-1) &

number of columns= 10 (2n)

So first we run the loop for rows 1-5 and then from 6-9 (row=1 to n-1) and then inside these for loops, we write for loops for columns according to their increasing and decreasing form.

While writing these loops condition for columns, some areas are not forming a complete triangle, so in condition statement less than < will be used instead of <=

Bonus Problems ๐Ÿค‘

Visit this link ๐Ÿ‘‡ and try to print the patterns using this technique:-

Pattern Problems

Conclusion

This technique can be used to solve most of the pattern problems that consist of triangles in any way. In some problems, instead of stars, you need to print some numbers. Just try to analyze the relation of values with rows and columns and you can print that pattern easily. These pattern problems help you to build a strong fundamental understanding of programming logic, so try to solve bonus problems.

Thanks for reading my first blog ๐Ÿค— and let me know your feedback or if you are facing any problems in the comment section.

Connect with me on Twitter

Did you find this article valuable?

Support Prabhjot Kaur by becoming a sponsor. Any amount is appreciated!

ย