Back-end · formation gratuite

C Language Training

Learn the C language, the foundation of many modern programming languages

  • Intermédiaire
  • 12 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to C Language

The C language is a low-level procedural programming language, created by Dennis Ritchie at Bell Labs in 1972. C is the foundation of many modern languages (C++, Java, C#, Python, etc.) and remains widely used for systems programming, embedded systems, and applications requiring high performance.

⚙️ What is the C language?

The C language is a compiled and procedural programming language. C is a low-level language that provides direct control over memory and system resources. It is a powerful language but requires a deep understanding of memory management and pointers.

💡 Why is the C language so important?

  1. Foundation of modern languages - C is the basis of many languages (C++, Java, C#, Python, JavaScript). Understanding C helps better master these languages
  2. Maximum performance - C offers direct control over memory and system resources, enabling very fast applications
  3. Systems programming - Used to develop operating systems (Linux, Windows), drivers, compilers
  4. Embedded systems - Ideal for microcontroller programming, IoT, real-time systems
  5. Standard and portable - C code can be compiled on almost all platforms (Windows, Linux, macOS, embedded)
  6. Total control - Manual memory and pointer management provides precise control over performance

🚀 Why learn the C language?

The C language is essential for understanding the foundations of programming:

  • ✅ Understand computing - C teaches you how computers, memory, and pointers really work
  • ✅ Performance - Applications requiring maximum performance (video games, real-time systems, embedded)
  • ✅ Systems programming - Development of operating systems, drivers, compilers, system tools
  • ✅ Solid foundation - Understanding C facilitates learning C++, Java, and other derived languages
  • ✅ Industry - Widely used in embedded systems, automotive, aerospace, critical systems
  • ✅ Precise control - Manual memory management allows optimizing every byte
  • ✅ ANSI Standard - Standardized language, portable across all platforms

📋 Prerequisites for learning C

To learn C effectively, it is recommended to have:

  • ✅ Basic computing - Know how to use a computer, create and edit files
  • ✅ Programming logic - Understanding basic concepts (variables, conditions, loops) is very useful
  • ✅ Patience - C requires more attention to detail than high-level languages

💡 Important note: To compile C code, you need a compiler like GCC (GNU Compiler Collection) which is available for free. On Linux, GCC is often preinstalled. On Windows, you can install MinGW or use Visual Studio. On macOS, install Xcode Command Line Tools. You can also use IDEs like Code::Blocks, Dev-C++, or Visual Studio Code with the C/C++ extension.

🎯 C Language Use Cases

The C language is used in many critical fields:

  • Operating systems - Linux, Windows (partially), macOS use C for their kernels
  • Systems programming - Drivers, compilers, interpreters, system tools
  • Embedded systems - Microcontrollers, IoT, real-time systems, automotive, aerospace
  • Video games - Game engines requiring maximum performance
  • Networks - Network protocols, high-performance servers
  • Scientific computing - Applications requiring intensive calculations
  • Databases - Database engines (MySQL, PostgreSQL use C)
  • Web servers - High-performance web servers (nginx, Apache)

📝 Basic Syntax

The C language is a compiled procedural programming language. C uses braces {} to define code blocks and requires a semicolon ; at the end of each statement.

// Premier programme C
#include 

int main() {
    printf("Bonjour, monde !\n");
    return 0;
}

// Variables
int age = 25;
char nom[] = "NiangProgrammeur";

// Affichage formaté
printf("Je m'appelle %s et j'ai %d ans\n", nom, age);

// Opérations simples
int resultat = 10 + 5;
printf("10 + 5 = %d\n", resultat);
}

💡 Important points about C syntax:

  • C uses braces {} to define code blocks
  • Comments use // for a line or /* */ for multiple lines
  • Semicolon required ; at the end of each statement
  • Strings use double quotes " and are character arrays
  • Functions must be declared before use (or via headers)
  • The entry point is the main() function which returns an int

🔍 Detailed syntax example

Here is a complete example showing several aspects of C syntax:

#include 

// Définition d'une fonction
int calculer_moyenne(int nombres[], int taille) {
    if (taille == 0) {
        return 0;
    }
    int somme = 0;
    for (int i = 0; i < taille; i++) {
        somme += nombres[i];
    }
    return somme / taille;
}

// Fonction principale
int main() {
    int notes[] = {15, 18, 12, 20, 16};
    int moyenne = calculer_moyenne(notes, 5);
    printf("La moyenne est : %d\n", moyenne);
    return 0;
}

🔤 Variables

In C, variables must be declared with a type before use. C is a statically typed language, meaning a variable's type is determined at compile time and cannot change.

#include 

int main() {
    // Déclaration de variables
    int age = 30;                    // Entier
    float prix = 19.99f;             // Nombre décimal (simple précision)
    double decimal = 3.14159;         // Nombre décimal (double précision)
    char lettre = 'A';                // Caractère unique
    char nom[] = "C";                // Chaîne de caractères (tableau)
    
    // Affichage avec printf
    printf("Age: %d\n", age);
    printf("Prix: %.2f\n", prix);
    printf("Decimal: %lf\n", decimal);
    printf("Lettre: %c\n", lettre);
    printf("Nom: %s\n", nom);
    
    // Déclaration puis assignation
    int nombre;
    nombre = 10;
    printf("Nombre: %d\n", nombre);
    
    // Constantes avec #define
    #define PI 3.14159
    #define MAX_SIZE 100
    
    // Constantes avec const
    const int TAILLE = 50;
    const char* MESSAGE = "Bonjour";
    
    // Noms de variables valides
    int age_utilisateur = 25;
    char nom_utilisateur[] = "Bassirou";
    float _prive = 3.14;  // Possible mais non recommandé
    
    return 0;
}

📌 Rules for variable names:

  • Must start with a letter or underscore _
  • Can contain letters, digits, and underscores
  • Cannot contain spaces or special characters
  • Are case-sensitive (age ≠ Age)
  • Cannot be C keywords (if, for, int, etc.)
  • Convention: use snake_case or camelCase for variables

📊 Data Types

C has several basic (primitive) data types. Here are the main types available in C:

#include 
#include   // Pour le type bool

int main() {
    // Types entiers
    char c = 'A';              // 1 octet (-128 à 127 ou 0 à 255)
    short s = 100;            // 2 octets (-32768 à 32767)
    int i = 1000;             // 4 octets (généralement)
    long l = 100000L;         // 4 ou 8 octets
    long long ll = 1000000LL; // 8 octets
    
    // Types entiers non signés
    unsigned char uc = 200;
    unsigned int ui = 5000;
    unsigned long ul = 100000UL;
    
    // Types décimaux
    float f = 3.14f;          // 4 octets (simple précision)
    double d = 3.14159;       // 8 octets (double précision)
    long double ld = 3.141592653589793L;  // 10 ou 16 octets
    
    // Type booléen (C99+)
    bool est_vrai = true;
    bool est_faux = false;
    
    // Chaînes de caractères (tableaux de char)
    char chaine[] = "Hello";  // Tableau de caractères
    char* pointeur = "World"; // Pointeur vers une chaîne
    
    // Affichage avec printf
    printf("char: %c\n", c);
    printf("int: %d\n", i);
    printf("float: %.2f\n", f);
    printf("double: %lf\n", d);
    printf("bool: %d\n", est_vrai);
    printf("chaine: %s\n", chaine);
    
    // Taille des types (en octets)
    printf("Taille de int: %zu octets\n", sizeof(int));
    printf("Taille de float: %zu octets\n", sizeof(float));
    printf("Taille de double: %zu octets\n", sizeof(double));
    
    return 0;
}

📚 C Data Types:

  • char - Character (1 byte)
  • int - Integer (generally 4 bytes)
  • float - Single precision decimal number (4 bytes)
  • double - Double precision decimal number (8 bytes)
  • void - Empty type (for functions without return)
  • bool - Boolean (C99+, requires stdbool.h)
  • short, long, long long - Integer variants
  • unsigned - Modifier for unsigned integers

🔢 Operators

C supports arithmetic, comparison, logical, assignment, and pointer operators:

#include 
#include   // Pour pow()

int main() {
    int a = 10, b = 3;
    
    // Opérateurs arithmétiques
    printf("%d + %d = %d\n", a, b, a + b);      // Addition: 13
    printf("%d - %d = %d\n", a, b, a - b);      // Soustraction: 7
    printf("%d * %d = %d\n", a, b, a * b);      // Multiplication: 30
    printf("%d / %d = %d\n", a, b, a / b);      // Division entière: 3
    printf("%d %% %d = %d\n", a, b, a % b);      // Modulo (reste): 1
    
    // Division avec float
    float resultat = (float)a / b;
    printf("%d / %d = %.2f\n", a, b, resultat); // Division: 3.33
    
    // Puissance (nécessite math.h)
    double puissance = pow(a, b);
    printf("%d^%d = %.0f\n", a, b, puissance);  // Puissance: 1000
    
    // Opérateurs de comparaison
    printf("%d > %d = %d\n", a, b, a > b);      // 1 (true)
    printf("%d < %d = %d\n", a, b, a < b);      // 0 (false)
    printf("%d >= %d = %d\n", a, b, a >= b);    // 1 (true)
    printf("%d <= %d = %d\n", a, b, a <= b);    // 0 (false)
    printf("%d == %d = %d\n", a, b, a == b);    // 0 (false)
    printf("%d != %d = %d\n", a, b, a != b);    // 1 (true)
    
    // Opérateurs logiques
    int x = 1, y = 0;  // 1 = true, 0 = false
    printf("%d && %d = %d\n", x, y, x && y);    // ET logique: 0
    printf("%d || %d = %d\n", x, y, x || y);    // OU logique: 1
    printf("!%d = %d\n", x, !x);                // NON logique: 0
    
    // Opérateurs d'assignation
    int c = 5;
    c += 3;  // Équivalent à c = c + 3 (c devient 8)
    c -= 2;  // Équivalent à c = c - 2 (c devient 6)
    c *= 2;  // Équivalent à c = c * 2 (c devient 12)
    c /= 3;  // Équivalent à c = c / 3 (c devient 4)
    c %= 3;  // Équivalent à c = c % 3 (c devient 1)
    
    // Opérateurs d'incrémentation/décrémentation
    int i = 5;
    printf("i = %d\n", i++);  // Post-incrémentation: affiche 5, puis i = 6
    printf("i = %d\n", ++i);  // Pré-incrémentation: i = 7, puis affiche 7
    
    return 0;
}

🔀 Conditional Structures

The C language uses if, else if, and else for conditions. Code blocks are delimited by braces {}.

# Structure if simple
age = 20

if age >= 18:
    print("Vous êtes majeur")
else:
    print("Vous êtes mineur")

# Structure if/elif/else
age = 15

if age >= 18:
    print("Vous êtes majeur")
    print("Vous pouvez voter")
elif age >= 13:
    print("Vous êtes adolescent")
elif age >= 6:
    print("Vous êtes enfant")
else:
    print("Vous êtes un bébé")

# Conditions multiples
note = 85

if note >= 90:
    mention = "Excellent"
elif note >= 80:
    mention = "Très bien"
elif note >= 70:
    mention = "Bien"
elif note >= 60:
    mention = "Assez bien"
else:
    mention = "Insuffisant"

print(f"Votre mention : {mention}")

# Opérateur ternaire (expression conditionnelle)
age = 20
statut = "Majeur" if age >= 18 else "Mineur"
print(statut)

# Conditions avec and/or
age = 25
permis = True

if age >= 18 and permis:
    print("Vous pouvez conduire")
else:
    print("Vous ne pouvez pas conduire")

🔄 Loops

The C language offers three types of loops: for (to iterate a defined number of times), while (to repeat while a condition is true), and do-while (executes at least once):

# Boucle for avec range()
for i in range(5):
    print(i)  # Affiche 0, 1, 2, 3, 4

# range() avec début et fin
for i in range(1, 6):
    print(i)  # Affiche 1, 2, 3, 4, 5

# range() avec pas
for i in range(0, 10, 2):
    print(i)  # Affiche 0, 2, 4, 6, 8

# Boucle for avec liste
fruits = ["pomme", "banane", "orange"]
for fruit in fruits:
    print(f"J'aime les {fruit}")

# Boucle for avec index (enumerate)
fruits = ["pomme", "banane", "orange"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Boucle while
compteur = 0
while compteur < 5:
    print(compteur)
    compteur += 1

# Boucle while avec break
compteur = 0
while True:
    print(compteur)
    compteur += 1
    if compteur >= 5:
        break  # Sortir de la boucle

# continue (passer à l'itération suivante)
for i in range(10):
    if i % 2 == 0:  # Si i est pair
        continue    # Passer au suivant
    print(i)       # Affiche seulement les impairs: 1, 3, 5, 7, 9

# Boucle for avec else
for i in range(5):
    print(i)
else:
    print("Boucle terminée")  # Exécuté si la boucle se termine normalement

⚙️ Functions

Functions allow code reuse. In C, we define a function with its return type, name, and parameters. Functions can take parameters and return values with return.

# Fonction simple (sans paramètres)
def dire_bonjour():
    print("Bonjour !")

dire_bonjour()  # Appel de la fonction

# Fonction avec paramètres
def saluer(nom):
    return f"Bonjour, {nom} !"

message = saluer("Python")
print(message)  # "Bonjour, Python !"

# Fonction avec plusieurs paramètres
def additionner(a, b):
    return a + b

resultat = additionner(5, 3)
print(resultat)  # 8

# Fonction avec paramètres par défaut
def saluer_personne(nom, message="Bonjour"):
    return f"{message}, {nom} !"

print(saluer_personne("Bassirou"))              # "Bonjour, Bassirou !"
print(saluer_personne("Bassirou", "Salut"))     # "Salut, Bassirou !"

# Fonction avec arguments nommés
def creer_personne(nom, age, ville="Dakar"):
    return f"{nom}, {age} ans, habite à {ville}"

print(creer_personne("Bassirou", 25))
print(creer_personne(age=25, nom="Bassirou", ville="Thiès"))

# Fonction avec *args (arguments variables)
def additionner_nombres(*args):
    return sum(args)

print(additionner_nombres(1, 2, 3, 4, 5))  # 15

# Fonction avec **kwargs (arguments nommés variables)
def afficher_info(**kwargs):
    for cle, valeur in kwargs.items():
        print(f"{cle}: {valeur}")

afficher_info(nom="Bassirou", age=25, ville="Dakar")

# Fonction lambda (fonction anonyme)
carre = lambda x: x ** 2
print(carre(5))  # 25

# Utilisation de lambda avec map()
nombres = [1, 2, 3, 4, 5]
carres = list(map(lambda x: x ** 2, nombres))
print(carres)  # [1, 4, 9, 16, 25]

📍 Pointers

Pointers are one of the most powerful and important features of the C language. A pointer is a variable that stores the memory address of another variable.

#include 

int main() {
    int nombre = 42;
    int* ptr = &nombre;  // ptr pointe vers nombre
    
    printf("Valeur de nombre: %d\n", nombre);      // 42
    printf("Adresse de nombre: %p\n", &nombre);    // Adresse mémoire
    printf("Valeur de ptr: %p\n", ptr);            // Même adresse
    printf("Valeur pointée par ptr: %d\n", *ptr);  // 42 (déréférencement)
    
    // Modifier via le pointeur
    *ptr = 100;
    printf("Nouvelle valeur de nombre: %d\n", nombre);  // 100
    
    // Pointeur NULL
    int* ptr_null = NULL;
    if (ptr_null == NULL) {
        printf("Pointeur NULL\n");
    }
    
    // Pointeurs et tableaux
    int tableau[] = {1, 2, 3, 4, 5};
    int* ptr_tableau = tableau;  // tableau est déjà un pointeur
    
    printf("Premier élément: %d\n", *ptr_tableau);        // 1
    printf("Deuxième élément: %d\n", *(ptr_tableau + 1)); // 2
    printf("Troisième élément: %d\n", ptr_tableau[2]);    // 3
    
    return 0;
}

📋 Arrays

Arrays in C are collections of elements of the same type stored contiguously in memory. The size of an array is fixed and must be known at compile time.

#include 

int main() {
    // Déclaration et initialisation
    int nombres[5] = {1, 2, 3, 4, 5};
    int tableau[10];  // Tableau non initialisé
    
    // Accès aux éléments (index commence à 0)
    printf("Premier élément: %d\n", nombres[0]);  // 1
    printf("Dernier élément: %d\n", nombres[4]);  // 5
    
    // Modification
    nombres[1] = 10;
    printf("nombres[1] = %d\n", nombres[1]);  // 10
    
    // Parcourir un tableau
    for (int i = 0; i < 5; i++) {
        printf("nombres[%d] = %d\n", i, nombres[i]);
    }
    
    // Tableaux multidimensionnels
    int matrice[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrice[i][j]);
        }
        printf("\n");
    }
    
    // Tableaux de caractères (chaînes)
    char chaine[] = "Bonjour";
    char nom[20] = "C";
    
    printf("Chaine: %s\n", chaine);
    printf("Nom: %s\n", nom);
    
    return 0;
}

