Loops in C Programming
Loops are control structures that allow you to execute a block of code repeatedly based on a condition. They are essential for automating repetitive tasks, processing collections of data, and implementing algorithms that require iteration.
Key Takeaways
- C provides three main types of loops:
for
,while
, anddo-while
- Loops help eliminate code repetition and make programs more efficient
- Loop control statements like
break
andcontinue
provide additional flow control - Infinite loops occur when the termination condition is never met
- Nested loops allow for complex iteration patterns like matrix traversal
Why Do We Need Loops?
Imagine you need to print numbers from 1 to 100, or process each element in an array with 1000 items. Writing the same code over and over would be tedious and error-prone. Loops solve this problem by allowing you to execute code repeatedly while changing certain variables with each iteration.
Without Loops
1printf("%d\n", 1);2printf("%d\n", 2);3printf("%d\n", 3);4// ... and so on until 1005printf("%d\n", 100);
Repetitive, error-prone, and hard to maintain
With Loops
1for (int i = 1; i <= 100; i++) {2 printf("%d\n", i);3}
Concise, maintainable, and scalable
Types of Loops in C
C provides three main types of loops, each with its own syntax and use cases:
Loop Type | When to Use | Condition Check |
---|---|---|
for | When the number of iterations is known beforehand | Before each iteration |
while | When iterations depend on a condition being true | Before each iteration |
do-while | When code must execute at least once | After each iteration |
The for Loop
The for
loop is ideal when you know exactly how many times you want to execute a block of code. It combines the initialization, condition check, and update in a single line, making the code more compact and readable.
Basic Syntax
1for (initialization; condition; update) {2 // Code to be executed in each iteration3}
The loop components work as follows:
- Initialization: Executed once before the loop begins; typically sets up a counter variable
- Condition: Evaluated before each iteration; if true, the loop continues
- Update: Executed after each iteration; typically increments or decrements the counter
The initialization, condition, and update expressions are all optional. You can create an infinite loop withfor(;;)
but make sure to include a way to exit the loop inside its body.
Example: Printing Numbers
1#include <stdio.h>23int main() {4 // Print numbers from 1 to 105 for (int i = 1; i <= 10; i++) {6 printf("%d ", i);7 }8 printf("\n");910 return 0;11}1213// Output: 1 2 3 4 5 6 7 8 9 10
Example: Calculating Sum
1#include <stdio.h>23int main() {4 int sum = 0;56 // Calculate sum of numbers from 1 to 1007 for (int i = 1; i <= 100; i++) {8 sum += i;9 }1011 printf("Sum of numbers from 1 to 100: %d\n", sum);1213 return 0;14}1516// Output: Sum of numbers from 1 to 100: 5050
Variations of for Loop
Multiple Initializations or Updates
1for (int i = 0, j = 10; i < j; i++, j--) {2 printf("i = %d, j = %d\n", i, j);3}
Omitting Sections
1int i = 0;2for (; i < 5; ) {3 printf("%d ", i);4 i++; // Update inside the loop body5}
Decreasing Loop
1for (int i = 10; i > 0; i--) {2 printf("%d ", i);3}
The while Loop
The while
loop executes a block of code as long as a specified condition is true. It's ideal when you don't know in advance how many iterations will be needed.
Basic Syntax
1while (condition) {2 // Code to be executed as long as condition is true3}
Common Mistake with while Loops
Always ensure that the condition in a while
loop will eventually become false, or include a break
statement to prevent an infinite loop.
Example: Reading Input Until a Condition
1#include <stdio.h>23int main() {4 int number;5 int sum = 0;67 printf("Enter positive numbers (enter a negative number to stop):\n");89 while (1) { // Infinite loop, will break when condition is met10 printf("Enter a number: ");11 scanf("%d", &number);1213 if (number < 0) {14 break; // Exit the loop if number is negative15 }1617 sum += number;18 }1920 printf("Sum of all positive numbers entered: %d\n", sum);2122 return 0;23}
Example: Processing Array Elements
1#include <stdio.h>23int main() {4 int numbers[] = {10, 20, 30, 40, 50};5 int size = sizeof(numbers) / sizeof(numbers[0]);6 int i = 0;78 while (i < size) {9 printf("%d: %d\n", i, numbers[i]);10 i++;11 }1213 return 0;14}1516// Output:17// 0: 1018// 1: 2019// 2: 3020// 3: 4021// 4: 50
When to Choose a while Loop
Use while
loops when the number of iterations is not known in advance, such as when processing user input, reading from files, or traversing linked data structures.
The do-while Loop
The do-while
loop is similar to the while
loop, but with one key difference: the code block is executed at least once before the condition is evaluated. This makes it useful when you want to ensure that certain code runs at least once.
Basic Syntax
1do {2 // Code to be executed at least once3} while (condition);
Notice the semicolon at the end of the do-while
loop. This is required and is a common source of syntax errors.
Example: Menu System
1#include <stdio.h>23int main() {4 int choice;56 do {7 printf("\n--- Menu ---\n");8 printf("1. Option One\n");9 printf("2. Option Two\n");10 printf("3. Option Three\n");11 printf("4. Exit\n");12 printf("Enter your choice (1-4): ");13 scanf("%d", &choice);1415 switch (choice) {16 case 1:17 printf("You selected Option One\n");18 break;19 case 2:20 printf("You selected Option Two\n");21 break;22 case 3:23 printf("You selected Option Three\n");24 break;25 case 4:26 printf("Exiting program...\n");27 break;28 default:29 printf("Invalid option! Please try again.\n");30 }3132 } while (choice != 4);3334 return 0;35}
In this example, the menu is displayed and processed at least once. The loop continues until the user selects option 4 to exit.
Example: Input Validation
1#include <stdio.h>23int main() {4 int number;56 do {7 printf("Enter a positive number: ");8 scanf("%d", &number);910 if (number <= 0) {11 printf("Error: Number must be positive.\n");12 }1314 } while (number <= 0);1516 printf("You entered: %d\n", number);1718 return 0;19}
This example ensures that the user enters a positive number. The prompt and validation occur at least once, and the loop continues until a valid input is provided.
Nested Loops
Nested loops are loops inside other loops. They're particularly useful for working with multi-dimensional data structures like arrays, matrices, or grids. The inner loop completes all its iterations for each single iteration of the outer loop.
Example: Printing a Pattern
1#include <stdio.h>23int main() {4 int rows = 5;56 for (int i = 1; i <= rows; i++) {7 // Inner loop to print stars8 for (int j = 1; j <= i; j++) {9 printf("* ");10 }11 printf("\n");12 }1314 return 0;15}1617// Output:18// *19// * *20// * * *21// * * * *22// * * * * *
Example: Matrix Operations
1#include <stdio.h>23int main() {4 int matrix[3][3] = {5 {1, 2, 3},6 {4, 5, 6},7 {7, 8, 9}8 };9 int sum = 0;1011 // Calculate the sum of all elements in the matrix12 for (int i = 0; i < 3; i++) {13 for (int j = 0; j < 3; j++) {14 sum += matrix[i][j];15 printf("%d ", matrix[i][j]); // Print each element16 }17 printf("\n"); // Move to next row18 }1920 printf("\nSum of all matrix elements: %d\n", sum);2122 return 0;23}2425// Output:26// 1 2 327// 4 5 628// 7 8 929//30// Sum of all matrix elements: 45
Performance Considerations with Nested Loops
Nested loops multiply the number of iterations. A loop with n iterations containing a loop with m iterations results in n×m total iterations. This can impact performance with large datasets.
Loop Control Statements
C provides special statements to alter the normal flow of loops:
Statement | Purpose | Effect |
---|---|---|
break | Exit the current loop immediately | Terminates the innermost loop |
continue | Skip remaining code in current iteration | Jumps to the next iteration of the loop |
goto | Jump to a labeled statement | Can break out of nested loops (use sparingly) |
These statements will be covered in more detail in the Break and Continue tutorial.
Infinite Loops
An infinite loop is a loop that runs indefinitely because its exit condition is never met. While typically an error, they can be intentional when combined with a break condition inside the loop.
Common Ways to Create Infinite Loops
Using for
1for (;;) {2 // Infinite loop3 // Need break condition inside4}
Using while
1while (1) {2 // Infinite loop3 // Need break condition inside4}
Using do-while
1do {2 // Infinite loop3 // Need break condition inside4} while (1);
Warning: Unintentional infinite loops can cause programs to hang and consume system resources. Always ensure there's a way to exit the loop either through the condition check or a break
statement.
Example: Intentional Infinite Loop with Exit Condition
1#include <stdio.h>2#include <stdlib.h> // For exit() function34int main() {5 int num;67 printf("Enter 0 to exit the program.\n");89 while (1) { // Intentional infinite loop10 printf("Enter a number: ");11 scanf("%d", &num);1213 if (num == 0) {14 printf("Exiting program...\n");15 break; // Exit condition16 }1718 printf("You entered: %d\n", num);19 }2021 return 0;22}
Common Pitfalls and Best Practices
Off-by-One Errors
Errors in loop boundaries are among the most common mistakes. For example, when working with arrays:
1// INCORRECT - Accesses memory outside the array2int array[5]; // Indices 0-43for (int i = 1; i <= 5; i++) {4 array[i] = i; // Tries to access array[5], which is out of bounds5}67// CORRECT - Proper array indexing8int array[5]; // Indices 0-49for (int i = 0; i < 5; i++) {10 array[i] = i + 1; // Accesses array[0] to array[4]11}
Missing Update Expression
Forgetting to update the loop counter or condition will result in an infinite loop:
1// INCORRECT - Infinite loop2int i = 0;3while (i < 10) {4 printf("%d ", i);5 // Forgot to increment i6}78// CORRECT9int i = 0;10while (i < 10) {11 printf("%d ", i);12 i++; // Don't forget to update the counter13}
Best Practices
- Use
for
loops when the number of iterations is known - Use
while
ordo-while
when the termination condition depends on events inside the loop - Keep loops as simple and focused as possible
- Avoid modifying loop counters inside the loop body (except in special cases)
- Be careful with loop boundaries, especially when working with arrays
- Consider using
size_t
for array indices and loop counters dealing with sizes
Real-World Examples
Example: Finding Prime Numbers
1#include <stdio.h>2#include <stdbool.h>34bool isPrime(int num) {5 if (num <= 1) return false;6 if (num <= 3) return true;7 if (num % 2 == 0 || num % 3 == 0) return false;89 // Check for factors beyond 310 for (int i = 5; i * i <= num; i += 6) {11 if (num % i == 0 || num % (i + 2) == 0) {12 return false;13 }14 }1516 return true;17}1819int main() {20 int limit;2122 printf("Find prime numbers up to: ");23 scanf("%d", &limit);2425 printf("Prime numbers up to %d are:\n", limit);2627 for (int i = 2; i <= limit; i++) {28 if (isPrime(i)) {29 printf("%d ", i);30 }31 }32 printf("\n");3334 return 0;35}
Example: Calculating Fibonacci Sequence
1#include <stdio.h>23int main() {4 int n, first = 0, second = 1, next;56 printf("Enter the number of Fibonacci terms to generate: ");7 scanf("%d", &n);89 printf("Fibonacci Sequence:\n");1011 for (int i = 0; i < n; i++) {12 if (i <= 1) {13 next = i;14 } else {15 next = first + second;16 first = second;17 second = next;18 }19 printf("%d ", next);20 }21 printf("\n");2223 return 0;24}
Practice Exercises
Exercise 1: Sum of Digits
Write a program that calculates the sum of the digits of a given integer. For example, if the input is 12345, the output should be 1+2+3+4+5 = 15.
Hint: Use the modulo operator (%) to extract each digit, and a loop to process all digits.
Exercise 2: Multiplication Table
Create a program that displays a multiplication table for numbers 1 through 10. Use nested loops to generate the table.
Hint: The outer loop should iterate through the rows, and the inner loop through the columns.
Exercise 3: Factorial Calculator
Write a program that calculates the factorial of a number using a loop. The factorial of n (written as n!) is the product of all positive integers less than or equal to n.
Hint: Remember that 0! = 1 by definition, and be careful with integer overflow for large inputs.
Summary
Loops are essential control structures in C programming that allow you to execute blocks of code repeatedly. In this tutorial, you learned:
- The three main types of loops:
for
,while
, anddo-while
- How to choose the appropriate loop type based on your specific needs
- How to nest loops for more complex iteration patterns
- Common loop control statements and how to use them
- How to avoid common pitfalls like infinite loops and off-by-one errors
With loops, you can make your programs more efficient by eliminating code repetition and implementing sophisticated algorithms. In the next tutorial, you'll learn about Break and Continue statements, which provide more fine-grained control over loop execution.
Related Tutorials
Conditional Statements in C
Learn about if, if-else, and nested if statements in C programming.
Continue learning