LOOPS IN
C PROGRAMMING
Discussion :
1. Introduction
2. Types of Loop
3. Nested Loop
4. Choosing the Right Loop
5. Common mistakes
6. Conclusion
Introduction to Loops:
• Loops are essential control structures that allow repetitive execution of code.
• They help automate tasks and handle repetitive operations efficiently.
‘for’ Loop
‘while’ Loop Types of Loop
‘do-while’ Loop
The ‘for’ Loop
• In this example, the outer loop iterates over rows, and the inner loop
iterates over columns.
• Each iteration of the inner loop prints the current row and column indices.
FEB Syntex OCT
JAN for (initialization; condition;
M A R increment/decrement) M AY
{ // code to be executed repeatedly }
Example of a ‘for’ Loop
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Iteration: %d\n", i);
}
return 0;
Output: }
Lorna Alvarado
The ‘while’ Loop
• Used when the number of iterations is not known in advance.
• The condition is checked before each iteration.
Syntex
while (condition) {
// code to be executed repeatedly
}
Example of a ‘while’ Loop
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("Iteration: %d\n", i);
i++; Output:
}
return 0;
}
The ‘do-while’ Loop
• Similar to while loop but guarantees at least one execution
of the loop body.
• The condition is checked after each iteration.
Syntex
do {
// code to be executed repeatedly
} while (condition);
Example of a ‘do-while’ Loop
#include <stdio.h>
int main() {
int i = 0;
do {
Output:
printf("Iteration: %d\n", i);
i++;
} while (i < 5);
return 0;
}
Nested Loop:
• Nested loops are loops within loops.
• They are used when you need to perform a repetitive task within another
repetitive task.
• Commonly used for tasks involving multi-dimensional arrays or grids.
Example of a Nested Loop
#include <stdio.h>
int main() {
int rows = 3;
int cols = 3;
// Outer loop for rows
for (int i = 0; i < rows; i++) {
// Inner loop for columns Output:
for (int j = 0; j < cols; j++) {
printf("(%d, %d) ", i, j);
}
printf("\n");
}
return 0; • In this example, the outer loop iterates over rows, and the inner loop
} iterates over columns.
• Each iteration of the inner loop prints the current row and column indices.
Choosing the Right Loop
• Use for when you know the number of iterations.
• Use while when the condition depends on external factors.
• Use do-while when you want the loop body to execute at least once.
Common mistakes
• Forgetting to update the loop variable.
• Infinite loops (ensure proper termination conditions).
Conclusion
• Loops are fundamental tools for efficient programming.
• Mastering loops is crucial for any C programmer.
THANK YOU