What is For Loop Programs in C- Online Embedded C Programming Classes

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free C Programming Course · Chapter 5 · Lecture 11

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

Planning a loop with three questions Repeated addition and its limits Series sums with accumulators Buffer fill and checksum in embedded C Choosing between for, while and do while Debugging loop programs Best practices FAQ

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.

TaskInitialisationConditionUpdate
Count up from 1 to 5i = 1i <= 5i++
Count down from 20 to 5 in fivesi = 20i >= 5i -= 5
Visit every array elementi = 0i < leni++
Repeat a hardware action 3 timesn = 0n < 3n++
Walk toward the middle of a bufferlo = 0, hi = len-1lo < hilo++, hi--
Three questions before every loop
ask▶Where do I start?▶When do I keep going?▶How do I move?
write▶expression1▶expression2▶expression3

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.

Repeated addition for 6 x 4
start▶product = 0
pass 1▶product = 6
pass 2▶product = 12
pass 3▶product = 18
pass 4▶product = 24
test▶i is 5, condition false, stop
Check the input first. A loop that trusts its count is a bug waiting for a negative number. Validate or take the absolute value before the loop starts.

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.

Accumulator pattern
before▶total = 0
each pass▶compute the term▶add it to total
after▶use total

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 programPurposeWhy for fits
Fill the bufferCreate test dataIndex runs 0 to length minus one
Add the bytesBuild the checksumOne accumulator, one pass over the data
Print the bytesShow the resultSame index range again
Toggle the LEDRepeat an action three timesKnown repeat count
Buffer and checksum workflow
loop 1▶Write bytes into the buffer
loop 2▶Add every byte to the checksum
loop 3▶Report buffer and checksum

Choosing the Right Loop for Your Program

SituationBest loopReason
Known number of repeatsforCounter logic stays in the header
Repeat until a condition appearswhileCount is unknown
Must run at least oncedo whileTest comes last
Run forever in firmwarefor (;;) 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 -Wextra to catch stray semicolons and always-true comparisons.
Do not hide loop bounds. Use a named constant such as 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.

Test Yourself on Loops

Take the quiz and interview lab in the next lecture of this free embedded C course.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →