Chủ Nhật, 30 tháng 3, 2014

MA PHƯƠNG


  1. #include <stdio.h>
  2. #include <conio.h>
  3. // func declaration
  4. void matrix( int n );
  5. // main()
  6. int main(void)
  7. {
  8.     int n;
  9.    
  10.     // input until it's valid.
  11.     do
  12.     {
  13.     printf("\n Plz input size of matrix [ odd size & n < 20 ]: n = ");
  14.     scanf("%d",&n);
  15.     if ( n % 2 == 0 ) printf("\n Invalid input value .. Plz re-input ... \n");
  16.     }
  17.     while ( n % 2 == 0 );
  18.    
  19.     if ( n > 20 ) { n = 19 ; // in case of n is greater than 20
  20.     printf("\n %d is greater than 20 & set to be default as 19 .",); } // end if
  21.    
  22.     // call matrix()
  23.     matrix(n);
  24.     // stop to watch
  25.     getch();
  26.     return 0;
  27. }
  28. // function matrix(int n)
  29. void matrix( int n )
  30. {
  31.      int a[20][20];
  32.      int i, j, row, col, count = 1;
  33.      int old_row, old_col, sum = 0;
  34.      
  35.      // set starting value of array
  36.      for ( i = 0 ; i < n ; i++ )
  37.      for ( j = 0 ; j < n ; j++ )
  38.          a[i][j] = 0;
  39.      
  40.      // set the 1st value to start
  41.      row = 0; col = (n-1) / 2;
  42.      
  43.      while ( count < n*+ 1 )
  44.      {
  45.            a[row][col] = count++ ; // set value for elements
  46.            old_row = row ; old_col = col; // save the last addresses
  47.            // define whether going out of array
  48.            row -= 1; if ( row == -1 ) row = n - 1;
  49.            col += 1; if ( col == n ) col = 0;
  50.            // in case of already having number
  51.            if ( a[row][col] != 0 )
  52.            {
  53.                 row = old_row + 1;
  54.                 col = old_col;
  55.            } // end if
  56.      } // end while
  57.      // print result
  58.      printf("\n");
  59.      for ( i = 0 ; i < n ; i++ )
  60.      {
  61.      for ( j = 0 ; j < n ; j++ )
  62.          printf("%4d",a[i][j]);
  63.      printf("\n");
  64.      } // end for
  65.      
  66.      // calculate sum
  67.      for ( j = 0 ; j < n ; j++ )
  68.          sum += a[0][j];
  69.      printf("\n Sum of each row - column - diagonal line is : %d " , sum);
  70.      
  71.      return;
  72. }

0 nhận xét:

Đăng nhận xét