Table of contents
1.
Introduction
2.
What is Iteration in C?
2.1.
Example 
3.
Types of Iteration Statements in Programming
4.
For Loop
5.
While Loop
6.
Do-While Loop
7.
Iteration Statements across Different Languages
7.1.
For Loop
7.2.
While Loop
7.3.
Do-While Loop
7.4.
Foreach Loop
8.
Frequently Asked Questions
8.1.
What is the difference between a for loop & a while loop?
8.2.
Can you have an infinite loop in C programming?
8.3.
What is the purpose of the break statement in loops?
9.
Conclusion
Last Updated: Jan 15, 2025
Easy

Iteration in C

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Iteration is a basic concept of programming that allows you to repeat a block of code multiple times. In C language, iteration is done by the use of loops. Loops help you to execute a set of instructions repeatedly until a specific condition is met. With iteration, you can automate repetitive tasks, process arrays or lists of data, and solve complex problems efficiently. 

Iteration in C

In this article, we will explain the different types of loops available in C language with which we can do iteration, like the for loop, while loop, & do-while loop. We will talk about their syntax, see examples, & discuss when to use each type of loop.

What is Iteration in C?

Iteration in C is the process of repeatedly executing a block of code until a specific condition is met. It allows you to automate repetitive tasks & solve complex problems efficiently. C programming provides three types of loops for iteration: the for loop, the while loop, & the do-while loop. Each loop has its own syntax & use case, allowing you to control the flow of program execution based on different conditions. Iteration is a fundamental concept in programming that enables you to process arrays, traverse data structures, & perform calculations repeatedly.

Example 

#include <stdio.h>


