t1nman

lab2_1

Apr 30th, 2012
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. /*  determines if a numerical square magic (sum of elems in each column
  2.  *  equally sum of elems in each row and equally sum of elems
  3.  *  in main diagonal) or not magic                                      */
  4.  
  5. #include <stdio.h>
  6. int isMagic(void);
  7.  
  8. main()
  9. {
  10.     FILE *ofp;
  11.  
  12.     ofp = fopen("output.txt", "w");
  13.     if (isMagic() == 0)
  14.         fprintf(ofp, "%s\n", "NO");
  15.     else
  16.         fprintf(ofp, "%s\n", "YES");
  17.  
  18.     fclose(ofp);
  19.    
  20.     return 0;
  21. }
  22.  
  23. int isMagic(void)
  24. {
  25.     int i, j;
  26.     FILE *ifp;
  27.     int size, sum = 0, diag = 0, line = 0;
  28.     char square[10][10];
  29.     char col[10];
  30.  
  31.     ifp = fopen("input.txt", "r");
  32.     fscanf(ifp, "%d\n", &size);
  33.  
  34.     for (i = 0; i < size; i++)
  35.         for (j = 0; j < size; j++)
  36.             fscanf(ifp, "%d", &square[i][j]);
  37.        
  38.        
  39.     for (j = 0; j < size; j++) {
  40.         sum += square[0][j];
  41.         col[j] = 0;
  42.     }
  43.  
  44.     for (i = 0; i < size; i++) {
  45.         for (j = 0; j < size; j++) {
  46.             line += square[i][j];
  47.             col[j] += square[i][j];
  48.             if (i == j)
  49.                 diag += square[i][j];
  50.         }
  51.         if (line != sum)
  52.             return 0;
  53.         else
  54.             line = 0;
  55.     }
  56.  
  57.     for (j = 0; j < size; j++) {
  58.         if (col[j] != sum)
  59.             return 0;
  60.     }
  61.  
  62.     if (diag != sum)
  63.         return 0;
  64.    
  65.     fclose(ifp);
  66.     return 1;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment