C: Practice: Arrays and Functions

🗓 Last updated: 2026-11-30👤 Written by: Ivy✓ Reviewed by: Alex🏷 Category: C Tutorial

No matter how many techniques you learn, they are just theory until you step into the ring. This chapter integrates arrays, functions, and pointers through four hands-on projects to test your real skills.

Reference entries in this section: qsort

1. Project 1: Bubble Sort

Bubble sort is the most basic sorting algorithm. The idea is to repeatedly traverse the array, comparing adjacent elements and swapping them if they are in the wrong order, until no swaps occur. Each pass "bubbles" the current largest value to the end.

(1) Algorithm Steps

  1. Start from the first element and compare each pair of adjacent elements
  2. If the left element is greater than the right, swap them
  3. After one pass, the largest value is in its correct position
  4. Repeat for the remaining portion until fully sorted

(2) Implementation

C
// Preprocessor directive
#include <stdio.h>

// Function definition
void bubble_sort(int *arr, int len) {
    // Variable declaration
    int i, j;
    // Variable declaration
    int swapped;

    // For loop
    for (i = 0; i < len - 1; i++) {
        swapped = 0;
        // For loop
        for (j = 0; j < len - 1 - i; j++) {
            // Conditional check
            if (arr[j] > arr[j + 1]) {
                // Variable declaration
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
            }
        }
        // Conditional check
        if (!swapped) break;
    }
}

// Function definition
void print_array(const int *arr, int len) {
    // Variable declaration
    int i;
    // For loop
    for (i = 0; i < len; i++) {
        // I/O operation
        printf("%d ", arr[i]);
    }
    // I/O operation
    printf("\n");
}

// Function definition
int main(void) {
    int data[] = {64, 34, 25, 12, 22, 11, 90};
    // Variable declaration
    int len = sizeof(data) / sizeof(data[0]);

    // I/O operation
    printf("Before: ");
    print_array(data, len);

    bubble_sort(data, len);

    // I/O operation
    printf("After:  ");
    print_array(data, len);

    // Return result
    return 0;
}
TEXT
Before: 64 34 25 12 22 11 90
After:  11 12 22 25 34 64 90

The swapped flag optimization: if no swaps occur during a pass, the array is already sorted and the algorithm terminates early. In the best case (already sorted), the time complexity drops to O(n).

💡 Tip: Bubble sort has average and worst-case time complexity of O(n^2), suitable only for small datasets or teaching. Use qsort in real projects.

▶ Example

Sort scores in descending order using bubble sort:

▶ Try it Yourself
TEXT
Ranking: 95 92 88 85 78

For descending order, simply change the comparison from > to <.


Binary search efficiently locates a target value in a sorted array by halving the search range each step.

(1) Algorithm Steps

  1. Set the search range to [low, high]
  2. Calculate the middle position: mid = (low + high) / 2
  3. If arr[mid] equals the target, it is found
  4. If arr[mid] is less than the target, search the right half
  5. If arr[mid] is greater than the target, search the left half
  6. If the range shrinks to empty without finding, the target does not exist