🏗️ Structures (struct)

Structures allow grouping multiple variables of different types under a single name. This is the equivalent of "objects" in other languages, but without methods.

#include 
#include 

// Définition d'une structure
struct Personne {
    char nom[50];
    int age;
    float taille;
};

int main() {
    // Création d'une variable de type Personne
    struct Personne p1;
    strcpy(p1.nom, "Bassirou");
    p1.age = 25;
    p1.taille = 1.75;
    
    printf("Nom: %s\n", p1.nom);
    printf("Age: %d\n", p1.age);
    printf("Taille: %.2f\n", p1.taille);
    
    // Initialisation lors de la déclaration
    struct Personne p2 = {"Aminata", 30, 1.65};
    printf("\nNom: %s, Age: %d\n", p2.nom, p2.age);
    
    // Tableau de structures
    struct Personne personnes[3] = {
        {"Bassirou", 25, 1.75},
        {"Aminata", 30, 1.65},
        {"Ibrahima", 28, 1.80}
    };
    
    for (int i = 0; i < 3; i++) {
        printf("%s a %d ans\n", personnes[i].nom, personnes[i].age);
    }
    
    // Pointeurs vers structures
    struct Personne* ptr = &p1;
    printf("\nNom via pointeur: %s\n", ptr->nom);  // Opérateur ->
    printf("Age via pointeur: %d\n", (*ptr).age);  // Ou (*ptr).age
    
    return 0;
}

