Apr 7, 2019 at 2:07am UTC
Hi I need to print a diamond with 2 symbols so that the two symbols loos like stripes, however I am not sure of how to get the symbols to alternate .
This is my function to print the regular diamond
void Ascii::printDiamond(int width, char symbol1, char symbol2)
{
for (int i = width; i >= 1; i--) {
for (int j = 1; j < i; j++) {
cout << " ";
}
for (int k = width; k >= i; k--) {
cout << symbol1 << " ";
}
cout << endl;
}
for (int l = 1; l <= width - 1; l++) {
for (int j = 1; j <= l; j++) {
cout << " ";
}
for (int k = width - 1; k >= l; k--) {
cout << symbol2 << " ";
}
cout << endl;
}
}
Last edited on Apr 7, 2019 at 2:30am UTC
Apr 7, 2019 at 8:41am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void printDiamond( int width, char symbol1, char symbol2 )
{
for (int i = 1, step = 1; i; i += step )
{
cout << string( width - i, ' ' );
for ( int j = 1; j <= i; j++ ) cout << symbol1 << ' ' ;
cout << '\n' ;
swap( symbol1, symbol2 );
if ( i == width ) step = -1;
}
}
int main()
{
printDiamond( 8, '*' , 'O' );
}
*
O O
* * *
O O O O
* * * * *
O O O O O O
* * * * * * *
O O O O O O O O
* * * * * * *
O O O O O O
* * * * *
O O O O
* * *
O O
*
Last edited on Apr 8, 2019 at 8:16pm UTC
Apr 8, 2019 at 7:57pm UTC
@whitenite1 thanks but I am still trying to get the code so that the stripes are diagonal. I got the first half of the diamond by using (k%2==0) but I still cant seem to get the bottom half to match.
Apr 8, 2019 at 8:15pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void printDiamond( int width, char symbol1, char symbol2 )
{
string alt( 1, symbol1 ); alt += symbol2;
for (int i = 1, step = 1, sym0 = 0; i; i += step )
{
cout << string( width - i, ' ' );
for ( int j = 1, sym = sym0; j <= i; j++, sym = 1 - sym ) cout << alt[sym] << ' ' ;
cout << '\n' ;
if ( i == width ) step = -1;
if ( step > 0 ) sym0 = 1 - sym0;
}
}
int main()
{
printDiamond( 8, '*' , 'O' );
}
*
O *
* O *
O * O *
* O * O *
O * O * O *
* O * O * O *
O * O * O * O *
O * O * O * O
O * O * O *
O * O * O
O * O *
O * O
O *
O
If you want the stripes going the other way change it to
if ( step < 0 ) sym0 = 1 - sym0;
Last edited on Apr 8, 2019 at 8:55pm UTC