fork(16) download
  1. #include <stdio.h>
  2.  
  3. #define N 99
  4.  
  5. int main()
  6. {
  7. int n, i, j, magic[N][N] = {0}, row = 0, col;
  8.  
  9. printf("This programs creates a magic squares of a specified size.\n");
  10. printf("The size must be an odd number between 1 and 99.\n");
  11. printf("Enter the size of magic square: ");
  12. scanf("%d", &n);
  13.  
  14.  
  15. col = (n-1)/2; //starting position
  16. magic[row][col] = 1;
  17.  
  18. for(i = 2; i <= n*n; i++) {
  19. row = (row + n - 1)%n; //the usual moves: column up, row under
  20. col = (col + 1)%n; //the modulo is a quick solution to the "rolling trouble"
  21. if(magic[row][col] != 0) { //but if that place's occupied, let's move under the last 'i' placed
  22. row = (n + row + 2)%n;
  23. col = (n + col - 1)%n;
  24. }
  25. magic[row][col] = i; //and let the cycle starts again
  26. }
  27.  
  28. printf("\n"); //printing the array
  29. for (i = 0; i < n; i++) {
  30. for (j = 0; j < n; j++) {
  31. printf("%4d", magic[i][j]);
  32. }
  33. printf("\n");
  34. }
  35. return 0;
  36. }
Success #stdin #stdout 0s 2856KB
stdin
Standard input is empty
stdout
This programs creates a magic squares of a specified size.
The size must be an odd number between 1 and 99.
Enter the size of magic square: