CodeBlanks Logo Icon CodeBlanks

Loop optimization

Learn loop optimization and unrolling.

Loop optimization

Loop unrolling processes multiple elements per iteration to reduce the loop count. This reduces loop overhead (condition check, increment) and increases instruction-level parallelism.

A 4-way unroll example: for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }. Each iteration handles 4 elements; the loop count is divided by 4. A second loop handles the remaining elements. Modern compilers do this automatically; writing it by hand at advanced level gives further gains.

Remaining elements

4-way unroll misses some elements when the array size is not a multiple of 4. So you add a remainder loop for (; i < n; i++) sum += a[i];.

Example: the 8-element array {1,2,3,4,5,6,7,8} is handled in two unrolled iterations (i=0, i=4) with no remainder; the sum is 36. With 10 elements, 8 would go through the unroll and 2 through the remainder. This pattern is required for both performance and correctness.

Practice 4-way unrolled sum

Write int sum_unrolled(int *a, int n): int sum = 0; int i;, loop for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }, remainder for (; i < n; i++) sum += a[i];, return sum;. In main declare int a[] = {1,2,3,4,5,6,7,8}; and print printf("toplam: %d\n", sum_unrolled(a, 8));.

Starter code

main.c
#include <stdio.h>

// Write sum_unrolled: 4-way unroll + remainder loop
// main: declare 8-element array, call sum_unrolled and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int sum_unrolled(int *a, int n) {
    int sum = 0;
    int i;
    for (i = 0; i + 3 < n; i += 4) {
        sum += a[i] + a[i+1] + a[i+2] + a[i+3];
    }
    for (; i < n; i++) sum += a[i];
    return sum;
}

int main(void) {
    int a[] = {1,2,3,4,5,6,7,8};
    printf("toplam: %d\n", sum_unrolled(a, 8));
    return 0;
}

Expected output

toplam: 36

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 4-way unroll step

Question
for (i = 0; i + 3 < n; i += ____) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }
Answer
for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }

Explanation: 4-way unroll uses i += 4 to divide the loop by 4.

2 Match loop concepts

Term Meaning
unroll Multiple elements
i += 4 4-way step
remainder loop Leftover elements
condition check Loop overhead

3 What does loop unrolling reduce?

  • Memory usage
  • File size
  • Loop overhead Correct answer
  • Line count

Explanation: Unrolling reduces loop overhead (condition, increment).

All lessons in Advanced