Skip to content

Beginner · Operators and control flow · topic 10 of 60 · 30 min

Solving problems with loops

Explanation

Classic beginner problems train loop thinking: sum and reverse the digits of a number with % 10 and / 10, check whether a number is prime by testing divisors up to its square root, find the greatest common divisor with Euclid's algorithm, and generate Fibonacci numbers. These appear in almost every C interview and placement test.

Digits: % 10 and / 10

n % 10 gives the last digit of a non-negative number, and n / 10 removes it. Repeating both until n becomes 0 visits every digit, from right to left.

c
int n = 4521, sum = 0, reversed = 0;
while (n > 0) {
    int digit = n % 10;          /* 1, then 2, then 5, then 4 */
    sum += digit;
    reversed = reversed * 10 + digit;
    n /= 10;
}
printf("sum %d, reversed %d\n", sum, reversed);   /* sum 12, reversed 1254 */

Prime check: only up to the square root

A prime number has no divisors other than 1 and itself. If n has a divisor bigger than its square root, it also has a matching one smaller than the square root, so testing up to √n is enough. Write the condition as i * i <= n to avoid floating point (but beware overflow for n close to INT_MAX).

c
int is_prime(int n) {
    if (n < 2) return 0;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return 0;     /* found a divisor */
    }
    return 1;
}
/* is_prime(97) → 1, is_prime(91) → 0 (7 × 13) */

GCD with Euclid's algorithm

The greatest common divisor (GCD) of two numbers is the largest number that divides both. Euclid noticed that gcd(a, b) equals gcd(b, a % b), and gcd(a, 0) is a. Each step makes the numbers smaller, so the loop ends quickly, even for huge numbers. The LCM is then a / gcd(a, b) * b (divide first to reduce overflow).

c
int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}
/* gcd(84, 36): (84,36) → (36,12) → (12,0) → 12 */

Fibonacci

c
long long a = 0, b = 1;
for (int i = 0; i < 10; i++) {
    printf("%lld ", a);           /* 0 1 1 2 3 5 8 13 21 34 */
    long long next = a + b;
    a = b;
    b = next;
}
Fibonacci numbers grow fast; even long long overflows after about the 92nd term.

Counting and patterns

Other common tasks: count digits (keep dividing by 10), check an Armstrong number (153 = 1³ + 5³ + 3³), check a palindrome number (reverse and compare), and print number or star patterns with nested loops. They all reuse the same few ideas: % and /, an accumulator variable, and loop bounds.

Careful: Edge cases break most first attempts: 0 (the digit loop above does not run at all, so 0 has digit sum 0 and "reverse" 0; is that what you want?), 1 (not prime), negative numbers (% of a negative number is negative in C), and overflow (reversing 1,999,999,999 overflows an int). Test these deliberately.
Think of it like this: Peeling digits with % 10 and / 10 is like taking coins off the top of a stack one at a time: you look at the top coin (the last digit), set it aside, and the stack gets shorter until nothing is left.
Tip: Before coding, trace the loop by hand on a small input in a table with one column per variable. Interviewers love it when you do this aloud.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Solving problems with loops · 1/6

Loop problems

In this lesson you will solve classic number problems with loops.

Prefer a video by a teacher? Find free videos on “c programs prime number gcd euclid reverse number digit sum” on YouTube ↗

In real life: A check digit on a product code

Barcodes and many ID numbers include a check digit computed from the other digits, so a mistyped digit is caught at the billing counter. The calculation is a digit loop like the ones in this topic. (This is a simplified scheme for practice, not the official EAN or Aadhaar algorithm.)

c
int check_digit(long long code) {
    int sum = 0, pos = 0;
    while (code > 0) {
        int d = code % 10;
        sum += (pos % 2 == 0) ? d * 3 : d;   /* weight every other digit by 3 */
        code /= 10;
        pos++;
    }
    return (10 - sum % 10) % 10;
}

Practice (0/3 done)

Task 1 · Code · Python

The same digit algorithm in Python, which runs here: write digit_sum(n) for n >= 0 using % 10 and // 10 in a loop (do not convert to a string).

Task 2 · Code · Javascript

The same algorithms in JavaScript: write isPrime(n) (testing divisors while i * i <= n) and gcd(a, b) using Euclid's loop.

Task 3 · Question

What does this print? int n = 1230, r = 0; while (n > 0) { r = r * 10 + n % 10; n /= 10; } printf("%d\n", r);

Quick quiz

Question 1

1.Why test divisors only up to √n when checking primes?

Question 2

2.What is gcd(48, 18)?

Question 3

3.What does n % 10 give for n = 4521?

Question 4

4.Which number is an Armstrong number (sum of cubes of its digits)?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Why test divisors only up to √n when checking primes?

Answer: Any divisor above √n pairs with one below √n

Divisors come in pairs.

What is gcd(48, 18)?

Answer: 6

(48,18) → (18,12) → (12,6) → (6,0).

What does n % 10 give for n = 4521?

Answer: 1

The last digit.

Which number is an Armstrong number (sum of cubes of its digits)?

Answer: 153

1 + 125 + 27 = 153.

Which of these is a data structure rather than an algorithm?Related

Answer: A queue

A queue is a way of storing items (first in, first out). The others are step-by-step methods, which are algorithms.

From What DSA is, and how to learn it

Outer loop runs 4 times, inner loop runs 5 times each. How many inner rounds in total?Related

Answer: 20

The inner loop runs fully for each outer round: 4 × 5 = 20.

From Loop patterns that solve real problems

Why is naive recursive Fibonacci slow?Related

Answer: It recomputes the same values exponentially many times

fib(n-1) and fib(n-2) overlap heavily.

From Recursion

Searching for the LAST x with x × x ≤ n, why use mid = (lo + hi + 1) // 2?Related

Answer: With lo = mid on success, rounding down could leave lo unchanged and loop forever

When hi = lo + 1, rounding down gives mid = lo; rounding up makes progress.

From Binary search on the answer

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Operators and control flow”. The module exam comes next.
  2. Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and arrays. 60 topics left in the course before the final exam.

← Previous: Loops: for, while and do-while