Back to C Programming
2025-12-297 min read

For loops (C Programming)

Learn For loops (C Programming) step by step with clear examples and exercises.

Why This Matters

For loops are an essential tool in C programming, enabling efficient and effective handling of repetitive tasks such as iterating over arrays, performing calculations, and tackling various programming challenges. Mastering for loops will empower you to write robust, well-structured C programs, prepare for coding interviews, and address real-world problems with ease.

Prerequisites

Before diving into the intricacies of for loops, it is crucial that you have a strong foundation in the following concepts:

  1. Basic C syntax: variables, data types, operators, control structures (if-else statements)
  2. Understanding arrays and pointers in C
  3. Comprehension of iterators and indexing
  4. Proficiency with arithmetic operations like addition, subtraction, multiplication, and division
  5. Familiarity with using functions such as printf() and scanf() for input/output operations
  6. Experience with basic file I/O operations (optional but recommended)

Core Concept

A for loop consists of three primary components: initialization, condition check, and iteration. The general syntax is as follows:

for (initialization; condition; increment/decrement) {
// code block to be executed
}
  1. Initialization: This part initializes the loop counter or iterator variable with a starting value.
  2. Condition: The condition checks if the loop should continue executing. If the condition is true, the loop continues; otherwise, it terminates.
  3. Iteration: After each iteration, this part updates the loop counter to move towards the end of the loop or reset it for a new iteration.

Example 1: Printing numbers from 1 to 10

Let's examine a simple example that uses a for loop to print numbers from 1 to 10:

#include <stdio.h>

int main() {
int i;
for (i = 1; i <= 10; ++i) {
printf("%d\n", i);
}
return 0;
}

In this example, the loop initializes i to 1, checks if i is less than or equal to 10 (condition), and increments i by 1 after each iteration. The printf function inside the loop prints the current value of i.

Example 2: Iterating over an array

Here's a more complex example that demonstrates how for loops can be used to iterate over arrays:

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

In this example, the loop initializes i to 0, checks if i is less than 5 (condition), and increments i by 1 after each iteration. The loop iterates over the array arr, printing each element on a separate space-separated line.

Worked Example

Let's consider a more complex example that calculates the factorial of a number using a for loop:

#include <stdio.h>

int main() {
int n, fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);

// Calculate factorial using for loop
for (int i = 1; i <= n; ++i) {
fact *= i;
}

printf("Factorial of %d is %d\n", n, fact);
return 0;
}

In this example, the user is prompted to enter a positive integer. The for loop initializes i to 1 and checks if i is less than or equal to the entered number (condition). Inside the loop, fact is multiplied by the current value of i. After the loop finishes, the factorial is printed on the console.

Common Mistakes

  1. Forgetting to initialize the loop counter: This can lead to undefined behavior or runtime errors.
  2. Incorrect condition check: If the condition is not properly set, the loop may not execute the desired number of times or may run indefinitely (infinite loop).
  3. Not updating the loop counter correctly: Failing to increment or decrement the loop counter as needed can cause the loop to terminate prematurely or continue indefinitely.
  4. Using a for loop when a while loop would be more appropriate: While loops offer more flexibility and may be better suited for certain situations, such as iterating over an unbounded collection or handling infinite loops with break statements.
  5. Misunderstanding the order of operations within the initialization, condition, and iteration parts of the for loop. Be aware that any variables declared inside the initialization part will only be accessible within the for loop.
  6. Failing to consider edge cases: Ensure your for loops handle all possible input scenarios, such as empty arrays or invalid user inputs.
  7. Not properly handling memory allocation when using pointers within for loops. Always ensure that memory is allocated and deallocated appropriately.
  8. Incorrectly declaring multiple variables within the initialization part of a for loop: To declare multiple variables, use separate statements or enclose them in curly braces ({}).
  9. Failing to account for overflow or underflow when working with large numbers or iterating over large arrays. Use appropriate data types and consider using long long int or unsigned long long int for larger values.
  10. Neglecting to handle negative numbers or zero when calculating factorials, as demonstrated in the worked example.

Practice Questions

  1. Write a C program that prints the sum of all even numbers between 1 and 50 using a for loop.
  2. Write a C program that finds the second largest number in an array of integers using a for loop.
  3. Write a C program that calculates the Fibonacci sequence up to the nth term, where n is entered by the user, using a for loop.
  4. Modify the factorial example provided earlier to handle negative numbers and calculate the result as 1 (0! = 1) if the input number is 0 or less.
  5. Write a C program that calculates the sum of the elements in an array using a for loop, assuming the array size is passed as an argument to the main function.
  6. Write a C program that finds the smallest and largest numbers in an array using a for loop.
  7. Write a C program that reverses the order of the elements in an array using a for loop.
  8. Write a C program that calculates the product of all numbers in an array using a for loop.
  9. Write a C program that finds the average of the numbers in an array using a for loop.
  10. Write a C program that sorts an array of integers in ascending order using a for loop and bubble sort algorithm.

FAQ

What happens if I forget to initialize the loop counter in a for loop?

  • If you forget to initialize the loop counter, the behavior of your program may be undefined, leading to runtime errors or unexpected results.

Can I use a for loop to iterate over an array in reverse order?

  • Yes, you can modify the initialization and increment/decrement parts of the for loop to achieve this. For example:
for (int i = arrSize - 1; i >= 0; --i) {
// code block to be executed
}

How can I break out of a for loop early?

  • You can use the break statement to exit a for loop prematurely. The loop will terminate immediately, and program execution continues with the next statement following the loop.

What is the difference between a for loop and a while loop in C?

  • A for loop provides a more concise syntax for iterating over a specific range of values, whereas a while loop offers more flexibility and can be used to handle infinite loops or situations where the number of iterations is not known beforehand.

How do I declare multiple variables within the initialization part of a for loop?

  • To declare multiple variables within the initialization part of a for loop, use separate statements or enclose them in curly braces ({}).

Can I use a for loop to iterate over strings in C?

  • Strings in C are treated as arrays of characters, so you can use a for loop to iterate over each character in the string:
char str[20] = "Hello, World!";
for (int i = 0; i < strlen(str); ++i) {
printf("%c", str[i]);
}

How can I use a for loop to perform multiple operations on an array element at each iteration?

  • You can use compound statements (curly braces {}) within the for loop to group multiple operations:
for (int i = 0; i < arrSize; ++i) {
// Perform multiple operations on arr[i]
arr[i] *= 2;
arr[i] += 5;
}

How can I use a for loop to iterate over two arrays simultaneously?

  • You can use nested for loops or pointers to iterate over two arrays at the same time:
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {6, 7, 8, 9, 10};
for (int i = 0; i < 5; ++i) {
// Perform operations on arr1[i] and arr2[i]
arr1[i] += arr2[i];
}

By understanding the core concepts of for loops, you'll be well-equipped to tackle a wide variety of C programming challenges with confidence. Happy coding!