Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 6 of 8

Loop Idioms & Efficiency - Real Patterns

Experienced C programmers recognise a set of standard loop patterns: array traversal, string scanning (null-terminated), line counting, reversal, and binary search. These patterns appear constantly in systems code. Mastering them reduces the time you spend thinking about mechanics and lets you focus on logic.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Essential Loop Patterns in C

Essential Loop Patterns in C
#include <stdio.h>
#include <string.h>

/* ── String length without strlen (shows the null-scan pattern) */
int my_strlen(const char *s) {
    int len = 0;
    while (*s != '') {   /* loop until null terminator */
        len++;
        s++;               /* advance the pointer */
    }
    return len;
}

/* ── Reverse an array in-place ──────────────────────────── */
void reverse(int *arr, int n) {
    for (int lo = 0, hi = n - 1; lo < hi; lo++, hi--) {
        int tmp   = arr[lo];
        arr[lo]   = arr[hi];
        arr[hi]   = tmp;
    }
}

/* ── Binary search - O(log n) ───────────────────────────── */
int bsearch_int(const int *arr, int n, int target) {
    int lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;   /* avoid overflow vs (lo+hi)/2 */
        if      (arr[mid] == target) return mid;
        else if (arr[mid]  < target) lo = mid + 1;
        else                         hi = mid - 1;
    }
    return -1;   /* not found */
}

/* ── Count lines in a string ────────────────────────────── */
int count_lines(const char *s) {
    int lines = 0;
    while (*s) {
        if (*s == '
') lines++;
        s++;
    }
    return lines + 1;   /* last line may not end with 
 */
}

int main(void) {
    printf("my_strlen("hello") = %d
", my_strlen("hello"));  /* 5 */

    int arr[] = {1, 2, 3, 4, 5};
    int n = (int)(sizeof(arr) / sizeof(arr[0]));
    reverse(arr, n);
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("
");   /* 5 4 3 2 1 */

    int sorted[] = {1, 3, 5, 7, 9, 11, 13};
    int m = (int)(sizeof(sorted) / sizeof(sorted[0]));
    printf("bsearch 7: index %d
", bsearch_int(sorted, m, 7));   /* 3 */
    printf("bsearch 4: index %d
", bsearch_int(sorted, m, 4));   /* -1 */

    printf("lines: %d
", count_lines("line1
line2
line3"));  /* 3 */

    return 0;
}

Common Mistakes

  • `(lo + hi) / 2` can overflow when `lo + hi > INT_MAX` - use `lo + (hi - lo) / 2` instead. This is a classic interview and production bug in binary search.
  • Walking off the end of a string - the null-scanning pattern `while (*s)` is safe because it stops at the null terminator. But if the string is not null-terminated (a common bug from `strncpy` misuse), this loops into undefined behaviour.
  • Comparing `int` loop counter against `size_t` length - `for (int i = 0; i < strlen(s); i++)` compares `int` (possibly negative) with `size_t` (unsigned). If i is somehow negative, you'll get -Wsign-compare warnings and potential infinite loops. Use `size_t i` or cast carefully.

Tip

Tip

Practice Loop Idioms Efficiency Real Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Idiomatic C loops leverage sequential memory access for maximum CPU cache utilization

Practice Task

Note

Practice Task - (1) Write a working example of Loop Idioms Efficiency Real Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Loop Idioms Efficiency Real Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Experienced C programmers recognise a set of standard loop patterns: array traversal, string scanning (null-terminated), line counting, reversal, and binary search.
  • `(lo + hi) / 2` can overflow when `lo + hi > INT_MAX` - use `lo + (hi - lo) / 2` instead. This is a classic interview and production bug in binary search.
  • Walking off the end of a string - the null-scanning pattern `while (*s)` is safe because it stops at the null terminator. But if the string is not null-terminated (a common bug from `strncpy` misuse), this loops into undefined behaviour.
  • Comparing `int` loop counter against `size_t` length - `for (int i = 0; i < strlen(s); i++)` compares `int` (possibly negative) with `size_t` (unsigned). If i is somehow negative, you'll get -Wsign-compare warnings and potential infinite loops. Use `size_t i` or cast carefully.

Topics in This Module

0/8 done