Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Loops in C Language

Introduction

Loops are fundamental control structures in programming that allow you to execute a block of code multiple times. In the C programming language, there are three main types of loops:

  • While Loop
  • Do-While Loop
  • For Loop

While Loop

The while loop continues to execute a block of code as long as a specified condition is true.

Syntax

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

Example

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

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once.

Syntax

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

Example

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

For Loop

The for loop is a more compact form of loop that combines initialization, condition-checking, and increment/decrement in a single line.

Syntax

for (initialization; condition; increment/decrement) {
     // code block to be executed
}

Example

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

Nested Loops

Loops can be nested within other loops. This is useful for iterating over multi-dimensional arrays or performing complex iterations.

Example

for (int i = 0; i < 3; i++) {
     for (int j = 0; j < 3; j++) {
         printf("i = %d, j = %d\n", i, j);
     }
}
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2

Conclusion

Understanding loops allows you to write more efficient and powerful programs. Whether you need to perform repetitive tasks or iterate over data structures, loops are an essential tool in your programming arsenal.