Comprehensive C Language Exercises | Sorting + Searching + Data Analysis

📘 Comprehensive C Language Exercises | Sorting + Searching + Data Analysis

Author: IoT Smart Academy

Table of Contents

  1. Bubble Sort: Output 10 temperature data in ascending order
  2. Selection Sort: Sort by signal strength from high to low (including structures)
  3. Binary Search: Find the target value in a sorted array
  4. Comprehensive: Sort first then search (input data → ascending → binary)
  5. Advanced Challenge: Remove duplicates + Count frequency

Exercise 1: Bubble Sort (10 temperature data in ascending order)

✅ Problem

Input 10 temperature values (float), sort them in ascending order and output.

💡 Idea

  • Use <span>float temp[10]</span> to store data
  • Bubble sort: compare adjacent elements, swap if out of order
  • Outer loop controls the number of passes, inner loop controls the number of comparisons

🧾 Complete Code

#include <stdio.h>

int main() {
    float t[10];
    int i, j;
    float tmp;

    printf("Please enter 10 temperature values (℃):\n");
    for (i = 0; i < 10; i++) scanf("%f", &t[i]);

    // Bubble sort: ascending order
    for (i = 0; i < 9; i++) {
        for (j = 0; j < 9 - i; j++) {
            if (t[j] > t[j + 1]) {
                tmp = t[j];
                t[j] = t[j + 1];
                t[j + 1] = tmp;
            }
        }
    }

    printf("Ascending result:\n");
    for (i = 0; i < 10; i++) printf("%.2f ", t[i]);
    printf("\n");
    return 0;
}

🧪 Example

Input: <span>24.5 21.0 23.1 28.6 22.8 19.3 26.1 27.4 25.0 20.2</span> Output (ascending): <span>19.30 20.20 21.00 22.80 23.10 24.50 25.00 26.10 27.40 28.60</span>

IoT Extension: After batch sampling of temperature/humidity/voltage, sorting is often required for quantile analysis or outlier detection.

Exercise 2: Selection Sort (Sensor Signal Strength in Descending Order)

✅ Problem

Input the ID and signal strength of 5 sensors, and sort them by strength from high to low. (It is recommended to use structures for data binding)

💡 Idea

  • Define a structure <span>Sensor {id, strength}</span>
  • Selection sort: each round selects the “maximum from the remaining” and places it in the current position
  • Ensure that ID and strength move together during sorting

🧾 Complete Code

#include <stdio.h>

typedef struct {
    int id;         // Sensor ID
    float strength; // Signal strength
} Sensor;

int main() {
    Sensor s[5];
    int i, j, maxIdx;
    Sensor tmp;

    printf("Please enter the ID and signal strength of 5 sensors, e.g.: 101 78.5\n");
    for (i = 0; i < 5; i++) scanf("%d %f", &s[i].id, &s[i].strength);

    // Selection sort: by strength in descending order
    for (i = 0; i < 4; i++) {
        maxIdx = i;
        for (j = i + 1; j < 5; j++) {
            if (s[j].strength > s[maxIdx].strength) maxIdx = j;
        }
        if (maxIdx != i) {
            tmp = s[i];
            s[i] = s[maxIdx];
            s[maxIdx] = tmp;
        }
    }

    printf("Sorted results by strength (descending):\n");
    printf("ID\tStrength\n");
    for (i = 0; i < 5; i++) printf("%d\t%.2f\n", s[i].id, s[i].strength);

    return 0;
}

🧪 Example

Input:

101 78.5
102 65.2
103 88.0
104 73.9
105 90.3

Output (descending):

ID    Strength
105     90.30
103     88.00
101     78.50
104     73.90
102     65.20

Practical Tip: Sorting structures is a common data processing method in competitions and projects.

Exercise 3: Binary Search (Find Target in Sorted Array)

✅ Problem

Given a sorted array (in ascending order), input a target value <span>x</span>, and use binary search to output its index position (prompt if not found).

💡 Idea

  • Binary search prerequisite: the array must be sorted
  • <span>left, right, mid</span> maintain the search interval
  • Compare <span>a[mid]</span> with <span>x</span>: equal → found; greater → go left; smaller → go right

