Monday, 2 January 2023

Magic Matrices using C language

 

#include<stdio.h>

#include<conio.h>

int main(void){

    char ans;

    int a[15][15],i,j,k,l,m,x,y,n;

    do{

        ejaz:

        //clrscr();                   //this line will work in TurboC++  to clear the console

        printf("\n Enter any odd number b/n 3 to 15 to get magic matrix: ");

        scanf("%5d",&n);

        if(n%2==0||n<3||n>15)

        goto ejaz;

        for(j=(n-1)/2,k=1,i=0,l=0;l<n;l++){

            for(m=1;m<=n;i--,j--,m++,k++){

                if(j<0)

                j=n-1;

                if(m<=n&&i+1==0)

                i=n-1;

                a[i][j]=k;

            }

            i+=2;

            j++;

        }

        printf("\n\n");

        for(y=3,i=0;i<n;i++,y+=3){

            for(x=5,j=0;j<n;j++,x+=5){

               //gotoxy(x,y);                          //gotoxy can give printing location to curser in TurboC++  

               printf("%5d",a[i][j]);

            }

            printf("\n\n");                      // this line does not needed in TurboC++, the gotoxy is all it needed

        }

        printf("\n Want to continue y/n:  ");

        fflush(stdin);           // fflush(stdin) is uesd to clear the garbage from standard input stream

        ans=getchar();

    }while(ans=='y'||ans=='Y');

    //getch();                //this line will work in TurboC++  to hold screen of the console

}

No comments:

Post a Comment