Pattern

I want to print output like this using loops only
Enter the number of rows: 5
5 4 3 2 1 0
4 5 4 3 2 1
3 4 5 4 3 2
2 3 4 5 4 3
1 2 3 4 5 4
0 1 2 3 4 5

Given below is what i have done till now ... Not coming up with any idea...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main(){
    int x, a;
    cin>>x;
    for(int i = 0; i<=x; i++){
        a=x;
        for(int j=0; j<=x; j++){
            if(i == 1) {
                cout <<a--<<" ";
            }
        }
        cout<<endl;
    }

}
Start with
0 1 2 3 4 5 4 3 2 1 0
Then figure out what your start position in that sequence is.
you have a bad case of tryhard here. step back and think about the problem before coding, and you may find something simpler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	unsigned int n = 43210;
	for(int i = 500000; i>=0; i-=100000)
	{		
                n+=i;
		if(n < 100000) cout << '0'; //leading zero on last value
		cout << n << endl;
		n/=10;
	}

out:
543210
454321
345432
234543
123454
012345


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
using namespace std;

void printIt( int N )
{
   for ( int i = 0; i <= N; i++ )
   {
      for ( int j = 0; j <= N; j++ ) cout << N - abs( i - j ) << " ";
      cout << '\n';
   }
}


int main()
{
   printIt( 5 );
}


5 4 3 2 1 0 
4 5 4 3 2 1 
3 4 5 4 3 2 
2 3 4 5 4 3 
1 2 3 4 5 4 
0 1 2 3 4 5 
we occasionally run into something what a c-string is just easier to deal with. this is one, borrowing salem's idea. Nothing you can't do with string, but its a lot more trouble. Destructive, though .. it breaks the c array as a side effect.

1
2
3
4
5
6
7
8
9
10
11
char c[] = "01234543210";
char * start = &c[5];
char * end = &c[10];
for(int i = 0; i < 6; i++)
{
  cout << start << endl; 
  start--;
  *end = 0;
  end--;  
}


experts... can you do it with string without having excess operations?
you can do it with cout &string[index] and moving the zero as I did, but it will print the extra 0 chars (harmless on a console) and I think its not considered friendly to do that?

lastchance has a less 'works for this one question' approach. I can't think of a way to avoid the extra work if you want it generic (as is so often the case).
Last edited on
Topic archived. No new replies allowed.