Reading history

Logic Building Problems in C: 13 Classic Exercises

11 min read 8 views

Build programming logic with 13 classic C problems, from digit sums and palindromes to GCD, primes, the sieve and Tower of Hanoi.

Logic building means learning to turn a problem in words into exact steps a computer can follow. Syntax is the easy part; the hard part is spotting the pattern. These 13 classic problems train exactly that skill, starting with digits and building up to recursion and the sieve of Eratosthenes.

In this lesson you will learn

  • A four-step method for solving any logic problem
  • The digit-peeling trick behind many number problems
  • How to test primes, find GCD and LCM, and factorise numbers efficiently
  • How binary search solves maths problems, not just searches
  • Two famous problems that need clever thinking: the sieve and Tower of Hanoi

A Four-Step Method for Any Problem

  1. Restate the problem in your own words. What exactly goes in, and what must come out?
  2. Work two or three small examples by hand. Write down every step you take without thinking about code.
  3. Find the repeating step. The step you repeated by hand becomes the body of your loop or recursive call.
  4. Code the simple version first, then improve it. Test edge cases: 0, 1, negative numbers and very large values.

Try each problem below on paper before reading the solution. That struggle is what builds the skill.

Level 1: Working With Digits

Problems 1–3: Count, Sum and Reverse the Digits

Key idea: n % 10 gives the last digit, and n / 10 removes it. Repeat until nothing is left, and you visit every digit from right to left. To build a reversed number, multiply what you have by 10 and add the new digit.

#include <stdio.h>

/* Digits of a number: peel the last digit with % 10, drop it with / 10. */
int main(void) {
    long n = 70214;
    long sum = 0, reversed = 0, count = 0;

    for (long x = n; x > 0; x /= 10) {
        int digit = x % 10;
        sum += digit;
        reversed = reversed * 10 + digit;
        count++;
    }
    printf("number   : %ld\n", n);
    printf("digits   : %ld\n", count);
    printf("sum      : %ld\n", sum);
    printf("reversed : %ld\n", reversed);
    return 0;
}

Output

number   : 70214
digits   : 5
sum      : 14
reversed : 41207

This one loop solves three problems at once. The same digit-peeling pattern appears in checksums, binary conversion and many interview questions.

Problems 4–5: Palindrome and Armstrong Numbers

A palindrome number reads the same backwards, like 12321: reverse it and compare. An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³.

#include <stdio.h>
#include <stdbool.h>

static bool is_palindrome(long n) {
    long original = n, reversed = 0;
    while (n > 0) { reversed = reversed * 10 + n % 10; n /= 10; }
    return original == reversed;
}

static bool is_armstrong(int n) {        /* sum of digits^k equals the number */
    int k = 0, total = 0;
    for (int x = n; x > 0; x /= 10) k++;
    for (int x = n; x > 0; x /= 10) {
        int d = x % 10, power = 1;
        for (int i = 0; i < k; i++) power *= d;
        total += power;
    }
    return total == n;
}

int main(void) {
    long tests[] = {12321, 4554, 1234};
    for (int i = 0; i < 3; i++)
        printf("%ld palindrome? %s\n", tests[i], is_palindrome(tests[i]) ? "yes" : "no");

    printf("Armstrong numbers below 1000:");
    for (int n = 1; n < 1000; n++)
        if (is_armstrong(n)) printf(" %d", n);
    printf("\n");
    return 0;
}

Output

12321 palindrome? yes
4554 palindrome? yes
1234 palindrome? no
Armstrong numbers below 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407

The Armstrong check makes two passes: one to count the digits, one to add up the powers. Using an integer loop for the power, instead of pow() from math.h, avoids rounding errors from floating-point numbers.

Level 2: Divisibility and Primes

Problem 6: Is It Prime?

Key idea: if n = a × b, then one of a or b is at most √n. So you only need to test divisors up to the square root. After checking 2, test only odd numbers.

#include <stdio.h>
#include <stdbool.h>

/* Only test divisors up to the square root: if n = a * b, one of them is <= sqrt(n). */
static bool is_prime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    for (int d = 3; (long)d * d <= n; d += 2)
        if (n % d == 0) return false;
    return true;
}

int main(void) {
    int checks[] = {1, 2, 91, 97, 7919};
    for (int i = 0; i < 5; i++)
        printf("%4d is %s\n", checks[i], is_prime(checks[i]) ? "prime" : "not prime");
    return 0;
}

Output

   1 is not prime
   2 is prime
  91 is not prime
  97 is prime
7919 is prime

For 7919, the loop tests odd numbers up to 88 instead of all numbers up to 7918, about 44 checks instead of nearly 8,000. Writing the condition as d * d <= n avoids calling sqrt() at all. 91 = 7 × 13 is a classic trap for people who guess by eye.

