How to print diamond patterns using recursion?
Overview
The pattern problem is one of the most common problems in any programming language. It can easily be solved using loops, but the problem occurs when someone tells us that we can only solve the pattern problem using recursion. This shot tries to solve the Diamond pattern problem using recursion. To solve the Diamond pattern problem, we first need to understand what the Diamond pattern problem is.
The Diamond pattern problem
The Diamond pattern problem is used to draw the following pattern with the use of asterisks *. Below is the diamond shape row, which represents the height of a Diamond. ♦️
Note: The value of a
rowcan be any number.
#include<iostream>using namespace std;void moveTonextLine(int k,int i,int z){if(k==i)// Base casereturn;cout<<"* ";moveTonextLine(k+z,i,z);}void addSpaceInDiamond(int j,int i,int z) // print space of diamond{if(j==i)return;cout<<" ";addSpaceInDiamond(j+z,i,z); // send recursive call}void upperPartOfDiamond(int row,int i){if(i>row)// Base casereturn;addSpaceInDiamond(row,i,-1);moveTonextLine(0,i,1);cout<<endl;upperPartOfDiamond(row,i+1);// send recursive call}void lowerPartOfDiamond(int row,int i)// print next line of diamond{if(i>row) // Base casereturn;addSpaceInDiamond(0,i,1);moveTonextLine(row,i,-1);cout<<endl;lowerPartOfDiamond(row,i+1); // send recursive call}int main(){int row,i,j,k;row =5;upperPartOfDiamond(row,0); // print uper part of trianglelowerPartOfDiamond(row,1);// print lower part of diamondreturn 0;}
Code example
#include<iostream>using namespace std;void moveTonextLine(int k,int i,int z){if(k==i)// Base casereturn;cout<<"* ";moveTonextLine(k+z,i,z);}void addSpaceInDiamond(int j,int i,int z) // print space of diamond{if(j==i)return;cout<<" ";addSpaceInDiamond(j+z,i,z); // send recursive call}void upperPartOfDiamond(int row,int i){if(i>row)// Base casereturn;addSpaceInDiamond(row,i,-1);moveTonextLine(0,i,1);cout<<endl;upperPartOfDiamond(row,i+1);// send recursive call}void lowerPartOfDiamond(int row,int i)// print next line of diamond{if(i>row) // Base casereturn;addSpaceInDiamond(0,i,1);moveTonextLine(row,i,-1);cout<<endl;lowerPartOfDiamond(row,i+1); // send recursive call}int main(){int row,i,j,k;row =5;upperPartOfDiamond(row,0); // print uper part of trianglelowerPartOfDiamond(row,1);// print lower part of diamondreturn 0;}
Code explanation
In the Diamond shape that is printed, we can see the following things:
- Asterisk (
*) - Space
- Next line
- Upper and lower parts of the
Diamond
Now, let’s try and understand the code that is used to print the Diamond shape:
-
In line 3, we write the
moveTonextLinefunction, which helps the courser move to the next line when printing one row of asterisks (*). -
In line 10, we write the
addSpaceInDiamondfunction, which manages the space between the asterisks (*). -
In lines 17–26, we write the
upperPartOfDiamondand thelowerPartOfDiamond functions, which print the upper and lower part of theDiamond.