Beginner · Operators and control flow · topic 10 of 60 · 30 min
Solving problems with loops
Explanation
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.
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).
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).
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
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;
}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.
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
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.)
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)
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).
The same algorithms in JavaScript: write isPrime(n) (testing divisors while i * i <= n) and gcd(a, b) using Euclid's loop.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Decisions: if, else and switchOperators and control flow · same module
- Type conversion and castingOperators and control flow · same module
- What DSA is, and how to learn itData Structures and Algorithms (DSA) for interviews · Thinking in Big-O
- Loop patterns that solve real problemsJavaScript Programming (language in depth) · Strings, decisions and loops
- RecursionFunctions and arrays
- Binary search on the answerData Structures and Algorithms (DSA) for interviews · Sorting and searching
Questions people ask about this
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.
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.
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.
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
- This is the last topic of “Operators and control flow”. The module exam comes next.
- Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and arrays. 60 topics left in the course before the final exam.