Exercices de programmation C : Tableaux et fonctions

Tableaux unidimensionnels et multidimensionnels

Exercice 1 : Analyse de la mémoire

Cet exercice permet de comprendre comment les tableaux sont stockés en mémoire. Nous allons examiner l'espace occupé par un tableau et les adresses de chaque élément.

#include <stdio.h>
#define LIGNE 4
#define COL 2

void analyserTableau1D() {
    int valeurs[LIGNE] = {1, 9, 8, 4};          
    int i;

    printf("Taille memoire occupee: %d octets\n", sizeof(valeurs));

    for (i = 0; i < LIGNE; ++i)
        printf("%p: %d\n", &valeurs[i], valeurs[i]);

    printf("Adresse du tableau: %p\n", valeurs); 
}

void analyserTableau2D() {
    int valeurs[COL][LIGNE] = {{1, 9, 8, 4}, {2, 0, 4, 9}};
    int i, j;

    printf("Taille memoire occupee: %d octets\n", sizeof(valeurs));

    for (i = 0; i < COL; ++i)
        for (j = 0; j < LIGNE; ++j)
            printf("%p: %d\n", &valeurs[i][j], valeurs[i][j]);

    printf("\nAdresses principales:\n");
    printf("tableau: %p\n", valeurs);
    printf("premiere ligne: %p\n", valeurs[0]);
    printf("deuxieme ligne: %p\n", valeurs[1]);
}

int main() {
    printf("Analyse: tableau int unidimensionnel\n");
    analyserTableau1D();

    printf("\nAnalyse: tableau int bidimensionnel\n");
    analyserTableau2D();

    return 0;
}

Réponses aux questions :

  1. Oui, l'adresse du tableau et celle du premier élément sont identiques.
  2. Oui, l'adresse de chaque ligne diffère de 16 octets (4 éléments × 4 octets), représentant la taille mémoire de chaque ligne.

Exercice 2 : Fonctions avec tableaux unidimensionnels

Cet exercice montre comment manipuler des tableaux passés en paramètres à des fonctions. Le programme calcule la moyenne des éléments en exclunat les valeurs extrêmes.

#include <stdio.h>
#define TAILLE_MAX 100

void saisie(int tableau[], int nombre);
double calcul(int tableau[], int nombre);

int main() {
    int donnees[TAILLE_MAX];
    int nombre, i;
    double resultat;

    while(printf("Entrez n: "), scanf("%d", &nombre) != EOF) {
        saisie(donnees, nombre);
        resultat = calcul(donnees, nombre);
        printf("Resultat = %.2f\n\n", resultat);
    }

    return 0;
}

void saisie(int tableau[], int nombre) {
    int i;
    for(i = 0; i < nombre; ++i)
        scanf("%d", &tableau[i]);
}

double calcul(int tableau[], int nombre) {
    int i, maximum, minimum;
    double somme;

    maximum = minimum = tableau[0];
    somme = 0;

    for(i = 0; i < nombre; ++i) {
        somme += tableau[i];

        if(tableau[i] > maximum)
            maximum = tableau[i];
        else if(tableau[i] < minimum)
            minimum = tableau[i];
    }

    return (somme - maximum - minimum) / (nombre - 2.0);
}

Réponses :

  1. Paramètre formel : int tableau[] ; argument : donnees
  2. La fonction saisie lit n valeurs dans le tableau ; calcul calcule la moyenne en supprimant les valeurs maximale et minimale.

Exercice 3 : Fonctions avec tableaux bidimensionnels

Cet exercice illustre la传递 des tableaux 2D aux fonctions. La déclartion du paramètre nécessite le nombre de colonnes.

#include <stdio.h>
#define TAILLE_MAX 100

void affichage(int matrice[][TAILLE_MAX], int taille);
void initialisation(int matrice[][TAILLE_MAX], int taille, int valeur);

int main() {
    int matrice[TAILLE_MAX][TAILLE_MAX];
    int taille, valeur;

    while(printf("Entrez taille et valeur: "), scanf("%d%d", &taille, &valeur) != EOF) {
        initialisation(matrice, taille, valeur);
        affichage(matrice, taille);
        printf("\n");
    }

    return 0;
}

void affichage(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    for(i = 0; i < taille; ++i) {
        for(j = 0; j < taille; ++j)
            printf("%d ", matrice[i][j]);
        printf("\n");
    }
}

void initialisation(int matrice[][TAILLE_MAX], int taille, int valeur) {
    int i, j;
    for(i = 0; i < taille; ++i)
        for(j = 0; j < taille; ++j)
            matrice[i][j] = valeur;
}

Réponses :

  1. Paramètre formel : int matrice[][TAILLE_MAX] ; argument : matrice
  2. Non, le compilateur a besoin du nombre de colonnes pour calculer les adresses des éléments.
  3. affichage affiche une matrice n×n ; initialisation remplit tous les éléments avec la valeur donnée.

Exercice 4 : Fonction médiane

Complétez la fonction qui calcule la médiane d'un tableau trié.

#include <stdio.h>
#define TAILLE_MAX 100

void saisie(int donnee[], int nombre);
double mediane(int donnee[], int nombre);

int main() {
    int donnee[TAILLE_MAX];
    int nombre;
    double resultat;

    while(printf("Entrez n: "), scanf("%d", &nombre) != EOF) {
        saisie(donnee, nombre);
        resultat = mediane(donnee, nombre);
        printf("Resultat = %g\n\n", resultat);
    }

    return 0;
}

void saisie(int donnee[], int nombre) {
    int i;
    for(i = 0; i < nombre; ++i)
        scanf("%d", &donnee[i]);
}