Problems 7–8: GCD and LCM

Key idea: Euclid noticed that the GCD of a and b is the same as the GCD of b and the remainder a % b. Keep replacing until the remainder is 0. Then LCM = a × b / GCD.

#include <stdio.h>

/* Euclid: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. */
static long gcd(long a, long b) {
    while (b != 0) { long r = a % b; a = b; b = r; }
    return a;
}

static long lcm(long a, long b) {
    return a / gcd(a, b) * b;         /* divide first to avoid overflow */
}

int main(void) {
    printf("gcd(84, 36) = %ld\n", gcd(84, 36));
    printf("lcm(84, 36) = %ld\n", lcm(84, 36));
    /* Two buses leave together; one returns every 12 min, the other every 18. */
    printf("buses meet again after %ld minutes\n", lcm(12, 18));
    return 0;
}

Output

gcd(84, 36) = 12
lcm(84, 36) = 252
buses meet again after 36 minutes

Euclid’s method is extremely fast: even for numbers in the billions it needs only a few dozen steps. In lcm, dividing before multiplying keeps the intermediate value small, so it does not overflow.

Problem 9: Prime Factorisation

Key idea: divide out each factor as many times as it fits, starting from the smallest. Whatever is left above 1 at the end is itself a prime.

#include <stdio.h>

/* Prime factors: divide out 2s, then odd numbers up to sqrt(n). */
static void factorise(long n) {
    printf("%ld =", n);
    const char *sep = " ";
    for (long d = 2; d * d <= n; d += (d == 2 ? 1 : 2)) {
        while (n % d == 0) { printf("%s%ld", sep, d); sep = " x "; n /= d; }
    }
    if (n > 1) printf("%s%ld", sep, n);
    printf("\n");
}

int main(void) {
    factorise(360);
    factorise(97);
    factorise(1001);
    return 0;
}

Output

360 = 2 x 2 x 2 x 3 x 3 x 5
97 = 97
1001 = 7 x 11 x 13

The odd-looking step d += (d == 2 ? 1 : 2) moves from 2 to 3, then through 5, 7, 9 and so on, skipping even numbers after 2. Testing 9 is harmless: by then every factor of 3 has already been divided out.

Level 3: Smarter Searching and Patterns

Problem 10: Integer Square Root With Binary Search

Key idea: we want the largest r with r × r ≤ n. If some r is too big, every larger r is too big as well, so the answer can be found by binary search over 0..n.

#include <stdio.h>

/* Integer square root by binary search: largest r with r * r <= n. */
static long isqrt(long n) {
    long lo = 0, hi = n, ans = 0;
    while (lo <= hi) {
        long mid = lo + (hi - lo) / 2;
        if (mid != 0 && mid > n / mid) hi = mid - 1;   /* mid*mid > n, without overflow */
        else { ans = mid; lo = mid + 1; }
    }
    return ans;
}

int main(void) {
    long tests[] = {0, 15, 16, 1000000, 999999999};
    for (int i = 0; i < 5; i++)
        printf("isqrt(%ld) = %ld\n", tests[i], isqrt(tests[i]));
    return 0;
}

Output

isqrt(0) = 0
isqrt(15) = 3
isqrt(16) = 4
isqrt(1000000) = 1000
isqrt(999999999) = 31622

The test mid > n / mid means the same as mid * mid > n, but it cannot overflow. This “binary search on the answer” idea solves many harder problems. Learn more in Binary Search Applications.

Problem 11: Pascal’s Triangle

Key idea: each number is the sum of the two above it. You can build each row in the same array if you update from right to left, so you never overwrite a value you still need.

#include <stdio.h>

/* Pascal's triangle: each entry = the one above-left + the one above. */
int main(void) {
    int rows = 6;
    long row[16] = {1};
    for (int r = 0; r < rows; r++) {
        for (int k = r; k > 0; k--) row[k] += row[k - 1];   /* update right to left */
        printf("%*s", (rows - r - 1) * 2, "");
        for (int k = 0; k <= r; k++) printf("%4ld", row[k]);
        printf("\n");
    }
    return 0;
}

Output

             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1

The k-th number in row r counts the ways to choose k items from r, written C(r, k). Row 5 shows there are 10 ways to choose 2 friends out of 5.

Level 4: Two Famous Classics

Problem 12: Sieve of Eratosthenes

To find all primes up to N, testing each number one by one is wasteful. The sieve works the other way round: for each prime p, cross out its multiples. Whatever is never crossed out is prime.

#include <stdio.h>
#include <string.h>

