How to Create Nested for Loops in C Programming

By Dan Gookin

With C programming, you can stick inside a for loop is another for loop. It may seem crazy to loop within a loop, but it’s a common practice. The official jargon is nested loop. A Nested Loop shows an example.

A NESTED LOOP

#include <stdio.h>
int main()
{
  int alpha,code;
  for(alpha='A';alpha<='G';alpha=alpha+1)
  {
    for(code=1;code<=7;code=code+1)
    {
      printf("%c%dt",alpha,code);
    }
    putchar('n');   /* end a line of text */
  }
  return(0);
}

Don’t let all the indents intimidate you; they make the code more readable. Indents also help show which statements belong to which for loop because they line up at the same tab stop.

Line 7 in A Nested Loop begins the first, outer for loop. It counts from letters A to G. It also contains the second, inner for loop and a putchar() function on Line 13. That function helps organize the output into rows by spitting out a newline after each row is displayed.

The printf() function in Line 11 displays the program’s output, specifying the outer loop value, alpha, and the inner loop value, code. The t escape sequence separates the output.

Exercise 11: Type the source code from A Nested Loop into your editor. Build and run.

A1 A2 A3 A4 A5 A6 A7
B1 B2 B3 B4 B5 B6 B7
C1 C2 C3 C4 C5 C6 C7
D1 D2 D3 D4 D5 D6 D7
E1 E2 E3 E4 E5 E6 E7
F1 F2 F3 F4 F5 F6 F7
G1 G2 G3 G4 G5 G6 G7

A triple nested loop contains three for statements, which continues the cascade shown in A Nested Loop. As long as you can match up the curly brackets with each for statement (and that’s easy, thanks to modern text editors), it’s something you can accomplish quite readily.

Exercise 12: Write a three-letter acronym-generating program. The program’s output lists all three-letter combinations from AAA through ZZZ, spewed out each on a line by itself.