Last active
January 16, 2019 07:01
-
-
Save pbesra/f553891b6ef1053c2be1db36fff1ec47 to your computer and use it in GitHub Desktop.
Diamond shape | C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
void solution(int n){ | |
// prints top triangle. | |
int m=2*n-1; | |
int t1=m/2; | |
int t2=m/2; | |
int t3=m/2; | |
int t4=m/2; | |
for(int i=0;i<n;i++){ | |
// prints left space | |
for(int j=0;j<t1;j++){ | |
cout << " "; | |
} | |
//prints star | |
//cout << "t2: " << t2 ; | |
// prints 'x' in odd and even places such no two 'x' have same column in two consecutive rows. | |
if(t2%2==0){ | |
for(int j=t2;j<=t3;j++){ | |
if(j%2==0){ | |
cout << "x"; | |
}else{ | |
cout << " "; | |
} | |
} | |
}else{ | |
for(int j=t2;j<=t3;j++){ | |
if(j%2==1){ | |
cout << "x"; | |
}else{ | |
cout << " "; | |
} | |
} | |
} | |
//prints right space | |
for(int j=t4;j<=2*n-1;j++){ | |
cout << " "; | |
} | |
cout << endl; | |
t1--; | |
t2--; | |
t3++; | |
t4++; | |
} | |
// prints lower triangle | |
m=2*n-2; | |
t1=0; | |
t2=1; | |
t3=(2*n-2); | |
t4=m/2; | |
for(int i=0;i<n-1;i++){ | |
// prints left space | |
for(int j=0;j<=t1;j++){ | |
cout << " "; | |
} | |
//prints star | |
//cout << "t2: " << t2 ; | |
if(t2%2==0){ | |
for(int j=t2;j<=t3;j++){ | |
if(j%2==0){ | |
cout << "x"; | |
}else{ | |
cout << " "; | |
} | |
} | |
}else{ | |
for(int j=t2;j<=t3;j++){ | |
if(j%2==1){ | |
cout << "x"; | |
}else{ | |
cout << " "; | |
} | |
} | |
} | |
//prints right space | |
for(int j=t4;j<=2*n-1;j++){ | |
cout << " "; | |
} | |
cout << endl; | |
t1++; | |
t2++; | |
t3--; | |
t4--; | |
} | |
} | |
int main(){ | |
int n=20; | |
solution(n); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment