C++ program to print diamond shape




Source Code :

#include <iostream>
using namespace std;

int main(){

int width,height,mid;
int l,r; // is a range of print line
cout<<"Enter Width for diamond : ";
cin>>width;

if(width%2 == 0){ // check if width is even then we make this odd by adding 1
width += 1; 
}

mid = width/2;

height = mid+1;

l=mid+1,r=mid+1;       // upper part of diamond

for(int i=1;i<=height;i++){

for(int j=1;j<=width;j++){

if(j >= l && j <= r){
cout<<"*";
}else{
cout<<" ";
}

}

l--;
r++;

cout<<endl;
}

l=1,r=width;              // below part of diamond

for(int i=1;i<=height;i++){

for(int j=1;j<=width;j++){

if(j >= l && j <= r){
cout<<"*";
}else{
cout<<" ";
}

}

l++;
r--;

cout<<endl;
}
system("pause");
return 0;

}


No comments:

Post a Comment