Understanding Loops in C
Programming
Loops are a foundational concept in C programming. They
enable repetitive execution of code blocks. Loops are essential
for efficient and concise code. This presentation will provide a
comprehensive guide to understanding and using loops
effectively.
Why Use Loops?
Automate repetitive tasks Efficiency
Automate data processing. Loops iterate through Consider printing numbers 1 to 10. Without loops,
data structures like arrays and lists. Implement it's tedious. The concise equivalent uses a simple
algorithms needing repetition. This includes for loop.
searching and sorting. Without Loop:
printf("1\n"); printf("2\n"); ...
printf("10\n");
With Loop:
for (int i = 1; i <= 10; i++)
{ printf("%d\n", i); }
The for Loop
Initialization
Executed once at the beginning.
Condition
Evaluated before each iteration. The loop continues if true.
Increment/Decrement
Executed after each iteration.
for (int i = 0; i < 5; i++) {
printf("Iteration: %d\n", i);
}
The code prints 0 to 4. for loops provide definite iteration and a clear
structure for counting.
The while Loop
Initialization
Done before the while loop.
2
Condition
Evaluated before each iteration.
1
3 Increment/Decrement
Done within the loop body.
int i = 0;
while (i < 5) {
printf("Iteration: %d\n", i);
i++;
}
The do-while Loop
Condition
Evaluated after each iteration.
Guaranteed Execution
Ensures at least one execution.
int i = 0;
do {
printf("Iteration: %d\n", i);
i++;
} while (i < 5);
The code prints 0 to 4. The do-while loop is a post-test loop. It
guarantees at least one execution. Use it for input validation where you
prompt the user until valid input is provided.
Loop Control: break
Terminates
The loop ends prematurely.
Transfers Control
Goes to the next statement.
for (int i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d\n", i);
}
This code prints 0 to 4. A common use is exiting a loop based
on a condition or error.
Loop Control: continue
Skips Iteration
Skips current iteration.
Proceeds
Goes to the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
printf("%d\n", i);
}
The code prints only odd numbers. A common use is skipping specific
cases within a loop.
Nested Loops
One loop inside Multi-dimensional
another data
Nested loops are useful for processing multi-dimensional data
like matrices.