Tuesday, 5 March 2013

Print a diamond shape using asterisks in C/C++

#include<iostream.h>
#include<conio.h>
main()
{
int sum=3;
for(int i=-sum;i<=sum;i++)
{
for(int j=-sum;j<=sum;j++)
{
if(abs(i)+abs(j)<=sum)
{cout<<"*";}
else{cout<<" ";}
}
cout<<endl;
}
getch();
}



The above code will prints-
*
***
*****
*******
*****
***
*
Wait I haven’t done yet. You can have fun with it. Just change the ‘ if ‘ condition. You will get new design :) . Wanna see???. Lets take a look-
1if(abs(i)*abs(j)  <= NUM)
prints-
***
***
*******
*******
*******
***
***
1if( abs(i)+abs(j)==NUM)
prints-
*
*  *
*      *
*          *
*      *
*  *
*
1if( abs(i)==abs(j))
prints-
*          *
*      *
*  *
*
*  *
*      *
*          *
1if( abs(i)==0||abs(j)==0)
prints-
*
*
*
*******
*
*
*
1if( abs(i)>=abs(j))
prints-
*******
*****
***
*
***
*****
*******
1if(abs(i) <=abs(j))
prints-
*          *
**      **
***  ***
*******
***  ***
**      **
*          *

2 comments:

  1. how about using number 123 in shaping diamond ?

    ReplyDelete
  2. what is the mean of abs and why it is use plz answer me fast?

    ReplyDelete