Tp6_1.c 2.13 KB
#include <stdio.h>
#include <string.h>

#define N 3

//lecture mat taille N*N
void lireMatrice (int mat[][N], int n){
        
    int i,j;
    for(i=0; i <= n-1 ; i++){
       
        for(j=0; j <= n-1; j++){
            scanf("%d", &mat[i][j]);
        }
    }
}

// affiche matrice carre
void afficheMat (int mat[][N], int n){
    int i,j;
    for(i=0; i <= n-1 ; i++){
       
        for(j=0; j <= n-1; j++){
           printf(" %d ", mat[i][j]);
        }
        printf("\n");
    }    
}

//calcul somme ligne donnee
int calcSommeLigne (int mat[][N], int n, int ligne){
    int j;
    int somme = mat [ligne][0];
       
        for(j=1; j <= n-1; j++){
           somme += mat[ligne][j];
        }
        //printf("%d",somme);
        return somme;
}

//calcul somme col donnee
int calcSommeCol (int mat[][N], int n, int col){
    int i;
    int somme = mat [0][col];
       
        for(i=1; i <= n-1; i++){
           somme += mat[i][col];
        }
        //printf("%d",somme);
        return somme;
}

//calcul somme col donnee
void calcSommeDiag (int mat[][N], int n, int * sommeHB, int * sommeBH){
    int i;
    *sommeHB = mat [0][0];
    *sommeBH = mat [n-1][0];   
        for(i=1; i <= n-1; i++){
           *sommeHB += mat[i][i];
           *sommeBH += mat[n-1-i][i];
           
        }
        //printf("%d et %d",*sommeHB, *sommeBH);
        
}

int estMagique(int mat[][N], int n){
    int i=0;
    int estMagique=1;
    
    int sommeHB, sommeBH;
    calcSommeDiag(mat, N, &sommeHB, &sommeBH);
    
    if(sommeHB != sommeBH){
        estMagique = 1;
    }
    
    while (i < n && estMagique ==1){
        if((calcSommeLigne(mat, N,i) != calcSommeCol(mat, N,i)) || (calcSommeLigne(mat, N,i) != sommeHB)){
            estMagique = 0;
        }
        
        i++;
    }
    return estMagique;
}

int main (){
 
    int mat [N][N];
    lireMatrice(mat, N);
    afficheMat(mat, N);
    calcSommeLigne(mat, N,1);
    calcSommeCol(mat, N,1);
    
    int sommeHB, sommeBH;
    calcSommeDiag(mat, N, &sommeHB, &sommeBH);
    
    if( estMagique(mat,N) == 1){
        printf("MAGIQUE");
    }else{ 
        printf("Non");
        
    }
    return 1;  
    
}