Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Nested Loop Examples in Embedded C: Search, Primes, Patterns, Matrices, Frames and Glyphs
Eight worked examples with real output: linear search, primes with break, triangle/pyramid/diamond patterns, 3×3 matrices, frame extraction, sensor filtering with continue, a 5×7 dot-matrix glyph and a pair-sum search. Study this one of the nested loop examples in embedded C closely.
Nested Loop Examples in Embedded C: What This Page Covers
These nested loop examples in embedded C combine break, continue and loops inside loops into practical routines: searching tables, finding primes, drawing patterns, handling matrices, extracting frames, filtering sensor data and rendering a 5×7 dot-matrix glyph. All programs were compiled and run with GCC; the output shown is real. These nested loop examples in embedded C build on each other.
| # | Example | Skill |
|---|---|---|
| 1 | Linear search with break and a comparison count | Early exit |
| 2 | Prime numbers with an early-exit inner loop | Nested break |
| 3 | Triangle, pyramid and diamond patterns | Nested for |
| 4 | 3×3 matrix add, transpose and multiply | Triple nesting |
| 5 | Extracting frames between start and end markers | break/continue |
| 6 | Filtering invalid sensor data | continue |
| 7 | Rendering a 5×7 font glyph for an LED matrix | Bits in nested loops |
| 8 | Finding a pair that adds up to a target | Leaving two loops |
| 9 | Mini exercises | Self-test |
Example 1: Linear Search with Early Exit
Problem: Find a value in an unsorted table and report how much work was done. The loop stops at the first match; a miss costs all n comparisons. On average a successful search examines half the table. Among the nested loop examples in embedded C this pattern is very common.
table[key]) usually beats searching.Example 2: Prime Numbers with an Early-Exit Inner Loop
Problem: List the primes up to 50. The outer loop takes each candidate; the inner loop tries divisors and leaves with break as soon as one divides evenly. The limit d * d <= n stops at the square root, so the number of divisions stays small. Keep these nested loop examples in embedded C for revision.
A naive version that tries every divisor from 2 to n − 1 and never leaves early performs 1176 divisions for this range; the two improvements together reduce the work to the 95 divisions shown above.
Example 3: Triangle, Pyramid and Diamond
Problem: Draw shapes with nested loops. Each row needs leading spaces and a number of stars that depends on the row number: the inner limits are expressions of the outer counter. The same technique draws bar graphs on a character LCD or serial terminal.
| Shape | Spaces in row r | Stars in row r |
|---|---|---|
| Right triangle | 0 | r |
| Pyramid (n rows) | n − r | 2r − 1 |
| Diamond (distance d from the middle) | d | 2(n − d) − 1 |
Example 4: 3×3 Matrix Addition, Transpose and Multiplication
Problem: Matrix arithmetic appears in sensor fusion, coordinate rotation and filters. Addition and transposition need two nested loops; multiplication needs three, so the cost grows as N³ (27 multiplications here). The row-by-row walk keeps the column index in the inner loop where possible.
arm_mat_mult_f32() or the fixed-point variants; they use the Cortex-M4 DSP instructions and the FPU.Example 5: Extracting Frames Between Start and End Markers
Problem: A serial link delivers text frames wrapped in STX (0x02) and ETX (0x03) with line noise in between. Each continue handles one case and returns to the loop top, so the code stays flat: start byte, noise outside a frame, end byte, data byte. A new STX inside a frame discards the broken one.
The output shows two frames. The broken frame “AB” is dropped when the next STX arrives, which is the standard way to resynchronise.
Example 6: Filtering Invalid Sensor Data with continue
Problem: A 12-bit ADC returns 0 for an open input and 4095 for a short or saturation; anything above 4095 is a software error. Skip such samples and compute statistics from the rest. The continue keeps the three calculations at one indentation level.
count would be 0 and sum / count would crash. Production code checks count > 0 before dividing.Example 7: Rendering a 5×7 Font Glyph
Problem: Character LCD modules and LED matrices store each character as seven bytes with five useful bits each. The outer loop walks the seven rows, the inner loop walks the five pixels from the leftmost bit (bit 4) to the rightmost (bit 0). On real hardware the inner loop would set an output pin instead of printing a character.
A 64-character font needs only 64 × 7 = 448 bytes of flash. The same nested loops can be used to send a bitmap to an SPI display, one row at a time.
Example 8: Finding a Pair That Adds Up to a Target
Problem: Find two readings whose sum equals a target (for example to check a calibration pair). The inner loop starts at i + 1, so each pair is examined once. A break leaves the inner loop and the extra test fi < 0 in the outer condition stops the outer loop: the flag technique from the theory page.
Pairs are examined in index order, so 3 + 11 at indexes 1 and 2 is reported first. The pair 5 + 9 also adds up to 14, but it is never reached because both loops have already stopped. If you need all pairs, remove the early exit.
Example 9: Mini Exercises
Exercise 1: How many times does the inner body run in for (i = 0; i < 4; i++) for (j = 0; j < 3; j++)?
Exercise 2: And in for (i = 0; i < 4; i++) for (j = 0; j < i; j++)?
Exercise 3: Which statement skips only the current pass of a loop?
continue.Exercise 4: In Example 2, why is d * d <= n enough?
Exercise 5: How can you leave two nested loops without goto?
Exercise 6: What is the cost class of matrix multiplication with three loops?
Exercise 7: Why does Example 5 use continue after setting in_frame?
Key Takeaways from the Nested Loop Examples in Embedded C
- These nested loop examples in embedded C show that the inner limit often depends on the outer counter.
- break gives the early exit that makes searches cheap; continue keeps filtering code flat.
- Nested loop cost multiplies: matrix multiplication is cubic, a pair search quadratic.
- Leave two loops with a flag in the outer condition, or move the loops to a function.
- Bitmaps and fonts are processed by nested loops over rows and bits.
- Always guard divisions and array indexes that depend on how many items were accepted.
Ready for the quiz?
Next: predict the output of loops with break and continue, find the bugs and answer the interview questions.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments