You’re building a C program. You want to iterate through the code multiple times, but you don’t want to just copy and paste it. What can you do to keep your code as condensed and maintainable as possible while still running it multiple times?

C has several functions intended to iterate through code. They’re called “looping” statements. The most popular of these loops are the for() loop and the while() loop.

A for() loop is a chunk of code that will run as long as its parameters are still true. The design of a for() loop is such that it begins with a single proposition (such as count = 1) and then continues to loop until a condition is met (such as count = 25). While the loop continues, a certain action is taken (such as incrementing the count by 1).

C Programming For Beginners

Last Updated August 2019

  • 76 lectures
  • All Levels
4.4 (3,812)

Learn C in ten easy steps on Windows, Mac OS X or Linux | By Huw Collingbourne

Explore Course

Every programmer needs to understand the logic between a for() loop — and a for() loop operates almost identically in nearly every language. For() loops are one of the most basic and essential forms of programming logic, perhaps second only to the if/then syntax.

What do you use a for() loop for?

For() loops are a staple of any complex coding language. Rather than having to repeat your code over and over, you can instead use a loop. When it comes to programming, there’s always an advantage to being able to simplify code. When you have a single for() loop, you only need to edit the code within the loop rather than edit multiple copies of code.

You can use a for() loop to:

But you don’t always need a for() loop for this. You can also use different types of loop, such as while() or do() while(). There are also functions — such as switch() — that you can use to create something similar to a for() loop.

The anatomy of a for() loop

for ([expression]) {
	[statement]
}

The best way to understand a for() loop is to dissect it. At first, a for() loop looks very complicated — but that’s just because it’s structurally abstract and dense. In reality, a for() loop is extremely simple.

Let’s start with an example. This example is meant to iterate through a variable num, executing a single chunk of code a certain number of times.

#include <stdio.h>

int main() {
	int i;
	for (i = 1; i < 11; ++i) {
		printf(“%d \n“, i);
	}
}

In the loop statement, we declare an int i. We then call the for() loop with the following:

i = 1;This clause sets the int i to equal one when the loop first starts.
i < 11;This clause tells the for loop to continue running until int i is no longer less than 11.
++i; This clause tells the for loop to increase int i by one each loop.

In the body of the loop, it tells the program to print the integer using the printf() command. %d refers to one of many C data types.

In short, the loop will execute 10 times, printing the numbers 1 through 10. The loop terminates once the int num is no longer less than 11 (is 11 or greater). And as long as that is true, the loop will continue to execute the entire block of code inside of it.

We could instead write:

int main() {
	int i;
	for (i = 1; i < 11; i=i+2) {
		printf(“%d\n”, i);
	}
}

This would increase the integer i by two every iteration. Alternatively, we could write:

for (i = 0; i < 11; ++i) {
	printf(“%d\n”, i);
}

In which case the integer i would start at 0 rather than 1. We could also write:

for (i = 1; i <= 25; ++i) {
	printf(“%d\n”, i);
}

This would go up until 25. (In general, it’s better practice to write comparisons like <= 10 rather than < 11 as it’s more fundamentally readable. In the past, < 11 was more desirable because it produced shorter code.)

Without the for() loop, the code to print the numbers 1 through 10 would need to look like this:

int main() {
		printf(“1\n”);
		printf(“2\n”);
		printf(“3\n”);
		printf(“4\n”);
		printf(“5\n”);
		printf(“6\n”);
		printf(“7\n”);
		printf(“8\n”);
		printf(“9\n”);
		printf(“10\n”);
	}

If you decided later that you would rather have a space instead of a new line, you would need to update every line. But with a for() loop, you only need to update one piece of recurring code.

Manipulating data within the for() loop

In the program, the for() loop essentially replicates code. Anything can reside inside of the code block because the code block is being “copied and pasted” multiple times at the direction of the for() loop — as long as the condition is true.  

Consider the following code:

int main() {
	int i;
	int count = 1;
	for (i = 1; i <= 10; ++i) {
		count = i;
	}
	printf(“%d”,count);
}

This code isn’t going to print the numbers 1 through 10 because nothing is printed inside the code. Instead, it’s going to print only the number 10. The variable count was influenced by the for() loop 10 times — but it was only printed outside of the for() loop. (Of course, the variable i can also be used to time the loop, but here we see that you can also use another int main int from outside the loop.)

In fact, you could also write your code as follows, if you wanted to again iterate from the numbers 1 through 10:

for(count = 1; count <= 10; ++count) {
		printf(“%d\n”,count);
	}

It’s not necessary to use “i”; it can be any main int. But i is usually used both out of convention and readability.

The “For” loop vs. “While” loop in C

The for() loop isn’t the only type of loop in C. Another loop variant is the while() loop, which can be used similarly. The while() loop looks like this:

int i;
i = 0;
while (i <= 10) {
printf(“%d\n”,i);
i=i+1; 
}

This while loop also prints the numbers 1 through 10. As you can see, we need to set the int i to 0 before the loop, and the argument passed to the while() loop is the same as the condition statement would be in the for() loop. We also need to increment i manually inside of the loop. In many ways, a while() loop is just a less abstract version of a for() loop.

But there are use cases that are much easier to perform in a while() loop. For example, the while() loop might continually request input from the user until the user gives the correct input.

The “For” loop vs. “Switch” case in C

The for() loop iterates through set code blocks. The switch() case, on the other hand, iterates through discrete code blocks.

Consider the following example: 

int i;
	i = 4;
	switch(i) {
		Case 1: 
			printf(“1\n”); break;
		Case 2:
			printf(“2\n”); break;
		Case 3:
			printf(“3\n”); break;
		Case 4: 
			printf(“4\n”); break;
	}

The above code is always going to execute printf(“4\n”) and then exit out of the switch() function. Of course, if i is set to 2 before the switch() function runs, then it will instead print 2. But the use cases for a switch() function are significantly different from a for() loop — in fact, it’s almost the direct opposite.

With the for() loop, the goal is to iterate between the same code. With the switch() function, the goal is to iterate between completely different blocks of code. Ideally, very little of the code within the switch() function should be repeated, because that would lead to code that’s difficult to maintain (each switch case would have to be updated every time).

Though the switch() case is commonly discussed alongside loops, it’s actually a replacement for unwieldy if/then syntax.

The for() loop and GOTO in C

Programmers who are experienced in older languages will be well-acquainted with GOTO. In other languages, GOTO was the original way to create a loop. Syntactically, GOTO would look like this:

LABEL [label]
[CODE BLOCK]
GO TO [label]

The above code would repeat infinitely (more on infinite recursion next) until it was exited by the program. “GOTO” essentially just directed the program to go to a specific place within the code. 

GOTO is available in C as well, and it can be used to create a for() loop. Consider the following code:

int sum = 1;
	loop:
	printf(“%d”,sum);
	sum=sum+1;
	if(sum<=10) {
		goto loop;
	}

The above code declares a code block “loop.” It prints “sum” from 1 through 10. As long as the integer sum is less than or equal to the number of ten, it “goes to” the label.

Why wouldn’t you use GOTO more frequently? GOTO is dangerous because there’s less structure and fewer controls. You can “GOTO” anywhere within your code from anywhere — and the code isn’t closed off; it’s going to continue going until something exits out.

It’s very easy to end up in an infinitely recursive loop with GOTO or end up with unexpected issues. The use of GOTO is generally deprecated, but it’s a holdover from older languages — and it can be powerful when used in the right hands.

Creating a loop of infinite recursion

An infinitely recursive loop is a loop that either does, or has the potential to, loop infinitely. An infinitely recursive loop can be a huge problem if it’s done accidentally but is sometimes useful when done intentionally.

Here is an example of an infinitely recursive loop:

for (i = 1; i <= 10; i = 1) {
printf(“%d\n”, i);
}

In this example, the programmer likely intended to type “i = i+1.” But instead, they typed “i=1.” Every time the loop initiates, the integer i is set to 1 again. The loop is never-ending because every time the condition is checked, i is less than or equal to 10 — infinitely.

This program will hang and crash because it cannot recover from this recursive loop. It will also consume a large number of resources as it does so.

This isn’t the only way to cause a recursive loop. There’s also another way to cause a recursive loop — and it’s why most programmers use the int i. You can cause a recursive loop by accidentally changing the variables used in its condition statement so that the condition is never met.

for (i = 1; i <= 10; ++i) {
printf(“%d\n”, i);
i=1;
}

In this situation, i is being reset to 1 inside of the for() loop itself. The above program will print 1 until the program crashes. When using “i,” this is very rare because programmers know that i is a reserved integer for the loop.

But if you’re using something like “count,” you could end up in a situation like this:

int i;
int count;
count = 10;
for (i = 1; i <= count; ++i) {
		
printf(“%d\n”, i);
count=count+1;
}

In the above code, the for() loop is iterating until the variable i equals the variable of count. But the variable of count is being increased alongside the variable i — they are never going to meet.

There are reasons why a developer might want an infinitely recursive loop. The clearest is when the developer would like to prompt the user to give input. The user might be directed to give input over and over again until the input has been given. This is potentially infinitely recursive if the user never responds correctly — although there still needs to be an option to exit out of the loop.

Thus, there are really two types of recursive loops:

The former is always a mistake; the latter is used frequently.

The most common mistakes with a for() loop

While the for() loop can seem complex, it ultimately becomes intuitive for most developers. The hurdle with the for() loop is that it’s syntactically dense; once you understand what each statement in the for() loop means, it’s easy enough to logic through.

Some of the most common mistakes with a for() loop include:

Page Last Updated: July 2021

Top courses in C (programming language)

C Programming For Beginners - Master the C Language
Tim Buchalka's Learn Programming Academy, Jason Fedin
4.4 (22,430)
Bestseller
Advanced C Programming Course
Tim Buchalka's Learn Programming Academy, Jason Fedin
4.4 (1,828)
Build Undetectable Malware Using C Language: Ethical Hacking
Aleksa Tamburkovski, Joe Parys
4.5 (880)
C Programming Language: The Ultimate Guide for Beginners
Aptuts Online Coaching, Prashant Nayak
4.5 (184)
C Programming from scratch- Master C Programming
Priyanka Yadav Desai
4.6 (55)
Bestseller
Advanced C Programming: Pointers
Huw Collingbourne
4.7 (2,414)
C Programming For Beginners
Huw Collingbourne
4.4 (3,812)
C PROGRAMMING made easy
Meganadha Reddy
4.4 (1,531)
C Programming from Scratch to Master
SACHIN NANDHA SABARISH J
4.7 (33)

More C (programming language) Courses

C (programming language) students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo