GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

📦 Lesson 7: Functions (Modular Code)

⏱️ Estimated time: 30 minutes | Difficulty: Intermediate

Reusability

Functions are independent blocks of code that perform specific tasks. They help make your programs organized, readable, and reusable.

Arrays

An array stores multiple values of the same type in contiguous memory.

#include <stdio.h>

int main() {
    // Declare and initialize
    int numbers[5] = {10, 20, 30, 40, 50};

    // Access elements (0-indexed!)
    printf("First: %d\n", numbers[0]);   // 10
    printf("Last: %d\n", numbers[4]);    // 50

    // Modify an element
    numbers[2] = 99;

    // Loop through array
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    // Output: 10 20 99 40 50

    return 0;
}

2D Arrays (Matrices)

int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

printf("%d\n", matrix[1][2]);  // 6 (row 1, col 2)

// Print entire matrix
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        printf("%d ", matrix[i][j]);
    }
    printf("\n");
}

Strings in C

In C, strings are arrays of characters ending with a null terminator '\0'.

#include <stdio.h>
#include <string.h>  // String functions

int main() {
    char name[50] = "Hello";

    // String functions
    printf("Length: %lu\n", strlen(name));     // 5
    
    char copy[50];
    strcpy(copy, name);       // Copy string
    
    strcat(name, " World");   // Concatenate
    printf("%s\n", name);     // Hello World
    
    // Compare strings
    if (strcmp(name, "Hello World") == 0) {
        printf("Strings are equal!\n");
    }
    
    return 0;
}

Common String Functions

Function Purpose
strlen(s) Get string length
strcpy(dest, src) Copy string
strcat(dest, src) Concatenate strings
strcmp(s1, s2) Compare strings (0 = equal)
strchr(s, c) Find character in string

✅ Quick Quiz

❓ What is the index of the first element in a C array?

❓ What terminates a C string?

❓ Which function gets the length of a string?

← Previous Next: Pointers & Memory →