Looping Over Arrays

Arrays and for loops are best friends. The loop counter becomes the index:

#include <stdio.h>

int main() {
    int nums[5] = {4, 8, 15, 16, 23};
    for (int i = 0; i < 5; i++) {
        printf("nums[%d] = %d\n", i, nums[i]);
    }
    return 0;
}

Output

nums[0] = 4
nums[1] = 8
nums[2] = 15
nums[3] = 16
nums[4] = 23

Tip: Loop with i = 0 and i < size. That visits every index exactly once.

Filling an array from input

#include <stdio.h>

int main() {
    int n;
    int scores[100];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &scores[i]);
    }
    printf("You entered %d scores. The first is %d.\n", n, scores[0]);
    return 0;
}

Input (what the user types)

3
50 70 90

Output

You entered 3 scores. The first is 50.

We don't know how many numbers will come, so we make the array big enough (100) and only use the first n places.

Total and average

#include <stdio.h>

int main() {
    int prices[4] = {30, 45, 10, 25};
    int total = 0;
    for (int i = 0; i < 4; i++) {
        total += prices[i];
    }
    printf("Total: %d\n", total);
    printf("Average: %.2f\n", total / 4.0);
    return 0;
}

Output

Total: 110
Average: 27.50

Finding the biggest value

Start by assuming the first item is the biggest, then check all the others:

#include <stdio.h>

int main() {
    int temps[6] = {21, 25, 19, 30, 27, 22};
    int hottest = temps[0];
    for (int i = 1; i < 6; i++) {
        if (temps[i] > hottest) {
            hottest = temps[i];
        }
    }
    printf("Hottest: %d\n", hottest);
    return 0;
}

Output

Hottest: 30

Searching

#include <stdio.h>

int main() {
    int ids[5] = {104, 230, 315, 412, 509};
    int wanted = 315;
    int foundAt = -1;
    for (int i = 0; i < 5; i++) {
        if (ids[i] == wanted) {
            foundAt = i;
            break;
        }
    }
    printf("Found at index %d\n", foundAt);
    return 0;
}

Output

Found at index 2

Tip: Using -1 to mean "not found" is a common trick, because -1 can never be a real index.

HOME LABS COMMUNITY DASHBOARD