🧾 Complete Code

#include <stdio.h>

int main() {
    int a[10] = {10, 15, 20, 30, 40, 50, 60, 75, 90, 100};
    int x, left = 0, right = 9, mid, pos = -1;

    printf("Please enter the number to search for:");
    scanf("%d", &x);

    while (left <= right) {
        mid = (left + right) / 2;
        if (a[mid] == x) { pos = mid; break; }
        else if (a[mid] > x) right = mid - 1;
        else left = mid + 1;
    }

    if (pos == -1) printf("Not found %d\n", x);
    else printf("Found %d, at index %d (the %dth)\n", x, pos, pos + 1);

    return 0;
}

🧪 Example

Input: <span>75</span> → Output: <span>Found 75, at index 7 (the 8th)</span>

IoT Extension: Index/dictionary structures are often based on the idea of “binary search” (e.g., lookup tables, mapping, deduplication).

Exercise 4 (Comprehensive): Input Data → Ascending Sort → Binary Search

✅ Problem

Input <span>n(≤50)</span> integers, first sort in ascending order, then input a target value to perform binary search and output the result.

💡 Idea

  • Use bubble sort to complete ascending order
  • Then perform binary search
  • Chain the process together (input → sort → search → output)

🧾 Complete Code

#include <stdio.h>

int main() {
    int n, i, j, x, left, right, mid, pos = -1;
    int a[50], tmp;

    printf("Please enter the number of elements n(≤50):");
    scanf("%d", &n);
    if (n <= 0 || n > 50) { printf("n is invalid\n"); return 0; }

    printf("Please enter %d integers:\n", n);
    for (i = 0; i < n; i++) scanf("%d", &a[i]);

    // 1) Bubble sort (ascending)
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp;
            }
        }
    }

    printf("Ascending result:");
    for (i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");

    // 2) Binary search
    printf("Please enter the target value to search for:");
    scanf("%d", &x);

    left = 0; right = n - 1; pos = -1;
    while (left <= right) {
        mid = (left + right) / 2;
        if (a[mid] == x) { pos = mid; break; }
        else if (a[mid] > x) right = mid - 1;
        else left = mid + 1;
    }

    if (pos == -1) printf("Not found %d\n", x);
    else printf("Found %d, at index %d (the %dth)\n", x, pos, pos + 1);

    return 0;
}

🧪 Example

n=8
Input: 34 12 56 12 89 23 10 45
Ascending: 10 12 12 23 34 45 56 89
Search: 34
Output: Found 34, at index 4 (the 5th)

Advanced Challenge

✨ Task A: Remove duplicates after sorting and output

  • Input several integers
  • After sorting in ascending order, remove duplicates and output (keep only one of the same elements)

👉 Tip: After sorting, equal elements are together; use a new array or overwrite in place.

✨ Task B: Count the frequency of each value (frequency table)

  • After sorting, traverse again
  • Count consecutive identical elements
  • Output <span>value: count</span>

These two tasks are the basics of “data cleaning”: deduplication + counting. They are very common in IoT logs/alert data.

Common Errors Reference

Error Phenomenon Cause Correction
Sorting misalignment Missing one side during swap Swap both positions simultaneously
Binary search infinite loop <span>left/right</span> not updating Update <span>left=mid+1/right=mid-1</span> promptly in branches
Binary search on unsorted array Not sorted first Sort first then binary search
Reading structure misalignment Input format is incorrect <span>scanf("%d %f", &id, &strength)</span>
Bubble sort boundary error Inner upper limit written as <span>n-i</span> Should be <span>n-1-i</span>

Summary

  • You practiced bubble/selection sort, sequential/binary search
  • You mastered the common process of “sorting → searching
  • You learned to use structures to bind multiple fields for sorting (practicality UP)
  • You understood the basic data cleaning ideas of deduplication/counting

✔️ If you can type out all the code in this article and understand the output, your “array + algorithm introductory ability” has passed!

Next Article Preview

📗 C Language Practical: Student Grade Management System (Array + Sorting + Searching + Statistics)

  • Input/Print/Sort/Query/Statistics/Save
  • Menu-style interaction, structure to manage data
  • A small project that can be run directly in class

Leave a Comment