📘 Module 8: Arrays & Strings – Contiguous Memory

Goal: Store multiple elements of the same type in a block of memory. Strings are just char arrays with a null terminator.

🔹 One‑dimensional array

int numbers[5] = {10, 20, 30, 40, 50};
printf("%d\n", numbers[2]);  // 30
numbers[3] = 99;

🔹 Strings (null‑terminated char arrays)

char name[] = "Feroniba";
printf("%c\n", name[0]);   // 'F'
printf("%s\n", name);      // whole string

📖 Example: Print all elements of an array

#include <stdio.h>
int main() {
    int arr[] = {2,4,6,8};
    int len = sizeof(arr)/sizeof(arr[0]);
    for (int i = 0; i < len; i++)
        printf("%d ", arr[i]);
    return 0;
}

✏️ Exercise 1 (easy)

Declare an array of 5 floats, initialise it with your favourite numbers, and print each element using a loop.

Solution
#include <stdio.h>
int main() {
    float vals[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
    for (int i = 0; i < 5; i++)
        printf("%.1f ", vals[i]);
    return 0;
}

✏️ Exercise 2 (medium – string length)

Write a function int stringLength(char str[]) that returns the length of a string without using strlen (loop until '\0').

Solution
int stringLength(char str[]) {
    int len = 0;
    while (str[len] != '\0') len++;
    return len;
}

✏️ Exercise 3 (array reversal)

Write a program that reverses an integer array in‑place (without using a second array). Use two pointers or indices.

Solution
#include <stdio.h>
int main() {
    int arr[] = {1,2,3,4,5};
    int n = 5;
    for (int i = 0; i < n/2; i++) {
        int temp = arr[i];
        arr[i] = arr[n-1-i];
        arr[n-1-i] = temp;
    }
    // print reversed
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    return 0;
}
← Back to Module 7 - Pointers Again to Course Start - Content →