Problem with loop

I want this type of output:
1
2
3
4
5
1 2 3 5 1
2 1 0 8 5
3 0 1 9 6
5 8 9 1 7
1 5 6 7 1


i.e.,
the diagonal values should be "1" like this:
1
2
3
4
5
1
  1
    1
      1
        1


then, values in the right side of diagonal are randoms like this:
1
2
3
4
  2 3 5 1
    0 8 5
      9 6
        7


and values in the left side of diagonal are also randoms but symmetry of the previous random values like this:
1
2
3
4
5

2
3 0
5 8 9
1 5 6 7


Finally this 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
33
34
35
36
37
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
	//srand(time(0));
	int **a;
	int n;
	int i, j, k;

	cout<<"Enter the size of matrix: ";
	cin>>n;

	a = new int *[n];

	for(i=0; i<n; ++i){
		a[i][i] = 1;
		cout<<a[i][i]<<" ";
	}

	for(i=0; i<n; ++i){
		a[i] = new int[n];
		for(k=0; k<i; ++k)
			cout<<a[i][k]<<" ";
		for(j=i+1; j<n; ++j){
			a[i][j] = rand()%10+1;
			a[j][i] = a[i][j];
			cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
	
	

	system ("Pause");
	return 0;
}


Whats the wrong in my loop?? Anyone please help.
Look at line 17 closely, and then at line 22.

Use std::vector<>

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
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

int main()
{
    std::size_t n ;
    std::cout << "Enter the size of matrix:\n";
    std::cin >> n ;
    std::vector< std::vector<int> > a( n, std::vector<int>(n) ) ;

    std::srand( std::time(nullptr) ) ;
    for( std::size_t i = 0 ; i < n ; ++i )
    {
        a[i][i] = 1 ; // diagonal
        for( std::size_t j = i+1 ; j < n ; ++j )
            a[i][j] = a[j][i] = std::rand() % 10 ;
    }

    for( const auto& row : a )
    {
        for( int v : row ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://ideone.com/9HmNNT
Last edited on
Thanx a lot. :)
Topic archived. No new replies allowed.