(2) Implementation

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int binary_search(const int *arr, int len, int target) {
    // Variable declaration
    int low = 0;
    // Variable declaration
    int high = len - 1;

    // While loop
    while (low <= high) {
        // Variable declaration
        int mid = low + (high - low) / 2;

        // Conditional check
        if (arr[mid] == target) {
            // Return result
            return mid;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    // Return result
    return -1;
}

// Function definition
int main(void) {
    int data[] = {2, 5, 8, 12, 16, 23, 38, 45, 56, 78};
    // Variable declaration
    int len = sizeof(data) / sizeof(data[0]);
    int targets[] = {23, 7, 78, 1};
    // Variable declaration
    int num = sizeof(targets) / sizeof(targets[0]);
    // Variable declaration
    int i;

    // For loop
    for (i = 0; i < num; i++) {
        // Variable declaration
        int pos = binary_search(data, len, targets[i]);
        // Conditional check
        if (pos >= 0) {
            // I/O operation
            printf("%d found at index %d\n", targets[i], pos);
        } else {
            // I/O operation
            printf("%d not found\n", targets[i]);
        }
    }
    // Return result
    return 0;
}
TEXT
23 found at index 5
7 not found
78 found at index 9
1 not found
💡 Tip: Use low + (high - low) / 2 instead of (low + high) / 2 to avoid integer overflow. This is a classic binary search detail.

Time complexity is O(log n); 1 billion elements require at most 30 comparisons.

▶ Example

Find the position of the first element greater than or equal to the target (lower bound search):

▶ Try it Yourself
TEXT
First >= 7 at index 4, value=7

Lower bound search is extremely common in competitive programming and the STL.


3. Project 3: String Reversal

Swap the front and back characters of a string, e.g., "hello" becomes "olleh". Use the two-pointer technique for in-place operation, no extra array needed.

(1) Implementation

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <string.h>

// Function definition
void str_reverse(char *s) {
    // Variable declaration
    char *left = s;
    // Variable declaration
    char *right = s + strlen(s) - 1;

    // While loop
    while (left < right) {
        // Variable declaration
        char temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }
}

// Function definition
int main(void) {
    char s1[] = "Hello World";
    char s2[] = "ABCDE";
    char s3[] = "racecar";

    str_reverse(s1);
    str_reverse(s2);
    str_reverse(s3);

    // I/O operation
    printf("%s\n", s1);
    // I/O operation
    printf("%s\n", s2);
    // I/O operation
    printf("%s\n", s3);

    // Return result
    return 0;
}
TEXT
dlroW olleH
EDCBA
racecar

Note: you must use a character array (modifiable), not a pointer to a string literal.

▶ Example

Check whether a string is a palindrome (skipping non-alphanumeric characters, ignoring case):

▶ Try it Yourself
TEXT
1
0
1

4. Project 4: Character Frequency Analysis

Count how many times each character appears in a string -- a fundamental text analysis operation.

(1) Implementation

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <string.h>

// Function definition
void char_freq(const char *s, int *freq, int size) {
    // Variable declaration
    int i;
    // For loop
    for (i = 0; i < size; i++) freq[i] = 0;
    // While loop
    while (*s != '\0') {
        unsigned char ch = (unsigned char)*s;
        // Conditional check
        if (ch < (unsigned)size) freq[ch]++;
        s++;
    }
}

// Function definition
int main(void) {
    char text[] = "Hello World!";
    int freq[256] = {0};
    // Variable declaration
    int i;

    char_freq(text, freq, 256);

    // For loop
    for (i = 32; i < 127; i++) {
        // Conditional check
        if (freq[i] > 0) printf("'%c': %d  ", i, freq[i]);
    }
    // I/O operation
    printf("\n");
    // Return result
    return 0;
}
TEXT
' ': 1  '!': 1  'H': 1  'W': 1  'd': 1  'e': 1  'l': 3  'o': 2  'r': 1

Using ASCII values as array subscripts, a single pass completes the count. 256 slots cover all 8-bit characters.

▶ Example

Count letter frequencies and find the most frequent letter:

▶ Try it Yourself
TEXT
Most frequent letter: o (4 times)

Reference entries in this section: qsort

❓ FAQ

Q How do I determine the size of my array in C?
A sizeof(arr) / sizeof(arr[0]) works for a local stack array, but not for a pointer returned by malloc. For heap arrays, you must keep a separate count variable alongside the pointer — the pointer itself carries no size information.
Q How can I initialize all members of an array to the same value?
A Use memset(arr, val, n * sizeof(type)) from string.h. Note that memset works byte-by-byte, so for non-zero values of multi-byte types you need a loop. The = {0} trick zeroes everything when n is part of the declaration but not for dynamically allocated arrays.
Q Is there a printf converter to print in binary format?
A No. printf has %d (decimal), %o (octal), %x (hex) but no %b for binary. To print binary, extract each bit with (n >> i) & 1 and print '0' or '1' from a loop. Or write it manually with a small helper function.
Q What is array-to-pointer conversion aka. decay?
A When you pass an array as a function argument, it automatically decays into a pointer to its first element. That is why sizeof inside a function gives you the size of a pointer (8 bytes on 64-bit) instead of the array. This is a C-specific rule — not related to const or scope.
Q Which is better, bubble sort or selection sort?
A Both have O(n^2) time. Bubble sort has an early termination flag that can give O(n) best case; selection sort always does n-squared comparisons but fewer swaps. The practical difference is tiny — neither is suitable for large datasets. Use qsort or a library sort instead.
Q Why use a 256-element array for frequency counting?
A unsigned char ranges from 0 to 255, totaling 256 distinct values. Using the character code directly as an array index gives O(1) access. For Unicode text you would need a hash table instead.

📖 Summary

📝 Exercises

  1. Enhance bubble sort: implement a function that can sort in either ascending or descending order, controlled by a function pointer parameter.
  2. Implement a recursive version of binary search: int bin_search_rec(const int *arr, int low, int high, int target).
  3. Write an enhanced character frequency analyzer: read a line of user input, then output the top 3 most frequent characters and their counts.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