Help with spacing in for loops

Hey guys just need a pointer!

Been working on a small project designed to print a hollow diamond.
I'm pretty much there but have been having trouble fixing a minor problem.

The diagonal line of my diamond running from the 12 o'clock to the 3 o'clock position is consistently '1 space to the left' of where it should be. Can't for the life of me figure out how to get this extra space in without everything else going to tits!

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

using namespace std;

int main()


{
   
int n;

cout << "Enter Diamond Width: ";
cin >> n;
	
	
for (int i=0; i < n; i++) /* This loop controls the TOP line */
 
    cout << " ";
    cout << "A" << endl;      /* "A" is being used as an example user boarder input */

for (int i = 1; i < n-1; i++)

    {
        for (int j = n-2; j >= i; j--)
			
			cout << " ";
			cout << "A";      

        for (int k = (n-2)/3; k <= i * 2; k++)
			
			cout << " ";
			cout << "A" << endl;    
    
	}

for (int i = 0; i < n-1; i++)

    {
        for (int j = 0; j < i; j++)
			
			cout << " ";
			cout << "A";      

        for (int k = (n-1)*2; k >= i * 2; k--)
			
			cout << " ";
			cout << "A" << endl;    

	}

for (int i = 0; i < n; i++) /* This loop controls the BOTTOM line */

    cout << " ";
    cout << "A";      

}


I think the problem lies in line 29 - the "k = (n-2)/3" bit. So close I can almost taste it but then again the most annoying problems are always at the end huh?

Any help is much appreciated!

Apologies if my forum/code formatting is not up to scratch. Newb to both!

Edit: Turns out its not 'one space' behind, it seems to change dependent on the size of the inputted value - which unfortunately makes the problem more of a pain in the butt
Last edited on
I noticed a nice little patter using the absolute value function. It usually looks like a really sharp right angle so I figured it might be able to do a diamond pretty well.
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 <cmath>

using namespace std;

int main()
{
   int n;
   char ch = 'A';

   cout << "Enter Diamond Width: ";
   cin >> n;
   
   for (int i = (1-n); i < n; i++)
   {
      for (int j = 0; j < abs(i); j++)
      { //outer spaces
         cout << " ";
      }
      cout << ch;
      
      if(abs(i) != (n-1)) //if not the first or last row, print a second "A"
      {
         for (int k = 1; k < 2*((n-1)-abs(i)); k++)
         { //inner spaces
            cout << " ";
         }
         cout << ch;
      }
      cout << endl;
   }
}
Last edited on
Thanks a lot! Never thought of building it from the middle outwards!

Onwards to putting lines through the middle :)
Topic archived. No new replies allowed.