Progress: 7 of 16 topics43%

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, and do-while
  • Loops help eliminate code repetition and make programs more efficient
  • Loop control statements like break and continue 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

c
1printf("%d\n", 1);
2printf("%d\n", 2);
3printf("%d\n", 3);
4// ... and so on until 100
5printf("%d\n", 100);

Repetitive, error-prone, and hard to maintain

With Loops

c
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 TypeWhen to UseCondition Check
forWhen the number of iterations is known beforehandBefore each iteration
whileWhen iterations depend on a condition being trueBefore each iteration
do-whileWhen code must execute at least onceAfter 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

c
1for (initialization; condition; update) {
2 // Code to be executed in each iteration
3}

The loop components work as follows:

  1. Initialization: Executed once before the loop begins; typically sets up a counter variable
  2. Condition: Evaluated before each iteration; if true, the loop continues
  3. 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

c
1#include <stdio.h>
2
3int main() {
4 // Print numbers from 1 to 10
5 for (int i = 1; i <= 10; i++) {
6 printf("%d ", i);
7 }
8 printf("\n");
9
10 return 0;
11}
12
13// Output: 1 2 3 4 5 6 7 8 9 10

Example: Calculating Sum

c
1#include <stdio.h>
2
3int main() {
4 int sum = 0;
5
6 // Calculate sum of numbers from 1 to 100
7 for (int i = 1; i <= 100; i++) {
8 sum += i;
9 }
10
11 printf("Sum of numbers from 1 to 100: %d\n", sum);
12
13 return 0;
14}
15
16// Output: Sum of numbers from 1 to 100: 5050

Variations of for Loop

Multiple Initializations or Updates

c
1for (int i = 0, j = 10; i < j; i++, j--) {
2 printf("i = %d, j = %d\n", i, j);
3}

Omitting Sections

c
1int i = 0;
2for (; i < 5; ) {
3 printf("%d ", i);
4 i++; // Update inside the loop body
5}

Decreasing Loop

c
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

c
1while (condition) {
2 // Code to be executed as long as condition is true
3}

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

c
1#include <stdio.h>
2
3int main() {
4 int number;
5 int sum = 0;
6
7 printf("Enter positive numbers (enter a negative number to stop):\n");
8
9 while (1) { // Infinite loop, will break when condition is met
10 printf("Enter a number: ");
11 scanf("%d", &number);
12
13 if (number < 0) {
14 break; // Exit the loop if number is negative
15 }
16
17 sum += number;
18 }
19
20 printf("Sum of all positive numbers entered: %d\n", sum);
21
22 return 0;
23}

Example: Processing Array Elements

c
1#include <stdio.h>
2
3int main() {
4 int numbers[] = {10, 20, 30, 40, 50};
5 int size = sizeof(numbers) / sizeof(numbers[0]);
6 int i = 0;
7
8 while (i < size) {
9 printf("%d: %d\n", i, numbers[i]);
10 i++;
11 }
12
13 return 0;
14}
15
16// Output:
17// 0: 10
18// 1: 20
19// 2: 30
20// 3: 40
21// 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

c
1do {
2 // Code to be executed at least once
3} 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

c
1#include <stdio.h>
2
3int main() {
4 int choice;
5
6 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);
14
15 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 }
31
32 } while (choice != 4);
33
34 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

c
1#include <stdio.h>
2
3int main() {
4 int number;
5
6 do {
7 printf("Enter a positive number: ");
8 scanf("%d", &number);
9
10 if (number <= 0) {
11 printf("Error: Number must be positive.\n");
12 }
13
14 } while (number <= 0);
15
16 printf("You entered: %d\n", number);
17
18 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

c
1#include <stdio.h>
2
3int main() {
4 int rows = 5;
5
6 for (int i = 1; i <= rows; i++) {
7 // Inner loop to print stars
8 for (int j = 1; j <= i; j++) {
9 printf("* ");
10 }
11 printf("\n");
12 }
13
14 return 0;
15}
16
17// Output:
18// *
19// * *
20// * * *
21// * * * *
22// * * * * *

Example: Matrix Operations

c
1#include <stdio.h>
2
3int main() {
4 int matrix[3][3] = {
5 {1, 2, 3},
6 {4, 5, 6},
7 {7, 8, 9}
8 };
9 int sum = 0;
10
11 // Calculate the sum of all elements in the matrix
12 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 element
16 }
17 printf("\n"); // Move to next row
18 }
19
20 printf("\nSum of all matrix elements: %d\n", sum);
21
22 return 0;
23}
24
25// Output:
26// 1 2 3
27// 4 5 6
28// 7 8 9
29//
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:

StatementPurposeEffect
breakExit the current loop immediatelyTerminates the innermost loop
continueSkip remaining code in current iterationJumps to the next iteration of the loop
gotoJump to a labeled statementCan 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

c
1for (;;) {
2 // Infinite loop
3 // Need break condition inside
4}

Using while

c
1while (1) {
2 // Infinite loop
3 // Need break condition inside
4}

Using do-while

c
1do {
2 // Infinite loop
3 // Need break condition inside
4} 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

c
1#include <stdio.h>
2#include <stdlib.h> // For exit() function
3
4int main() {
5 int num;
6
7 printf("Enter 0 to exit the program.\n");
8
9 while (1) { // Intentional infinite loop
10 printf("Enter a number: ");
11 scanf("%d", &num);
12
13 if (num == 0) {
14 printf("Exiting program...\n");
15 break; // Exit condition
16 }
17
18 printf("You entered: %d\n", num);
19 }
20
21 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:

c
1// INCORRECT - Accesses memory outside the array
2int array[5]; // Indices 0-4
3for (int i = 1; i <= 5; i++) {
4 array[i] = i; // Tries to access array[5], which is out of bounds
5}
6
7// CORRECT - Proper array indexing
8int array[5]; // Indices 0-4
9for (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:

c
1// INCORRECT - Infinite loop
2int i = 0;
3while (i < 10) {
4 printf("%d ", i);
5 // Forgot to increment i
6}
7
8// CORRECT
9int i = 0;
10while (i < 10) {
11 printf("%d ", i);
12 i++; // Don't forget to update the counter
13}

Best Practices

  • Use for loops when the number of iterations is known
  • Use while or do-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

c
1#include <stdio.h>
2#include <stdbool.h>
3
4bool 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;
8
9 // Check for factors beyond 3
10 for (int i = 5; i * i <= num; i += 6) {
11 if (num % i == 0 || num % (i + 2) == 0) {
12 return false;
13 }
14 }
15
16 return true;
17}
18
19int main() {
20 int limit;
21
22 printf("Find prime numbers up to: ");
23 scanf("%d", &limit);
24
25 printf("Prime numbers up to %d are:\n", limit);
26
27 for (int i = 2; i <= limit; i++) {
28 if (isPrime(i)) {
29 printf("%d ", i);
30 }
31 }
32 printf("\n");
33
34 return 0;
35}

Example: Calculating Fibonacci Sequence

c
1#include <stdio.h>
2
3int main() {
4 int n, first = 0, second = 1, next;
5
6 printf("Enter the number of Fibonacci terms to generate: ");
7 scanf("%d", &n);
8
9 printf("Fibonacci Sequence:\n");
10
11 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");
22
23 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, and do-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

Switch Statements in C

Multi-way decision making in C with switch statements.

Continue learning

Break and Continue Statements

Control the flow of loops and switch statements in C.

Continue learning