-
- #include <stdio.h>
- #include <conio.h>
- // func declaration
- void matrix( int n );
- // main()
- int main(void)
- {
- int n;
- // input until it's valid.
- do
- {
- }
- while ( n % 2 == 0 );
- if ( n > 20 ) { n = 19 ; // in case of n is greater than 20
- // call matrix()
- matrix(n);
- // stop to watch
- getch();
- return 0;
- }
- // function matrix(int n)
- void matrix( int n )
- {
- int a[20][20];
- int i, j, row, col, count = 1;
- int old_row, old_col, sum = 0;
- // set starting value of array
- for ( i = 0 ; i < n ; i++ )
- for ( j = 0 ; j < n ; j++ )
- a[i][j] = 0;
- // set the 1st value to start
- row = 0; col = (n-1) / 2;
- while ( count < n*n + 1 )
- {
- a[row][col] = count++ ; // set value for elements
- old_row = row ; old_col = col; // save the last addresses
- // define whether going out of array
- row -= 1; if ( row == -1 ) row = n - 1;
- col += 1; if ( col == n ) col = 0;
- // in case of already having number
- if ( a[row][col] != 0 )
- {
- row = old_row + 1;
- col = old_col;
- } // end if
- } // end while
- // print result
- for ( i = 0 ; i < n ; i++ )
- {
- for ( j = 0 ; j < n ; j++ )
- } // end for
- // calculate sum
- for ( j = 0 ; j < n ; j++ )
- sum += a[0][j];
- return;
- }
0 nhận xét:
Đăng nhận xét