Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Name: magicsquare.c
- Copyright:
- Author: Mr.Kindle
- Date: 29-11-22 23:24
- Description: This program print the n*n magic square. Provided that 'n' must be an odd number.It also print the sum
- of each row or column or digonals which are equal offcourse.
- youtube: https://youtu.be/uVnsJjwLT4Y
- */
- #include<stdio.h>
- #include<stdlib.h>
- #define MAX 15
- void magicsquare( int);
- void display();
- /*taking mat and n as global variable so that all other function may use it*/
- int MAT[MAX][MAX];
- int n;
- int main()
- {
- int i,j,num;
- int count=0;
- printf("Enter 'n' (an odd number only) for n*n matrix: ");
- scanf("%d",&n);
- if(n%2 == 0)//check for even number which is not acceptable
- {
- printf("\nPlease enter only odd number: ");
- exit(1);
- }
- printf("Enter initial (or minimum range) number: ");
- scanf("%d",&num);
- magicsquare( num);
- printf("\n\n");
- display();
- return 0;
- }//main
- void magicsquare( int num)
- {
- int i,j,no_of_term;
- int term;
- no_of_term = n*n;//total number of element
- /*setting INitial position of cursor*/
- i=(n-1)/2; //middle row
- j=0; //first column
- for(term=1;term<=no_of_term;term++)
- {
- MAT[i][j]=num++;//first assign then increase
- if(term%n == 0)//if term is multiple of 'n'
- j++; //take the cursor one step right
- else
- { i++; //go down
- j--; //go left
- }
- /*if cursor comes out of the matrix*/
- if(i>n-1)
- i=0;
- if(j<0)
- j=n-1;
- }//for
- }//end of magic square
- void display()
- {
- int i,j,sum = 0;
- for (i=0;i<n;i++)
- {
- printf("|"); //for decoration
- for (j=0;j<n;j++)
- {
- printf(" %2d |",MAT[i][j]);
- if(i==0)
- {
- sum = sum + MAT[i][j];
- }
- }
- printf("\n");
- }
- printf("\n\n sum of each row, each column or each digonal is = %d",sum);
- }//end of display
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement