Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
For Loop Programs in C
Turn the for loop into working programs: counting, repeated addition, series sums and an embedded checksum, all compiled and run. From our free C programming course for embedded systems.
Syntax is the easy part. What makes a programmer is writing for loop programs in C that handle boundaries, accumulators and odd inputs correctly. This lecture is part of our free C programming course and free C tutorial, aimed at embedded C programming learners who want practice rather than theory alone.
All programs were compiled with GCC and the output shown is real. Each example uses its own scenario, so you can adapt the patterns directly to firmware tasks such as checksums, buffer fills and repeated hardware actions.
What You Will Learn
Prerequisites
- The for loop lecture in Chapter 5
- Integer data types from Chapter 2 and a first look at array indexing (only a[i] is used)
- GCC installed on Linux
Planning For Loop Programs in C
Before you write any loop, answer three questions: what is the starting value, what condition keeps the loop going, and how does the counter move? Those are the three slots of the for header. If you can fill them in words first, the code writes itself. The table below shows how common tasks map onto the three expressions.
| Task | Initialisation | Condition | Update |
|---|---|---|---|
| Count up from 1 to 5 | i = 1 | i <= 5 | i++ |
| Count down from 20 to 5 in fives | i = 20 | i >= 5 | i -= 5 |
| Visit every array element | i = 0 | i < len | i++ |
| Repeat a hardware action 3 times | n = 0 | n < 3 | n++ |
| Walk toward the middle of a buffer | lo = 0, hi = len-1 | lo < hi | lo++, hi-- |
Multiplying with a For Loop in C
Some small microcontrollers have no hardware multiplier, so multiplication by a small count is sometimes written as repeated addition. It is also a perfect first exercise for for loop programs in C, because the loop count is simply the second number.
#include <stdio.h>
int main(void)
{
int a = 6, b = 4;
int product = 0;
int i;
for (i = 1; i <= b; i++) {
product = product + a;
printf("step %d: product=%d\n", i, product);
}
printf("%d x %d = %d\n", a, b, product);
/* what happens when b is 0 or negative */
b = -2;
product = 0;
for (i = 1; i <= b; i++)
product += a;
printf("%d x %d = %d (loop never ran)\n", a, b, product);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o repadd repadd.c
./repadd
step 1: product=6
step 2: product=12
step 3: product=18
step 4: product=24
6 x 4 = 24
6 x -2 = 0 (loop never ran)
Each pass adds a to the running total, and four passes give 24. The second part of the program shows a limit you must know about: when the count is zero or negative, the condition is false from the start, the body never runs and the product stays zero. For negative counts the result is wrong, not just empty, so real code checks the sign first.
Series Sums with a For Loop in C
Summing a series is the standard accumulator pattern: one variable collects a running total and the counter produces the next term. The program below computes two series together. The first adds the squares 1, 4, 9, 16, 25. The second adds a halving sequence 1, 1/2, 1/4 and so on.
#include <stdio.h>
int main(void)
{
int n = 5;
int k;
int squares = 0;
double geo = 0.0;
double term = 1.0;
for (k = 1; k <= n; k++) {
squares += k * k;
geo += term;
term /= 2.0;
printf("k=%d squares=%d geometric=%.4f\n", k, squares, geo);
}
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o series series.c
./series
k=1 squares=1 geometric=1.0000
k=2 squares=5 geometric=1.5000
k=3 squares=14 geometric=1.7500
k=4 squares=30 geometric=1.8750
k=5 squares=55 geometric=1.9375
Two ideas are worth noting. The accumulators start at zero before the loop, because a forgotten initial value is the number one accumulator bug. And the halving sum creeps toward 2 without ever passing it, which shows that a loop count of five gives an approximation rather than an exact limit.
Pick the accumulator type carefully
Use double or float only when fractions are needed. On a small microcontroller without a floating point unit, floating point arithmetic is slow and large, so integer scaling is often preferred.
Embedded For Loop Programs in C
Firmware loves counted loops. The next program fills a buffer with a predictable pattern, adds the bytes to build an 8-bit checksum and then simulates toggling an LED three times. It uses fixed-width types from stdint.h because register and buffer sizes matter in embedded work.
#include <stdio.h>
#include <stdint.h>
#define BUF_LEN 8
int main(void)
{
uint8_t buf[BUF_LEN];
uint8_t checksum = 0;
unsigned int i;
for (i = 0; i < BUF_LEN; i++)
buf[i] = (uint8_t)(i * 3 + 1);
for (i = 0; i < BUF_LEN; i++)
checksum = (uint8_t)(checksum + buf[i]);
printf("bytes:");
for (i = 0; i < BUF_LEN; i++)
printf(" %u", buf[i]);
printf("\nchecksum=%u\n", checksum);
for (i = 0; i < 3; i++)
printf("LED toggle %u\n", i + 1);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o forembedded forembedded.c
./forembedded
bytes: 1 4 7 10 13 16 19 22
checksum=92
LED toggle 1
LED toggle 2
LED toggle 3
The checksum is 92 because the eight bytes add to 92 and fit in one byte. If the sum had passed 255, the 8-bit variable would have wrapped, which is exactly how simple checksums behave on real links.
| Loop in the program | Purpose | Why for fits |
|---|---|---|
| Fill the buffer | Create test data | Index runs 0 to length minus one |
| Add the bytes | Build the checksum | One accumulator, one pass over the data |
| Print the bytes | Show the result | Same index range again |
| Toggle the LED | Repeat an action three times | Known repeat count |
Choosing the Right Loop for Your Program
| Situation | Best loop | Reason |
|---|---|---|
| Known number of repeats | for | Counter logic stays in the header |
| Repeat until a condition appears | while | Count is unknown |
| Must run at least once | do while | Test comes last |
| Run forever in firmware | for (;;) or while (1) | Super loop style |
When planning for loop programs in C, a simple test helps: if you can say how many times the loop will run before it starts, reach for the for loop. If the answer depends on data you have not read yet, use a while loop.
Debugging Tips for Loop Programs
Even well planned for loop programs in C misbehave sometimes, so build a small debugging routine and use it every time.
- Print the counter at the top of the body for a few passes and compare it with your expectation.
- Check the first and last pass by hand before trusting the middle ones.
- When a loop never ends, look at whether the update moves the counter toward the condition.
- When it runs one time too many or too few, test the boundary: is it
<or<=? - Compile with
-Wall -Wextrato catch stray semicolons and always-true comparisons.
BUF_LEN for the length instead of repeating the number. When the buffer size changes, every loop updates together.Best Practices
Habits that keep loop programs safe
- Initialise every accumulator before the loop.
- Use named constants for loop limits.
- Keep the body short and move long work into a function.
- Validate any count that comes from user input or a received packet.
- Choose the narrowest type that holds the result, and think about overflow.
These habits apply to every one of your for loop programs in C, from a ten-line exercise to a driver.
Performance: keep expensive operations such as division and floating point out of the loop body when they can be done once before it. Security: a loop count taken from an external message must be clamped to the buffer size, otherwise the loop becomes an out-of-bounds write.
Key Takeaways
- Fill the three for slots in words first: start, continue, move.
- Repeated addition shows the loop count equals the second operand, and zero or negative counts need care.
- Accumulators must start at a known value before the loop.
- Buffer fills and checksums are everyday for loop programs in C for embedded work.
- Choose for when the repeat count is known, while or do while otherwise.
Conclusion
Practising for loop programs in C builds the habit of thinking about boundaries, accumulators and types before writing a single line. Those habits matter far more than the syntax, because the bugs in real firmware nearly always live at the edges of a loop.
The final lecture of this block is a practice lab with multiple choice questions, output prediction, challenges and interview questions on do while and for loops.
Frequently Asked Questions
How do I write a for loop program in C?
Decide the start value, the continue condition and the update step, then place them in the three slots of the for header.
How do I sum a series with a for loop in C?
Start an accumulator at zero, compute each term using the counter, add it inside the loop and use the total after the loop.
How can I multiply without the multiplication operator?
Add the first number to a running total as many times as the second number, using the second number as the loop bound.
What happens if the loop count is zero?
The condition is false at the first test, so the body never runs and the accumulator keeps its starting value.
Why use stdint.h types in embedded loops?
Fixed-width types such as uint8_t make buffer and register sizes explicit and behave the same on every platform.
How do I avoid off by one errors in for loops?
Start at zero, test with less than against the length and check the first and last pass by hand.
Where can I practise more in this free C tutorial?
The next lecture is a free quiz and interview lab built for embedded C programming learners.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments