C: Practice: Arrays and Functions
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.
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
- Start from the first element and compare each pair of adjacent elements
- If the left element is greater than the right, swap them
- After one pass, the largest value is in its correct position
- Repeat for the remaining portion until fully sorted
(2) Implementation
// 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;
}
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).
qsort in real projects.
▶ Example
Sort scores in descending order using bubble sort:
▶ Try it YourselfRanking: 95 92 88 85 78
For descending order, simply change the comparison from > to <.
2. Project 2: Binary Search
Binary search efficiently locates a target value in a sorted array by halving the search range each step.
(1) Algorithm Steps
- Set the search range to
[low, high] - Calculate the middle position:
mid = (low + high) / 2 - If
arr[mid]equals the target, it is found - If
arr[mid]is less than the target, search the right half - If
arr[mid]is greater than the target, search the left half - If the range shrinks to empty without finding, the target does not exist
(2) Implementation
// 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;
}
23 found at index 5
7 not found
78 found at index 9
1 not found
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 YourselfFirst >= 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
// 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;
}
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 Yourself1
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
// 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;
}
' ': 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 YourselfMost frequent letter: o (4 times)
❓ FAQ
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.(n >> i) & 1 and print '0' or '1' from a loop. Or write it manually with a small helper function.📖 Summary
- Bubble sort sorts by swapping adjacent elements; the swapped flag enables early termination
- Binary search requires a sorted array; O(log n) efficiency far exceeds linear search
- The two-pointer technique reverses strings in-place with O(1) space complexity
- Character frequency analysis uses ASCII values as array subscripts, completing in one pass
- These projects demonstrate the three core skills: array storage, function encapsulation, and pointer manipulation
📝 Exercises
- Enhance bubble sort: implement a function that can sort in either ascending or descending order, controlled by a function pointer parameter.
- Implement a recursive version of binary search:
int bin_search_rec(const int *arr, int low, int high, int target). - Write an enhanced character frequency analyzer: read a line of user input, then output the top 3 most frequent characters and their counts.