C Language Lab 3 Explained: 7 Essential Exercises in Functions, Recursion, Branching, and ASCII Output

This article focuses on a set of foundational C programming labs. Across seven independent exercises, it trains function encapsulation, conditional branching, recursive design, and loop-based output. The goal is to solve a common beginner problem: being able to write statements, but not yet being able to abstract logic into functions. Keywords: C, recursion, function design.

Technical Specification Snapshot

Parameter Details
Language C
License/Source Blog lab notes; no open-source license specified
Stars Not provided
Core Dependencies stdio.h, stdlib.h
Topic Scope switch branching, recursion, combinations, greatest common divisor, character graphics

This lab set systematically covers the core training points of C function design

The original material contains seven lab tasks, ranging from score-to-grade mapping to printing character arrays. Together, they cover function declarations, return value design, parameter passing, recursive problem solving, and control-flow decisions.

The value of these exercises does not lie in their difficulty. Their real value is that each task maps to a fundamental algorithmic pattern. For beginners, these patterns often determine whether they can move smoothly into data structures, algorithms, and engineering-oriented coding later on.

Lab 1 uses switch to perform discrete score-to-grade mapping

The score_to_grade function uses score / 10 to compress a continuous score range into a finite set of branches, then uses switch to return grades A through E. This is a classic interval-mapping pattern.

#include <stdio.h>

char score_to_grade(int score) {
    switch (score / 10) {
        case 10:
        case 9: return 'A';   // Map 90-100 to A
        case 8: return 'B';   // Map 80-89 to B
        case 7: return 'C';   // Map 70-79 to C
        case 6: return 'D';   // Map 60-69 to D
        default: return 'E';  // Map all other scores to E
    }
}

This code maps an integer score to a character grade and demonstrates a compact pattern that combines switch with return.

The original article points out two common mistakes. First, character return values must use single quotes. Second, if a case omits break, fall-through occurs and can produce incorrect results. This is one of the most common control-flow issues in the early stages of learning C.

Labs 2 and 3 demonstrate two ways of thinking: iteration and recursion

sum_digits uses % 10 and / 10 to extract each digit. At its core, it performs integer digit decomposition. power, by contrast, uses recursion and even-odd divide-and-conquer to compute exponents, making it significantly more efficient than naive repeated multiplication.

int sum_digits(int n) {
    int ans = 0;
    while (n != 0) {
        ans += n % 10;  // Add the current least significant digit
        n /= 10;        // Remove the processed least significant digit
    }
    return ans;
}

int power(int x, int n) {
    if (n == 0) return 1;          // Any number to the power of 0 is 1
    if (n % 2 != 0) return x * power(x, n - 1);  // Reduce odd exponents with one multiplication
    int t = power(x, n / 2);
    return t * t;                  // Accelerate even exponents by squaring
}

These functions implement digit-sum calculation and fast exponentiation, respectively. The first trains loop-based reasoning, while the second trains recursion and divide-and-conquer.

The key value of power is not just that it uses recursion. More importantly, it converts a mathematical property into program structure. An even exponent requires solving only one subproblem, which makes this a strong introductory example of high-quality recursive design.

The triangle classification exercise shows that condition order directly affects correctness

The core of classify_triangle is not the if-else syntax itself, but the order of checks. The function must first determine whether the three sides can form a triangle, then classify equilateral, isosceles, right, and ordinary cases. Otherwise, invalid input may be misclassified.

int classify_triangle(int a, int b, int c) {
    if (a + b <= c || a + c <= b || b + c <= a)
        return 0;  // The sum of any two sides must be greater than the third side
    else if (a == b && b == c)
        return 2;  // All three sides are equal: equilateral triangle
    else if (a == b || a == c || b == c)
        return 3;  // Two sides are equal: isosceles triangle
    else if (a * a + b * b == c * c ||
             a * a + c * c == b * b ||
             b * b + c * c == a * a)
        return 4;  // Satisfies the Pythagorean theorem: right triangle
    else
        return 1;  // All remaining cases are ordinary triangles
}

This function maps input side lengths to triangle type codes and demonstrates how to design a multi-condition classification function.

One important detail is that an isosceles right triangle is classified here as isosceles rather than right. That highlights an important requirement question: whether classification rules should be mutually exclusive must be defined at the specification level, not inferred from the code alone.

Combinations and greatest common divisor illustrate mathematical definitions and brute-force search

Lab 5 presents two ways to compute combinations: an iterative version based on the factorial formula, and a recursive version based on Pascal’s identity, C(n,m)=C(n-1,m)+C(n-1,m-1). Both are correct, but they fit different use cases.

int comb(int n, int m) {
    if (m == 0 || m == n)
        return 1;  // Boundary condition for combinations
    if (m > n)
        return 0;  // Return 0 directly for invalid input
    return comb(n - 1, m) + comb(n - 1, m - 1);  // Recursively split into subproblems
}

int gcd3(int a, int b, int c) {
    int min = a;
    if (b < min) min = b;
    if (c < min) min = c;
    for (int i = min; i >= 1; i--) {
        if (a % i == 0 && b % i == 0 && c % i == 0)
            return i;  // Search downward for the first common factor
    }
    return 1;
}

These functions demonstrate recursive computation of combinations and a direct search method for the greatest common divisor of three integers.

gcd3 works, but its efficiency is limited. A better implementation would first compute gcd(a, b), then compute the GCD of that result with c, replacing linear trial division with the Euclidean algorithm.

The character graphics exercise trains nested loops and layout control

Lab 7’s print_charman is essentially a three-level formatting problem. The outer loop controls the number of rows, the middle loop controls indentation, and the inner loop controls how many character figures appear on each line. The output elements are the head, body, and legs.

Lenovo Screenshot_20260419121420 AI Visual Insight: This image shows a console screenshot of the lab output after execution. It is used to verify the mapping between input scores and output grades, with emphasis on confirming that the switch-case classification logic runs correctly.

7.1 AI Visual Insight: This image shows the first output pattern of the character figure array. Each layer is composed of O, `

`, and `I I`, and tab characters create a pyramid-like alignment, confirming that the nested loops and indentation control are working as intended. ![7.2](https://img2024.cnblogs.com/blog/3779862/202604/3779862-20260421233236837-670168657.jpg) **AI Visual Insight:** This image shows another character graphics output example. It emphasizes that as the parameter changes, both the number of character figures and the indentation levels change together, validating the correctness of the outer row control and inner repeated-print logic. “`c void print_charman(int n) { for (int i = n – 1; i >= 0; i–) { for (int k = n; k > i; k–) printf(“\t”); // Control left indentation for (int j = 0; j i; k–) printf(“\t”); // Control body layer alignment for (int j = 0; j \t”); printf(“\n”); for (int k = n; k > i; k–) printf(“\t”); // Control leg layer alignment for (int j = 0; j [AI Readability Summary] > > This article reconstructs a set of foundational C programming labs covering score mapping, digit summation, exponentiation, triangle classification, combinations, greatest common divisor, and character-based output. It extracts the core algorithm in each task, highlights common mistakes, and provides reusable implementation ideas, making it a strong reference for getting started with function design and recursion.