This blog is under construction

Sunday 23 June 2013

C program to generate magic square

Write a C program to generate magic square.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int x, y, z, flag = 0, M, n = 3, count = 0;

        /* calculate the magic number */
        M = ((n * n * n) + n) / 2;
        printf("Magic number is %d\n", M);

        /*
         * magic no is nothing but the sum of elements in any row,
         * sum of elements in any column and sum of elements in 
         * any diagonal should give the same value(magic number)
         */
        for (x = 0; x < 10; x++) {
                for (y = 0; y < 10; y++) {
                        for (z = 0; z < 10; z++) {
                                /* print magic squares alone */
                                if ((x - z + x + z - y + x + y) == M) {
                                        if ((x - z + x + y +z + x - y) == M)
                                                if ((x - z + x + x + z) == M) {
                                                        printf("Magic Square %d:\n", count + 1);
                                                        printf("%d %d %d\n", (x - z) ,
                                                                          (x + z - y), (x + y));
                                                        printf("%d %d %d\n", x + y +z, x, x - y - z);
                                                        printf("%d %d %d\n", x - y, x + y - z, x + z);
                                                        printf("\n\n");
                                                        count++;
                                                        if (count == 5)
                                                                exit(0);
                                                }
                                }
                        }
                }
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Magic number is 15
  Magic Square 1:
  5 5 5
  5 5 5
  5 5 5

  Magic Square 2:
  4 6 5
  6 5 4
  5 4 6

  Magic Square 3:
  3 7 5
  7 5 3
  5 3 7

  Magic Square 4:
  2 8 5
  8 5 2
  5 2 8

  Magic Square 5:
  1 9 5
  9 5 1
  5 1 9



No comments:

Post a Comment