💾 Memory Management

In C, you must manually manage memory. The functions malloc(), calloc(), realloc(), and free() allow allocating and freeing memory dynamically.

#include 
#include   // Pour malloc, calloc, realloc, free

int main() {
    // Allocation dynamique avec malloc
    int* ptr = (int*)malloc(5 * sizeof(int));  // Tableau de 5 entiers
    
    if (ptr == NULL) {
        printf("Erreur d'allocation mémoire\n");
        return 1;
    }
    
    // Utilisation de la mémoire allouée
    for (int i = 0; i < 5; i++) {
        ptr[i] = i * 10;
    }
    
    for (int i = 0; i < 5; i++) {
        printf("ptr[%d] = %d\n", i, ptr[i]);
    }
    
    // Libération de la mémoire
    free(ptr);
    ptr = NULL;  // Bonne pratique : mettre le pointeur à NULL
    
    // Allocation avec calloc (initialise à zéro)
    int* ptr2 = (int*)calloc(5, sizeof(int));
    printf("\nTableau initialisé à zéro:\n");
    for (int i = 0; i < 5; i++) {
        printf("ptr2[%d] = %d\n", i, ptr2[i]);
    }
    
    // Réallocation avec realloc
    ptr2 = (int*)realloc(ptr2, 10 * sizeof(int));  // Agrandir à 10 éléments
    printf("\nAprès réallocation:\n");
    for (int i = 5; i < 10; i++) {
        ptr2[i] = i * 10;
    }
    
    for (int i = 0; i < 10; i++) {
        printf("ptr2[%d] = %d\n", i, ptr2[i]);
    }
    
    free(ptr2);
    
    // Allocation pour une chaîne de caractères
    char* chaine = (char*)malloc(50 * sizeof(char));
    if (chaine != NULL) {
        strcpy(chaine, "Bonjour C !");
        printf("\nChaine: %s\n", chaine);
        free(chaine);
    }
    
    return 0;
}

