Loops in Programming Understanding repetition structures in programming
What are Loops? Definition: A loop allows executing a block of code repeatedly. Importance: Simplifies tasks requiring repetition.
Types of Loops Entry-controlled: for, while Exit-controlled: do-while
For Loop Syntax in C: for(initialization; condition; increment) { // code } Python: for i in range(5): print(i)
While Loop C Example: while(condition) { // code } Python Example: i = 0 while i < 5: print(i) i += 1
Do-While Loop (C only) Syntax: do { // code } while(condition); Executes code block at least once.
Nested Loops Example C Example: for(i=1;i<=3;i++) { for(j=1;j<=3;j++) { printf("%d %d", i, j); } } Python Example: for i in range(3): for j in range(3): print(i, j)
Common Loop Issues Infinite loops if condition never becomes false. Off-by-one errors in loop counters.
Summary Loops provide repetition in programs. Types: for, while, do-while, nested loops. Ensure termination conditions to avoid infinite loops.