Swastik Pattern in C++

naivedh profile image Naivedh Updated on ・2 min read

Hello World!!
So, Today we are going to talk about patterns in c++. Some people have a question why Patterns?? My answer to it is "Improves your Logic" and if you're going to sit in a Campus Interview I would suggest you, go through patterns, improve your logic because many times there are questions about patterns and logic.

So let's, Start today we will learn a pattern called Swastik.

Alt Text

I would suggest you try it out the pattern first if you get stuck go through the code and if you are a newbie follow along.

First, we declare variables and ask the user for the number of row/columns(i.e 'n') and then we calculate mid-value.

Alt Text

Now, assume that we have entire n * n Matrix as shown below. We divide it into 4 parts.

Alt Text

We will use 2 for loops:
(a)For rows of 1 to mid-value(first 3 rows in the above image ).
(b)For rows of mid-value to n(next 2 rows in the above image).

Each for loop contains 2 for loops:
(c)For a column of 1 to mid-value(left side).
(d)For a column of mid-value to n(right side).

We enter the first main loop. In this loop, we loop through the 1st part out of 4 parts.
now if j==0 or j==mid or i==mid we print "*".

Alt Text

Now, loop through the 2nd part out of 4 parts. If i==0 or i==mid we will print "*".

Alt Text

We enter the Second main loop. In this loop, we loop through the 3rd part out of 4 parts. IF j==mid or i==n-1 we will print "*".

Alt Text

Now loop through the last part. If j==n-1 we print "*".

Alt Text

So, that's it. You can go through entire code at https://github.com/Naivedh/Swastik

Note: The spacing provided before-after "*" is so that it looks good you can remove it.

If you want to practice more patterns. Here are some of them.

Alt Text

Alt Text

Alt Text

Posted on by:

naivedh profile



I am Naivedh Shah, I am Web Developer and a Python Programmer.


markdown guide