🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Triad Numbers Program
Solve triad numbers in C with digit extraction, bitmasks and goto. Free C programming course for embedded systems.
Today’s lesson in our free C tutorial solves a classic puzzle: finding triad numbers in C. Three numbers form a triad if each has three digits, the second is twice the first, the third is three times the first, and all nine digits are different. For example 219, 438 and 657 use every digit from 1 to 9 exactly once.
The puzzle looks like pure maths, but solving it teaches three tools used constantly in embedded C programming: digit extraction with % and /, bit flags that record what has been seen, and the careful use of goto. It is a core lesson in our free embedded C course.
What You Will Learn
- How to turn the puzzle rules into a small search with exact loop limits
- How to pull digits out of a number with
% 10and/ 10 - How a single unsigned integer can act as a set of ten flags
- How to leave two nested loops at once with
goto - How to write the cleaner version with a helper function and early return
- How to test and trace candidate numbers by hand
Prerequisites
- Nested
forandwhileloops - Bitwise operators
&,|and<< - Basic functions and pointers to
unsignedvalues
Understanding the Triad Numbers Problem
Let the first number be first. Then the triad is first, 2*first and 3*first. Because every number must have exactly three digits, 3*first cannot exceed 999. That gives first <= 999/3 = 333, and since first must itself have three digits, it starts at 100. So we only need to test the 234 values from 100 to 333, not all 900 three-digit numbers.
For each candidate, collect all nine digits. If any digit appears twice, reject the candidate immediately. If all nine are new, print the triple.
Digit Extraction for Triad Numbers in C
The remainder operator gives the last digit: n % 10. Integer division by ten removes that digit: n / 10. Repeating both until n reaches zero visits every digit from right to left. For 657 the digits come out as 7, then 5, then 6. This works without strings, arrays or library calls, which is exactly what you want on a small microcontroller.
| Step | n | n % 10 (digit) | n / 10 (next n) |
|---|---|---|---|
| 1 | 657 | 7 | 65 |
| 2 | 65 | 5 | 6 |
| 3 | 6 | 6 | 0 (stop) |
Using a Bitmask to Remember Digits
To know whether a digit was seen, we need ten yes/no flags, one for each digit 0 to 9. Instead of an array of ten integers, use the ten lowest bits of one unsigned variable. The expression 1u << digit makes a number with only that digit’s bit set. To test, use seen & (1u << digit). To record, use seen |= 1u << digit.
Every digit lights up once and none is hit twice, so 219 is a triad. Compare 123: its digits are 1, 2 and 3, and doubling gives 246. The digit 2 is already marked, so the candidate is rejected the moment the 2 in 246 is processed.
Embedded tip
Bit flags like this are how GPIO ports, interrupt masks and status registers work. Practising with 1u << n here makes register code feel natural later.
Version One: Leaving Two Loops with goto
The outer loop walks the candidates. The inner loop handles the three multiples, and a while inside it peels off digits. When a repeated digit is found, we are three levels deep and want to go to the next candidate. A break would only leave the innermost loop. A goto to a label at the end of the outer loop body leaves all of them in one step. This is one of the few places where goto is widely accepted.
#include <stdio.h>
int main(void)
{
int first, k, n, digit;
unsigned seen;
for (first = 100; first <= 999 / 3; first++) {
seen = 0;
for (k = 1; k <= 3; k++) {
n = first * k;
while (n > 0) {
digit = n % 10;
if (seen & (1u << digit))
goto next_candidate; /* leave BOTH loops */
seen |= 1u << digit;
n /= 10;
}
}
printf("%d %d %d\n", first, 2 * first, 3 * first);
next_candidate:
;
}
return 0;
}
Build and run
gcc -Wall -Wextra -std=c11 -o triad_goto triad_goto.c
./triad_goto
Expected output:
192 384 576
219 438 657
267 534 801
273 546 819
327 654 981
Notice that 267, 534 and 801 uses the digit 0 once. The rules only ask that all nine digits differ, and zero is allowed in the second and third numbers.
Version Two: A Helper Function Instead of goto
Many teams avoid goto in application code. The same logic reads cleanly if the digit checking moves into a function that returns 0 as soon as a duplicate is found. Early return replaces the jump, and the three calls are chained with &&, which stops at the first failure.
#include <stdio.h>
/* Returns 1 if every digit of n is new to 'seen' (and records them),
* 0 as soon as a repeated digit is found. */
static int take_digits(int n, unsigned *seen)
{
while (n > 0) {
unsigned bit = 1u << (n % 10);
if (*seen & bit)
return 0;
*seen |= bit;
n /= 10;
}
return 1;
}
static int is_triad(int first)
{
unsigned seen = 0;
return take_digits(first, &seen) &&
take_digits(2 * first, &seen) &&
take_digits(3 * first, &seen);
}
int main(void)
{
int first, found = 0;
for (first = 100; first <= 333; first++) {
if (is_triad(first)) {
printf("%d %d %d\n", first, 2 * first, 3 * first);
found++;
}
}
printf("Total triads: %d\n", found);
return 0;
}
Expected output of the second version:
192 384 576
219 438 657
267 534 801
273 546 819
327 654 981
Total triads: 5
Both programs print the same five triads, which is a useful self-check: two different structures, one answer.
goto Versus Function: Which to Choose
| Aspect | goto to a label | Helper function |
|---|---|---|
| Leaves nested loops | One jump | Early return |
| Readability | Needs a clear label name | Name describes the idea |
| Reusable | No | Yes, is_triad() can be tested alone |
| Typical home | Kernel style error cleanup | Application and firmware logic |
| Risk | Jumping past needed cleanup | Slight call overhead |
The Linux kernel uses goto heavily for error cleanup, where each failure label undoes one earlier step. That is the same fall-through staircase idea you learned two lectures ago.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Too many results | Digits not checked across all three numbers | Share one seen mask for the whole triple |
| Missed triads | Loop limit too low | Use first up to 333 inclusive |
| Wrong digits | Forgot to reset the mask per candidate | Set seen = 0 inside the outer loop |
| Endless inner loop | Forgot n /= 10 | Update n every pass |
| Compiler error at label | Label directly before a closing brace | Add an empty statement after the label |
Warning
Reuse of a mask between candidates is the most common bug in this puzzle. Reset it at the top of every candidate.
Best Practices
- Derive loop limits from the problem, not by guessing.
- Use unsigned types for bit manipulation.
- Name labels by purpose, such as next_candidate.
- Prefer small testable functions when the logic may be reused.
- Check the result count against a second implementation.
Performance considerations
The search tries 234 candidates with at most nine digit steps each, so it finishes in well under a millisecond even on a small microcontroller. The bitmask avoids arrays and string conversion, keeping both RAM use and code size tiny.
Summary and Key Takeaways
- The triad puzzle reduces to 234 candidates.
- % 10 and / 10 extract digits without strings.
- One unsigned variable can track ten digits.
- goto can leave nested loops, but a function with early return is often cleaner.
- Five triads exist under these rules.
Conclusion
You have solved a puzzle with the three tools that matter most in low-level work: arithmetic on digits, bit flags and structured exits from nested loops. Finish the chapter with the quiz lab in the next lecture of this free C programming course, where you can test everything from switch fall-through to goto.
Frequently Asked Questions
What are triad numbers?
Three three-digit numbers where the second is twice the first, the third is three times the first, and all nine digits are different.
How many triad numbers are there?
Under these rules there are five: 192 384 576, 219 438 657, 267 534 801, 273 546 819 and 327 654 981.
Why does the first number stop at 333?
Because three times the first number must still be a three-digit number, so it cannot exceed 999.
How do I extract digits in C?
Use n % 10 to get the last digit and n / 10 to remove it, repeating until n is zero.
Is goto bad in C?
Not always. It is accepted for leaving nested loops and for error cleanup, but a helper function is usually easier to read.
Why use a bitmask instead of an array?
A bitmask stores ten flags in one variable, which saves memory and is the same technique used in hardware registers.
Can zero appear in a triad?
Yes. 267 534 801 includes a zero, and the rules only require that all nine digits are different.
Practice task
Change the program to find pairs where the second number is twice the first and all six digits are different. Count how many pairs exist.
Finish the Chapter With the Quiz
Test yourself on switch fall-through, leap years, weekdays and triad numbers in the next free embedded C lecture.

2 Comments