/* Sieve of Eratosthenes: cross out multiples of each prime, starting at p*p. */
int main(void) {
    enum { N = 60 };
    char composite[N + 1];
    memset(composite, 0, sizeof composite);

    for (int p = 2; p * p <= N; p++)
        if (!composite[p])
            for (int m = p * p; m <= N; m += p)
                composite[m] = 1;

    printf("primes up to %d:", N);
    for (int i = 2; i <= N; i++)
        if (!composite[i]) printf(" %d", i);
    printf("\n");
    return 0;
}

Output

primes up to 60: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59

Crossing out starts at p × p, because smaller multiples like 2p and 3p were already crossed out by smaller primes. The sieve runs in O(N log log N) time, which is close to linear.

Problem 13: Tower of Hanoi

Move n discs from peg A to peg C, one at a time, never placing a bigger disc on a smaller one. Key idea: to move n discs, first move the top n − 1 out of the way to B, then move the biggest disc to C, then move the n − 1 discs from B onto it. The same idea solves the smaller pieces, which is recursion.

#include <stdio.h>

/* Tower of Hanoi: move n-1 discs out of the way, move the biggest, move n-1 back on top. */
static long moves = 0;
static int show = 1;                 /* print each move only for the small demo */

static void hanoi(int n, char from, char to, char via) {
    if (n == 0) return;
    hanoi(n - 1, from, via, to);
    moves++;
    if (show) printf("move disc %d from %c to %c\n", n, from, to);
    hanoi(n - 1, via, to, from);
}

int main(void) {
    hanoi(3, 'A', 'C', 'B');
    printf("3 discs: %ld moves\n", moves);

    show = 0;
    moves = 0;
    hanoi(20, 'A', 'C', 'B');
    printf("20 discs: %ld moves (2^20 - 1)\n", moves);
    return 0;
}

Output

move disc 1 from A to C
move disc 2 from A to B
move disc 1 from C to B
move disc 3 from A to C
move disc 1 from B to A
move disc 2 from B to C
move disc 1 from A to C
3 discs: 7 moves
20 discs: 1048575 moves (2^20 - 1)

The number of moves is 2n − 1, so it doubles with every extra disc. With 64 discs, at one move per second, it would take about 585 billion years. This is a good example of exponential time; see time complexity of recursive functions.

How to Keep Improving

  • Solve before you read. Give each problem 20 minutes of honest effort on paper first.
  • Rewrite from memory. A day later, write the solution again without looking.
  • Change the problem. Find palindromes in binary, count digits of negative numbers, or print Pascal’s triangle with commas between the numbers.
  • Move on to arrays. When these feel easy, try our C practice problems and the DSA in C track.

Common Mistakes

  1. Overflow. Factorials, powers and reversed numbers grow fast. Use long long and check limits.
  2. Forgetting 0, 1 and negatives. Is 1 prime? (No.) How many digits does 0 have? (One, but the loop above returns 0.) Handle these cases on purpose.
  3. Using pow() for whole numbers. It works with floating point and can return 124.999 instead of 125. Multiply in a loop instead.
  4. Testing every divisor up to n. Stop at the square root.
  5. Deep recursion without a base case. Every recursive function needs a stopping condition, like if (n == 0) return; in Hanoi.

Practice Exercises

Exercise 1. Using the digit-peeling idea, find the product of the digits of 2045.

Show answer

2 × 0 × 4 × 5 = 0. Any number containing a 0 digit has a digit product of 0.

Exercise 2. What is gcd(270, 192)? Trace Euclid’s steps.

Show answer

270 % 192 = 78 → 192 % 78 = 36 → 78 % 36 = 6 → 36 % 6 = 0. GCD = 6.

Exercise 3. How many moves does Tower of Hanoi need for 10 discs?

Show answer

210 − 1 = 1,023.

Exercise 4. The digit loop prints 0 digits for n = 0. How would you fix it?

Show answer

Use a do { ... } while (x > 0); loop, which always runs once, or handle n == 0 separately before the loop.

Frequently Asked Questions

How long does it take to build programming logic?

Most learners see a clear improvement after 4 to 6 weeks of solving one or two problems a day. Consistency matters more than the number of hours.

Should I memorise solutions?

Memorise the key ideas, like digit peeling, the square-root limit and Euclid’s rule, not the exact code. Ideas transfer to new problems; memorised code does not.

Why practise logic in C rather than Python?

Either works. C makes you think about types, overflow and memory, which builds a deeper understanding. Python lets you focus purely on the idea.

What should I learn after these problems?

Move on to arrays and strings, then data structures. Our DSA in C track continues from here.

Summary

  • Restate, work examples by hand, find the repeating step, then code it.
  • % 10 and / 10 peel digits for sums, reversals and palindromes.
  • Test divisors only up to √n; use Euclid for GCD; LCM = a / gcd × b.
  • Binary search can find answers, such as an integer square root.
  • The sieve finds all primes fast; Tower of Hanoi needs 2n − 1 moves.
Lessons are also marked complete when you click Next.