int main() {
    int sum = 0;
    
    for (int i = 1; i <= 10; i++) {
        sum += i;
    }
    
    printf("The sum of the first 10 natural numbers is: %d", sum);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output

The sum of the first 10 natural numbers is: 55


In this code : 

  • In this example, we use a for loop to iterate from 1 to 10. The loop variable i starts at 1 & is incremented by 1 in each iteration until it reaches 10.
     
  • Inside the loop, we add the current value of i to the sum variable using the += operator. This accumulates the sum of the numbers from 1 to 10.
     
  • After the loop finishes, we print the final value of sum, which represents the sum of the first 10 natural numbers.

Types of Iteration Statements in Programming

  1. For Loop
  2. While Loop
  3. Do-While Loop
  4. Foreach Loop (in some languages like Python, Java, etc.)


Now, we know what iteration is, let’s discuss methods to achieve this with the help of different examples : 

For Loop

The for loop is one of the most commonly used iteration structures in C programming. It provides a concise way to write loops with a specific number of iterations. The syntax of the for loop consists of three parts: initialization, condition, & increment/decrement.

The general syntax of a for loop is :

for (initialization; condition; increment/decrement) {
    // code block to be executed
}
You can also try this code with Online C Compiler
Run Code


This syntax has : 

1. Initialization: This is where you initialize a loop counter variable. It is executed only once at the beginning of the loop.
 

2. Condition: This is a boolean expression that is evaluated before each iteration. If the condition is true, the loop continues; otherwise, the loop terminates.
 

3. Increment/Decrement: This part is executed after each iteration of the loop. It is used to update the loop counter variable.
 

Let’s see a simple example that shows the usage of a for loop to print the numbers from 1 to 5:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output

1 2 3 4 5


In this example, the loop counter variable `i` is initialized to 1. The loop continues as long as `i` is less than or equal to 5. After each iteration, `i` is incremented by 1 using the `i++` statement. The `printf` statement inside the loop prints the value of `i` followed by a space.

When to use: The for loop is useful when you know the exact number of iterations are required like, iterating over arrays or performing a specific number of repetitions.

The explanation of the for loop looks good to me. Let's move on to the next heading.

While Loop

The while loop is another fundamental iteration structure in C language. It allows you to repeat a block of code as long as a specified condition is true. The loop continues to execute until the condition becomes false.

The syntax of a while loop is:

while (condition) {
    // code block to be executed
}

 

The `condition` is a boolean expression that is evaluated before each iteration. If the condition is true, the code block inside the loop is executed. This process repeats until the condition becomes false.

Example that shows the usage of a while loop to calculate the sum of numbers from 1 to 10:

#include <stdio.h>

int main() {
    int sum = 0;
    int i = 1;
    
    while (i <= 10) {
        sum += i;
        i++;
    }
    
    printf("Sum of numbers from 1 to 10: %d", sum);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output:

Sum of numbers from 1 to 10: 55


In this example, we initialize a variable `sum` to store the running total & a loop counter variable `i` to 1. The while loop continues as long as `i` is less than or equal to 10. Inside the loop, we add the current value of `i` to `sum` using the `+=` operator & then increment `i` by 1.

After the loop finishes, the final value of `sum` is printed, which is the sum of numbers from 1 to 10.

When to use : The while loop is useful when you don't know the exact number of iterations needed & the loop continuation depends on a specific condition being true.

Great! Let's move on to the next heading.

Do-While Loop

The do-while loop is similar to the while loop, but with a slight difference in the order of execution. In a do-while loop, the code block is executed at least once before checking the condition. The loop continues to execute as long as the condition remains true.

The syntax of a do-while loop is:

do {
    // code block to be executed
} while (condition);


The code block inside the loop is executed first, & then the `condition` is evaluated. If the condition is true, the loop repeats. If the condition is false, the loop terminates.

Let’s discuss an example that shows the usage of a do-while loop to prompt the user for input until a specific value is entered:

#include <stdio.h>


int main() {
    int number;
    
    do {
        printf("Enter a number (enter 0 to exit): ");
        scanf("%d", &number);
        printf("You entered: %d\n", number);
    } while (number != 0);
    
    printf("Exiting the loop.");
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output

Enter a number (enter 0 to exit): 5
You entered: 5
Enter a number (enter 0 to exit): 3
You entered: 3
Enter a number (enter 0 to exit): 0
You entered: 0
Exiting the loop.


In this example, the do-while loop prompts the user to enter a number using `printf` & `scanf`. The entered number is then printed back to the user. The loop continues to prompt for input until the user enters the value 0.

When to use : The do-while loop is useful when you want to execute the code block at least once, regardless of the initial condition. It is commonly used for menu-driven programs or scenarios where you need to process user input repeatedly until a specific condition is met.

Iteration Statements across Different Languages

Iteration statements, also known as loops, are used to repeat a block of code multiple times. Different programming languages offer similar constructs with slight variations in syntax. Below are examples of common iteration statements in popular programming languages:

For Loop

Java

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

 

C

for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

 

Python

for i in range(5):  # Iterates from 0 to 4
    print(i)

While Loop

Java

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

 

C

int i = 0;
while (i < 5) {
    printf("%d\n", i);
    i++;
}

 

Python

i = 0
while i < 5:
    print(i)
    i += 1

Do-While Loop

 

Java

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);

 

C

int i = 0;
do {
    printf("%d\n", i);
    i++;
} while (i < 5);

 

Python: (Python doesn’t have a direct do-while loop, but similar behavior can be achieved using a while loop with a break condition.)

i = 0 
while True: 
	print(i) 
	i += 1 
	if i >= 5: 
		break

Foreach Loop

C: (C doesn’t have a native foreach loop, but similar functionality can be achieved using a for loop.)

int array[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    printf("%d\n", array[i]);
}

 

Java

int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
    System.out.println(element);
}

 

Python

for element in [1, 2, 3, 4, 5]:
    print(element)

Frequently Asked Questions

What is the difference between a for loop & a while loop?

A for loop is ideal for a known number of iterations, such as iterating arrays or repeated tasks, with concise syntax for initialization, condition, and updates. A while loop suits uncertain iterations, continuing based on a condition, offering flexibility for complex logic.

Can you have an infinite loop in C programming?

Yes, it is possible to have an infinite loop in C programming if the loop condition never becomes false. This can happen if the loop condition is always true or if the loop counter is not properly updated. Infinite loops can cause a program to hang or consume excessive system resources.

What is the purpose of the break statement in loops?

The break statement is used to prematurely exit a loop. When encountered inside a loop, the break statement immediately terminates the loop & transfers the program control to the next statement after the loop. It is often used in combination with conditional statements to exit a loop based on certain conditions.

Conclusion

In this article, we have learned about iteration in C language & discussed the different types of loops available. We covered the for loop, which is used when the number of iterations is known; the while loop, which is used when the loop continuation depends on a specific condition; & the do-while loop, which ensures that the code block is executed at least once before checking the condition. We also provided examples to show the usage of each loop type.

Live masterclass