💡 Note importante : En C, vous devez toujours libérer la mémoire allouée avec free() pour éviter les fuites mémoire. N'oubliez jamais de vérifier si l'allocation a réussi (pointeur != NULL) avant d'utiliser la mémoire !

📁 Manipulation de fichiers

En C, la manipulation de fichiers se fait avec les fonctions de la bibliothèque standard : fopen(), fclose(), fprintf(), fscanf(), fread(), fwrite(), etc.

#include 

int main() {
    FILE* fichier;
    
    // Écrire dans un fichier (mode "w" = write)
    fichier = fopen("fichier.txt", "w");
    if (fichier == NULL) {
        printf("Erreur lors de l'ouverture du fichier\n");
        return 1;
    }
    
    fprintf(fichier, "Bonjour C !\n");
    fprintf(fichier, "Ceci est la deuxième ligne\n");
    fclose(fichier);
    
    // Lire un fichier (mode "r" = read)
    fichier = fopen("fichier.txt", "r");
    if (fichier == NULL) {
        printf("Erreur lors de l'ouverture du fichier\n");
        return 1;
    }
    
    char ligne[100];
    while (fgets(ligne, sizeof(ligne), fichier) != NULL) {
        printf("%s", ligne);
    }
    fclose(fichier);
    
    // Ajouter à un fichier (mode "a" = append)
    fichier = fopen("fichier.txt", "a");
    if (fichier != NULL) {
        fprintf(fichier, "Nouvelle ligne ajoutée\n");
        fclose(fichier);
    }
    
    // Modes de fichier
    // "r"  - Lecture (le fichier doit exister)
    // "w"  - Écriture (crée ou écrase le fichier)
    // "a"  - Ajout (ajoute à la fin, crée si n'existe pas)
    // "r+" - Lecture et écriture
    // "w+" - Lecture et écriture (crée ou écrase)
    // "a+" - Lecture et ajout
    
    return 0;
}

💡 Best practice: Always close files with fclose() after use to free resources. Always check that fopen() returns a non-NULL pointer before using the file. This avoids resource leaks and access errors!

🎓 Next Steps

Congratulations! You now have a solid foundation in the C language.

✅ What you learned:

  • C syntax and variables
  • Data types (int, float, double, char, void)
  • Operators (arithmetic, comparison, logical, pointers)
  • Conditional structures (if, else if, else, switch)
  • Loops (for, while, do-while)
  • Functions (definition, parameters, return, prototypes)
  • Pointers and references
  • Arrays and character strings
  • Structures (struct) and unions
  • Memory management (malloc, calloc, realloc, free)
  • File manipulation (fopen, fclose, fprintf, fscanf, fread, fwrite)

🚀 To go further:

  • C++ - Object-oriented language based on C
  • Systems programming - Development of drivers, system tools
  • C Libraries - Using external libraries (GTK, SDL, etc.)
  • Networks - Network programming with sockets
  • Advanced algorithms - Complex data structures, optimized algorithms
  • Embedded systems - Microcontroller programming, IoT
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?