C_Programming_Loops_Presentation and fme
C_Programming_Loops_Presentation and fme
• Example:
• for (int i = 1; i <= 5; i++) {
• printf("%d ", i);
• }
while Loop
• Syntax:
• while (condition) {
• // code to execute
• }
• Example:
• int i = 1;
• while (i <= 5) {
• printf("%d ", i);
do-while Loop
• Syntax:
• do {
• // code to execute
• } while (condition);
• Example:
• int i = 1;
• do {
• printf("%d ", i);
Key Differences
• Feature | for loop | while loop | do-while
loop
• -------------|-----------|------------|----------------
• Entry check | Yes | Yes | No
• Exit check | Yes | Yes | After 1st run
• Use case | Known iterations | Unknown
iterations | At least one execution
Use Case Examples
• - for loop: Counting, iterating over arrays
• - while loop: Reading input until a condition is
met
• - do-while loop: Menu-driven programs
Common Errors
• - Infinite loops (missing increment or condition
always true)
• - Off-by-one errors
• - Using '=' instead of '==' in conditions
Conclusion
• - Loops simplify repetitive tasks in C
• - Choose the loop based on your use case
• - Practice helps in mastering their differences
and applications