Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

Up until now, we've looked at ways to repeat code, but if you've used while loops, you know they can feel a bit disjointed. You initialize a variable here, check a condition there, and then remember to increment it somewhere in the middle of the block. It's easy to forget that last part and end up in an infinite loop—trust me, I've crashed my IDE more times than I'd like to admit.

The for loop is essentially a "compact" version of the while loop. It puts the initialization, the condition, and the increment all in one line. It's the industry standard when you know exactly how many times you need to iterate, like when you're walking through an array.

Calculating a Weekly Temperature Average

Let's build something practical. Imagine we're writing a small piece of software for a weather station. We have an array containing the high temperatures for one week, and we need to calculate the average. Since we know there are exactly seven days in a week, a for loop is the perfect tool.

#include <stdio.h>

int main() {
    float temps[] = {72.5, 75.0, 68.2, 70.1, 77.4, 81.0, 74.3};
    float sum = 0;

    for (int i = 0; i < 7; i++) {
        sum += temps[i];
    }

    float average = sum / 7;
    printf("The average temperature is: %.2f\n", average);

    return 0;
}

I'm using int i = 0 to start my counter, i < 7 as my boundary, and i++ to move to the next element. It's clean, and I can see the entire logic of the loop without scanning the whole block of code.

The "Off-by-One" Trap

Now, here is where I usually trip up when I'm typing quickly. It's the most common mistake in C: the off-by-one error. Let's say I wrote the loop like this instead:

for (int i = 0; i <= 7; i++) {
    sum += temps[i];
}

Notice that <=? I'm thinking, "Well, there are seven days, so I want to go up to seven." But remember, C arrays are zero-indexed. Our array has indices 0, 1, 2, 3, 4, 5, and 6. When the loop hits i = 7, the program tries to access temps[7], which is a memory location outside our array.

Depending on your compiler, this might just add a random "garbage" value from memory to your sum, or it might cause a segmentation fault and crash your program entirely. Whenever you see a loop crashing at the very end of a collection, check your boundary condition. Use <, not <=, when working with array lengths.

Making the Loop Dynamic

Hardcoding the number 7 is fine for a quick demo, but it's a bad habit. If we change the array to a two-week period, we'd have to hunt down every "7" in our code and change it. Instead, let's use the sizeof trick to let the loop figure out the length on its own.

#include <stdio.h>

int main() {
    float temps[] = {72.5, 75.0, 68.2, 70.1, 77.4, 81.0, 74.3};
    int days = sizeof(temps) / sizeof(temps[0]);
    float sum = 0;

    for (int i = 0; i < days; i++) {
        sum += temps[i];
    }

    printf("Average over %d days: %.2f\n", days, sum / days);
    return 0;
}

By dividing the total size of the array by the size of one element, we get the count of elements. Now, no matter how many temperatures I add to that list, the for loop handles it automatically. This is how you write professional, maintainable code.




📋 Practical Task

The 12-Times Table Generator

Write a program that asks the user for a positive integer. Using a for loop, print the multiplication table for that number from 1 to 12.

Requirements:

  • The program should prompt the user for an input (e.g., "Enter a number: ").
  • The output should be formatted as "Number x Multiplier = Result" (e.g., "5 x 1 = 5", "5 x 2 = 10", etc.).
  • Ensure your loop starts at 1 and ends exactly at 12.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.