//C code to print magic square for odd numbers entered
#include<stdio.h>
/*function to get number of digits*/
int get_num_of_digits(n)
{
int k = 0 ;
while (n!=0)
{
n/=10;
k++;
}
return k;
}
/* move up */
int up ( int n , int i)
{
return i==0?n-1:--i;
}
/*move left */
int left ( int n , int j)
{
return j==0?n-1:--j ;
}
/*To print magic square*/
void print_magic( int n , int a[][n])
{
int b , c , d, i , g;
d = get_num_of_digits(n*n);
for(b = 0 ; b< n ; b++)
{
for (c= 0 ; c<n ; c++)
{
g = get_num_of_digits(a[b][c]);
for ( i = 0; i<d-g ; i++)
printf(" ");
printf("%d " , a[b][c]);
}
printf("\n");
}
}
/* to store magic elements*/
int store_magic_element(int n , int i , int j , int k , int a[][n])
{
a[i][j] = k++;
return k;
}
/*Function to get magic square*/
void get_magic_square(int n , int a[][n])
{
int i= 0 , j = n/2 ;
int count = 0 , temp , k = 1;
while ( count!= n)
{
k = store_magic_element(n , i , j , k , a);
temp = 1;
while(temp!=n)
{
i = up(n , i);
j = left(n , j);
k = store_magic_element(n , i , j , k , a);
temp++;
}
count++;
i++;
}
}
/*main function*/
int main()
{
int n ;
printf("enter the order of matrix : ");
scanf("%d" , &n);
int a[n][n];
get_magic_square(n , a);
print_magic( n , a);
}
#include<stdio.h>
/*function to get number of digits*/
int get_num_of_digits(n)
{
int k = 0 ;
while (n!=0)
{
n/=10;
k++;
}
return k;
}
/* move up */
int up ( int n , int i)
{
return i==0?n-1:--i;
}
/*move left */
int left ( int n , int j)
{
return j==0?n-1:--j ;
}
/*To print magic square*/
void print_magic( int n , int a[][n])
{
int b , c , d, i , g;
d = get_num_of_digits(n*n);
for(b = 0 ; b< n ; b++)
{
for (c= 0 ; c<n ; c++)
{
g = get_num_of_digits(a[b][c]);
for ( i = 0; i<d-g ; i++)
printf(" ");
printf("%d " , a[b][c]);
}
printf("\n");
}
}
/* to store magic elements*/
int store_magic_element(int n , int i , int j , int k , int a[][n])
{
a[i][j] = k++;
return k;
}
/*Function to get magic square*/
void get_magic_square(int n , int a[][n])
{
int i= 0 , j = n/2 ;
int count = 0 , temp , k = 1;
while ( count!= n)
{
k = store_magic_element(n , i , j , k , a);
temp = 1;
while(temp!=n)
{
i = up(n , i);
j = left(n , j);
k = store_magic_element(n , i , j , k , a);
temp++;
}
count++;
i++;
}
}
/*main function*/
int main()
{
int n ;
printf("enter the order of matrix : ");
scanf("%d" , &n);
int a[n][n];
get_magic_square(n , a);
print_magic( n , a);
}
No comments:
Post a Comment