Creating an X shape

I need some help with a homework problem. The question is asking me to create an X
shape with decrementing numbers.


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
/* The Output should look like this
5   1
 4 2
  3
 4 2
5   1

or

7     1
 6   2
  5 3
   4
  5 3
 6   2
7     1
*/
but so far I can only get a V shape. 

int main(int argc, char** argv) {
    int n;
    int x;
    
    cout<<"Enter an integer between 1-50.\n";
    cin>>n;
    
    if(n%2==1){ //loop for odd integers.
        x = n;
        for(int i = 1; i <= n; i++){
            cout<<setw(i)<<x<<setw(2*x)<<i<<endl;
            x--;
        }
    }else{  //branch for even integers.
        
    }

    return 0;
}

/*Right now my output looks like this:
5         1
 4       2
  3     3
   2   4
    1 5
*/


I'm having a hard time figuring out how to get the lines to converge at the middle number then diverge out.
Last edited on
Hi,
Not very sure, but can you please try this line :
cout<< setw(10 + i*2) << x < <setw(10 + 2*x*2) << i << endl;
Or :
cout<< setw(5 + i*4) << x << setw(5 + 2*x*2) << i << endl;
Nope that basically does the same thing I did with the formatting.
I'm having a hard time figuring out how to get the lines to converge at the middle number then diverge out.
Or maybe you try this then :
cout<< setw(5 + x*4) << x << setw(5 + 2*i*2) << i << endl;
If all else falls, you may consider using the alternative. Try this function :
1
2
3
4
5
6
7
8
#include <windows.h> 
void gotoxy(int x, int y)
{
  COORD coord;
  coord.X = x;
  coord.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}


And :
1
2
3
4
gotoxy(5 + x*4);
cout << x;
gotoxy(5 + 2*i*2);
cout << i;
Does that help you? :)
I probably shouldn't use that since the assignment requires me to use only for-loops and the iostream library.
Maybe this will be sufficient :
cout<< setw(8 + x*4) << x << setw(8 + 2*i*2) << i << endl;
Topic archived. No new replies allowed.