SovranCode
HomeCourses C C For Loop
This device
Course contentsC For Loop · 21 titles

C Fundamentals

C IntroductionC First ProgramC VariablesC Data TypesC OperatorsC Input and Output

Control Flow

C If ElseC For LoopC While Loop

Functions and Collections

C FunctionsC ArraysC Strings

Memory and User-Defined Types

C PointersC StructuresC EnumsC Dynamic Memory

Files, Tooling, and Projects

C File HandlingC PreprocessorC DebuggingC MakefilesC Project: Command-Line Inventory Manager
Learn C Programming21 complete lessons

C Fundamentals

C IntroductionC First ProgramC VariablesC Data TypesC OperatorsC Input and Output

Control Flow

C If ElseC For LoopC While Loop

Functions and Collections

C FunctionsC ArraysC Strings

Memory and User-Defined Types

C PointersC StructuresC EnumsC Dynamic Memory

Files, Tooling, and Projects

C File HandlingC PreprocessorC DebuggingC MakefilesC Project: Command-Line Inventory Manager
PREVIOUS LESSONC If Else
NEXT LESSONC While Loop
Control Flow 55 min

C For Loop

Visit a counted range with for, keep the bound exclusive or inclusive on purpose, and prove the loop can stop.

What you will leave with

You will be able to write a for loop whose initialization, condition, and update you can name, trace the first and last values, nest a shallow inner loop, and use break or continue only when the exceptional case is clear.

Use for when the count is visible from the start

A for loop places its three moving parts together: initialization runs once, the condition is checked before every cycle, and the update runs after the body. This structure fits numbered lessons, days, retries with a fixed limit, and array indexes. Declaring the index in the for header (for (int day = 1; ...)) is valid C99 and later, which this course uses.

C FUNDAMENTALS RUNNER

Trace a counted practice loop

The loop starts day at 1, runs while day is at most total_days, then changes day with day++.

#include <stdio.h>

int main(void) {
  int total_days = 3;

  for (int day = 1; day <= total_days; day++) {
    printf("Practice day %d\n", day);
  }
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change the start value to 0 and update the label so the first printed day still makes sense.

  1. 01
    Initialize once

    int day = 1 creates the starting index before the first condition check.

  2. 02
    Test before the body

    day <= total_days decides whether another cycle is allowed.

  3. 03
    Run one cycle

    The body uses the current index.

  4. 04
    Update toward the stop

    day++ adds one so the condition can become false.

Trace the first, last, and forbidden values

Most loop bugs are boundary bugs. Agree on whether the index is zero-based or one-based and whether the ending value belongs in the range. The starter below prints four lines for three lessons: it starts at 0 and includes the endpoint 3. Repair it by starting at 1 with <= total_lessons, or starting at 0 with lesson < total_lessons.

C FUNDAMENTALS RUNNER

Repair an off-by-one loop

Change one part of the loop header, predict the output, then run it again.

#include <stdio.h>

int main(void) {
  int total_lessons = 3;

  for (int lesson = 0; lesson <= total_lessons; lesson++) {
    printf("Lesson %d\n", lesson);
  }
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Make the output contain exactly Lesson 1, Lesson 2, and Lesson 3.

Let the inner loop finish before the outer loop advances

With weeks = 2 and days = 3, expect six lines. Give each index a meaningful name and keep the body small. Nested loops that search every pair of a large collection need a better algorithm later; here the job is to trace the total work.

C FUNDAMENTALS RUNNER

Trace a two-level practice schedule

Notice that the day counter resets to 1 each time a new week begins.

#include <stdio.h>

int main(void) {
  int weeks = 2;
  int days = 3;

  for (int week = 1; week <= weeks; week++) {
    for (int day = 1; day <= days; day++) {
      printf("Week %d, day %d\n", week, day);
    }
  }
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change days to 2 and calculate the total lines before running.

Use break and continue sparingly

break leaves the nearest loop. continue skips the rest of this cycle; a for loop still performs its update before testing again. A plain loop condition is still the clearest normal stopping rule.

C FUNDAMENTALS RUNNER

Skip one cycle and stop after a found result

Attempt 2 uses continue. Attempt 4 uses break.

#include <stdio.h>

int main(void) {
  int attempt;

  for (attempt = 1; attempt <= 5; attempt++) {
    if (attempt == 2) {
      puts("Skip attempt 2.");
      continue;
    }
    printf("Check attempt %d\n", attempt);
    if (attempt == 4) {
      puts("A valid result appeared.");
      break;
    }
  }
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change the skipped attempt to 3 and the successful attempt to 5.

Arrays use index < count

When you visit every element of an array with count items, the usual header is for (int index = 0; index < count; index++). The array does not store its own length. Details belong in C Arrays. Prefer C While Loop when the stop depends on changing state rather than a known count.

Independent lab: print a numbered list

Print one labeled line for each of 1 through n, then change n and predict the last printed number and the value of the index after the loop ends.

Lesson review

  • A for header names initialization, condition, and update.
  • Boundary tests use the first value, last allowed value, cycle count, and the value after the last update.
  • An inner loop completes for one outer value before the outer index changes.
  • break and continue are exceptional exits, not a substitute for a clear condition.

Related lessons

  • C If Else — The loop condition is the same true/false idea as if.
  • C While Loop — Use while when the stop depends on changing state.
  • C Arrays — The collection you will index most often.
KNOWLEDGE CHECK

Trace initialization, condition, and update

Name the first value, the last allowed value, the number of cycles, and the value just after the last update.

01Which loop is usually clearest when a task must happen five times?
02How many times does this body run: for (int day = 1; day <= 3; day++)?
03For an array of count elements, which bound visits every valid index once?
04When does a nested inner loop run relative to the outer loop?
05What does continue do in a for loop?
PREVIOUS LESSONC If Else
NEXT LESSONC While Loop
ON THIS PAGEC For Loopfor syntaxBoundariesNested loopsbreak and continueArraysIndependent labLesson reviewKnowledge checkRelated lessons
Course contents