How to Use for Loops in C Programming

By Dan Gookin

A loop is simply a group of statements in your C code that repeats. The for keyword helps set up that basic type of loop.

How to do something x number of times in C programming

It’s entirely possible, and even a valid solution, to write source code that displays the same line of text ten times. Simple, but it’s not a loop.

WRITE THAT DOWN TEN TIMES!

#include <stdio.h>
int main()
{
  int x;
  for(x=0; x<10; x=x+1)
  {
    puts("Sore shoulder surgery");
  }
  return(0);
}

Exercise 1: Create a new project using the source from Write That Down Ten Times! Type everything carefully, especially Line 7. Build and run.

As output, the program coughs up the phrase Sore shoulder surgery ten times, in ten lines of text. The key, of course, is in Line 7, the for statement. That statement directs the program to repeat the statement(s) in curly brackets a total of ten times.

Basics of the for loop

The for loop is usually the first type of loop you encounter when you learn to program. It looks complex, but that’s because it’s doing everything required of a loop — in a single statement:

for(initialization; exit_condition; repeat_each)

Here’s how it works:

initialization is a C language statement that’s evaluated at the start of the loop. Most often, it’s where the variable that’s used to count the loop’s iterations is initialized.

exit_condition is the test upon which the loop stops. In a for loop, the statements continue to repeat as long as the exit condition is true. The expression used for the exit_condition is most often a comparison, similar to something you’d find in an if statement.

repeat_each is a statement that’s executed once every iteration. It’s normally an operation affecting the variable that’s initialized in the first part of the for statement.

The for statement is followed by a group of statements held in curly brackets:

for(x=0; x<10; x=x+1)
{
  puts("Sore shoulder surgery");
}

You can omit the brackets when only one statement is specified:

for(x=0; x<10; x=x+1)
  puts("Sore shoulder surgery");

In this for statement, and from Write That Down Ten Times!, the first expression is initialization:

x=0

The value of the int variable x is set to 0. In C programming, you start counting with 0, not with 1.

The second expression sets the loop’s exit condition:

x<10

As long as the value of variable x is less than 10, the loop repeats. Once that condition is false, the loop stops. The end effect is that the loop repeats ten times. That’s because x starts at 0, not at 1.

Finally, here’s the third expression:

x=x+1

Every time the loop spins, the value of variable x is increased by 1. The preceding statement reads, “Variable x equals the value of variable x, plus 1.” Because C evaluates the right side of the equation first, nothing is goofed up. So if the value of x is 5, the code is evaluated as

x=5+1

The new value of x would be 6.

Read the expression this way:

for(x=0; x<10; x=x+1)

“For x starts at 0, while x is less than 10, increment x.”

Counting with a Loop shows another example of a simple for loop. It displays values from -5 through 5.

COUNTING WITH A LOOP

#include <stdio.h>
int main()
{
  int count;
  for(count=-5; count<6; count=count+1)
  {
    printf("%dn",count);
  }
  return(0);
}

Exercise 3: Type the source code from Counting with a Loop into a new project. Build and run.

Exercise 4: Create a new project using the source code from Counting with a Loop as a starting point. Display the values from 11 through 19. Separate each value by a tab character, t. Use the <= sign for the comparison that ends the loop. Clean up the display by adding a final newline character when the loop is done.

  • The for statement uses two semicolons to separate each item, not commas. Even so:

  • It’s possible to specify two conditions in a for statement by using commas. This setup is rather rare, so don’t let it throw you.

How to count with the for statement

You’ll use the for statement quite frequently in your coding travels. Counting by Two shows another counting variation.

COUNTING BY TWO

#include <stdio.h>
int main()
{
  int duo;
  for(duo=2;duo<=100;duo=duo+2)
  {
    printf("%dt",duo);
  }
  putchar('n');
  return(0);
}

Exercise 5: Create a new project using Counting by Two as your source code. Compile and run.

The program’s output displays even values from 2 through 100. The value 100 is displayed because the “while true” condition in the for statement uses <= (less than or equal to). The variable duo counts by two because of this expression:

duo=duo+2

In Line 9, the printf() function uses t to display tabs (though the numbers may not line up perfectly on an 80-column display). Also, the putchar() function kicks in a newline character in Line 11.

Exercise 6: Modify the source code from Counting by Two so that the output starts at the number 3 and displays multiples of 3 all the way up to 100.

Exercise 7: Create a program that counts backward from 25 to 0.

How to loop letters in C programming

Counting by Letter shows another way to “count” using a for loop.

COUNTING BY LETTER

#include <stdio.h>
int main()
{
  char alphabet;
  for(alphabet='A';alphabet<='Z';alphabet=alphabet+1)
  {
    printf("%c",alphabet);
  }
  putchar('n');
  return(0);
}

Before you type the source code from Counting by Letter, can you guess what the output might be? Does it make sense to you?

Exercise 8: Use the source code from Counting by Letter to create a new project. Build and run.

Exercise 9: Modify the printf() function in Line 9 so that the %d placeholder is used instead of %c.

Computers see characters as numbers. Only when numbers are displayed and they fall in the ASCII code range for characters do characters appear.

Exercise 10: Using Counting by Letter as your inspiration, write a for loop that “counts” backward from z (lowercase Z) to a (lowercase A).