Printing a diamond pattern – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#3124 siteicon   siteicon   siteicon  

Printing a diamond pattern

A program that prints a diamond pattern of stars where a size unit is given in form of half of the diamond height.

Learning Objectives

  • Printing a filled diamond pattern using adjustment of pre print spaces first in decreasing order and then in increasing order.

Source Code

TC++ #3124

#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int n=5;
int i,j;
int sp=n-1;
for(int i=1;i<=n;++i)
{
for (j = 1; j<=sp; j++) cout<<" ";
sp--;
for (j=1;j<=2*i-1;j++) cout<<"*";
cout<<endl;
}
sp=1;
for(int i=1;i<=n-1;++i)
{
for (j=1;j<=sp;j++) cout<<" ";
sp++;
for (j=1;j<=2*(n-i)-1;j++) cout<<"*";
cout<<endl;
}
getch();
return 0;
}

Source Code

#include <iostream>
using namespace std;
int main()
{
int n=5;
int i,j;
int sp=n-1;
for(int i=1;i<=n;++i)
{
for (j = 1; j<=sp; j++) cout<<" ";
sp--;
for (j=1;j<=2*i-1;j++) cout<<"*";
cout<<endl;
}
sp=1;
for(int i=1;i<=n-1;++i)
{
for (j=1;j<=sp;j++) cout<<" ";
sp++;
for (j=1;j<=2*(n-i)-1;j++) cout<<"*";
cout<<endl;
}
return 0;
}

Test it !

Run Output

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

Code Understanding

int n=5; //This would diamond half height upto centre of diamond.
int i,j;    //These are loop index variables
int sp=n-1; //Since first row will have 1 star so spaces would be 1 less.
for(int i=1;i<=n;++i) //Row counting index for upper portion of the diamond
{
for (j = 1; j<=sp; j++) cout<<” “; //Prints spaces before the first star of each row.
sp–;                                                  //Space will have to be reduced for next row.
for (j=1;j<=2*i-1;j++) cout<<“*”; //This prints given number of *
cout<<endl;         //For new line for next row iteration
}
sp=1; //This will have to be set before printing reverse triangle the lower portion of diamond
for(int i=1;i<=n-1;++i)  //Outer loop for lower portion. This time it will be 1 less row as center row is already printed.
{
for (j=1;j<=sp;j++) cout<<” “;
Loop for printing of increasing number of spaces with each iteration
sp++; //Increasing it for next iteration
for (j=1;j<=2*(n-i)-1;j++) cout<<“*”;
Inner loop to print number of * upto half size and less than 1
cout<<endl; //New line for next row
}


Suggested Filename(s): diamond.cpp



Share

sunmitra| Created: 28-Jan-2018 | Updated: 28-Jan-2018|






Back