Creating an X in the Terminal

Hello,
I can only get part of the X to show up in the terminal. It is supposed to look like this:
*     *
 *   *
  * *
   *
  * *
 *   *
*     *

Can anyone help me? Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
using namespace std;

int main()
{
int size = 4;
	char c = '*';
	string str;
	int diff_size = (size + (size - 1));
	for(int i=0; i < diff_size; i++) // rows
	{
		for (int j = 0; j <= i; j++) // columns
		{
			if(i == j) // this is correct
			{
				str += c;
			}
			else if(j == (diff_size - i))
			{
				str += c;
			}
			else // this is correct
			{
				str += " ";
			}
		}
		str += '\n';
	}
	cout << str;
	return 0;
}

I believe that something is wrong inside my nested for loops.
My outcome currently is this:
*
 *
  *
   *
   **
  *  *
 *    *

I think your j loop needs to cover the same range as the i one. Not stop when it reaches i.

To check this out, try adding '.' rather then ' ' in the else case.
Last edited on
Thank you Andy from your suggestions I was able to figure out the rest of my problems. My final code is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
using namespace std;

int main()
{
int size = 4;
char c = 4;
string str;
int diff_size = (size + (size - 2));// change size -1 to size - 2 
	for(int i=0; i <= diff_size; i++) // changed < to <=
	{
		for (int j = 0; j <= diff_size; j++) // changed j <= i to j <= diff_size
		{
			if(i == j) 
			{
				str += c;
			}
			else if(j == (diff_size -i))
			{
				str += c;
			}
			else 
			{
				str += " ";
			}
		}
		str += '\n';
	}
        cout << str;
        return 0;
}


Topic archived. No new replies allowed.