double mediane(int donnee[], int nombre) {
    return (donnee[nombre/2 - 1] + donnee[nombre/2]) / 2.0;
}

Note : Ce code suppose que le tableau est déjà trié et que nombre est pair.

Exercice 5 : Rotation de matrice

Cet exercice demande de décaler chaque ligne d'une matrice vers la droite, en faisait recirculer la dernière colonne au début.

#include <stdio.h>
#define TAILLE_MAX 100

void saisie(int matrice[][TAILLE_MAX], int taille);
void affichage(int matrice[][TAILLE_MAX], int taille);
void deplacerDroite(int matrice[][TAILLE_MAX], int taille);

int main() {
    int matrice[TAILLE_MAX][TAILLE_MAX];
    int taille;

    printf("Entrez la taille: "); 
    scanf("%d", &taille);
    saisie(matrice, taille);

    printf("Matrice originale:\n");
    affichage(matrice, taille);

    deplacerDroite(matrice, taille);

    printf("Matrice apres transformation:\n");
    affichage(matrice, taille);
    return 0;
}

void saisie(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    for (i = 0; i < taille; ++i) {
        for (j = 0; j < taille; ++j)
            scanf("%d", &matrice[i][j]);
    }
}

void affichage(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    for (i = 0; i < taille; ++i) {
        for (j = 0; j < taille; ++j)
            printf("%4d", matrice[i][j]);
        printf("\n");
    }
}

void deplacerDroite(int matrice[][TAILLE_MAX], int taille) {
    int ligne, colonne, temp;
    for(ligne = 0; ligne < taille; ++ligne) {
        temp = matrice[ligne][taille - 1];
        for(colonne = taille - 1; colonne > 0; --colonne)
            matrice[ligne][colonne] = matrice[ligne][colonne - 1];
        matrice[ligne][0] = temp;
    }
}

Exercice 6 : Conversion de base

Ce programme convertit un nombre décimal en différentes bases (binaire, octal, hexadécimal).

#include <stdio.h>
#include <stdlib.h>
#define TAILLE_MAX 100

void convertirBase(int valeur, int base);

int main() {
    int nombre;

    while(printf("Entrez un entier decimal: "), scanf("%d", &nombre) != EOF) {
        convertirBase(nombre, 2);
        convertirBase(nombre, 8);
        convertirBase(nombre, 16);
        printf("\n");
    }
    system("pause");
    return 0;
}

void convertirBase(int valeur, int base) {
    char resultat[TAILLE_MAX];
    char chiffres[] = "0123456789ABCDEF";
    int reste;
    int i;
    int compteur = 0;

    do {
        reste = valeur % base;
        resultat[compteur++] = chiffres[reste];
        valeur = valeur / base;
    } while (valeur);

    for(i = compteur - 1; i >= 0; --i)
        printf("%c", resultat[i]);
    printf("\n");
}

Exercice 7 : Vérification de carré magique

Un carré magique est une matrice n×n où la somme de chaque ligne, chaque colonne et des deux diagonales principales est égale.

#include <stdio.h>
#define TAILLE_MAX 100

void saisieCarre(int matrice[][TAILLE_MAX], int taille);
void affichageCarre(int matrice[][TAILLE_MAX], int taille);
int verifierCarreMagique(int matrice[][TAILLE_MAX], int taille);

int main() {
    int matrice[TAILLE_MAX][TAILLE_MAX];
    int taille;

    while(printf("Entrez n: "), scanf("%d", &taille) != EOF) {
        printf("Entrez la matrice:\n");
        saisieCarre(matrice, taille);

        printf("Matrice:\n");
        affichageCarre(matrice, taille);

        if(verifierCarreMagique(matrice, taille))
            printf("C'est un carre magique\n\n");
        else
            printf("Ce n'est pas un carre magique\n\n");
    }
    return 0;
}

void saisieCarre(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    for(i = 0; i < taille; ++i)
        for(j = 0; j < taille; ++j)
            scanf("%d", &matrice[i][j]);
}

void affichageCarre(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    for(i = 0; i < taille; ++i) {
        for(j = 0; j < taille; ++j)
            printf("%4d", matrice[i][j]);
        printf("\n");
    }
}

int verifierCarreMagique(int matrice[][TAILLE_MAX], int taille) {
    int i, j;
    int sommeCible = taille * (taille * taille + 1) / 2;  
    int sommeLigne, sommeColonne, sommeDiag1 = 0, sommeDiag2 = 0;
    
    for(i = 0; i < taille; ++i) {
        sommeLigne = 0;
        sommeColonne = 0;
        for(j = 0; j < taille; ++j) {
            sommeLigne += matrice[i][j];
            sommeColonne += matrice[j][i];
        }
        if(sommeLigne != sommeCible || sommeColonne != sommeCible)
            return 0;
        
        sommeDiag1 += matrice[i][i];
        sommeDiag2 += matrice[i][taille - 1 - i];
    }
    
    if(sommeDiag1 != sommeCible || sommeDiag2 != sommeCible)
        return 0;
    
    return 1;
}

Explication du principe :

La fonction calcule d'abord la somme magique avec la formule n×(n²+1)/2. Ensuite, elle parcourt la matrice en accumulant simultanément les sommes des lignes, des colonnes et des deux diagonlaes principales. Grâce à la structure de la matrice, on peut effectuer ces calculs en une seule passent. Si toutes les sommes sont égales à la somme magique, la fonction retourne 1, sinon 0.

Étiquettes: Langage-C tableaux fonctions Matrices programmation

Publié le 16 juillet à 09h43