Faster, better AI-powered code reviews. Start your free trial!  
Faster, better AI-powered code reviews.
Start your free trial!

Get high quality AI code reviews

C For Loop: C Explained

Table of Contents

The C for loop is a fundamental programming tool in the C language, as it allows for a given set of instructions to be iterated several times. This can greatly reduce the amount of code that needs to be written, and it can also be used for repetitive operations like searching for specific values in a database or printing out a list of characters on the screen. In this article, we will take a closer look at what a C for loop is, how to write one, understand the syntax of a C for loop, its benefits, common pitfalls, practical examples and further resources on the subject.

What is a C For Loop?

A C for loop is a structure used to iterate through a set of code several times. It can also be referred to as a “repeating loop” or “iterative loop”. In other words, every time the loop is executed, it repeats until its condition stops being true. The syntax of the C for loop indicates how many times the loop should iterate and which lines of code should be repeated.

In the loop structure for C, the initialization statement is executed once only before the loop begins, and then the condition turns the loop ‘on’ and ‘off’. If the condition is true, the loop body gets executed. After each iteration is complete, the increment/decrement statement will get executed and the condition gets tested again. The following diagram explains this well:

For Loop Diagram

How to Write a C For Loop

When writing a C for loop, you need to include three parts: an initializing statement, a condition statement and an increment/decrement statement. The syntax for a for loop is as follows:

for (initializing statement; condition statement; increment/decrement statement) {    // Body of the loop}

The initialization statement values are set up once, before the loop starts to run. This usually involves declaring and setting an initial value for a counting variable. In the condition statement, you specify the condition that must be met in order for the loop to keep running. If the condition is no longer true, the loop will stop executing. Finally, the increment/decrement statement is used to update the counting variable at the end of each iteration. This way, it keeps track of how many times the loop has been executed.

Understanding the Syntax of a C For Loop

As previously mentioned, there are three main parts to the syntax of a C for loop – the initialization statement, condition statement and increment/decrement statement, all of which have their own specific syntax rules.

  • The Initialization Statement: This part of the syntax sets up the initial value for a counting variable before the loop runs. Generally, this statement has two parts – declaring a variable and setting an initial value.
  • int i = 0;
  • The Condition Statement: This is where you specify when the loop should stop executing. A true condition will keep the loop running until it’s no longer true.
  • i < 10;
  • The Increment/Decrement Statement: This part of the syntax keeps track of how many times the loop has been executed by updating the counting variable. This is usually done through incrementing or decrementing.
  • i++;

For example, you can combine all three parts into one for loop like this:

for (int i = 0; i < 10; i++) {    // Body of the loop}

Benefits of Using C For Loops

  • For loops can save time as they allow you to repeat certain instructions without having to rewrite them every time.
  • For loops can improve readability as they are compact and easy to parse.
  • For loops can be used to perform more complicated operations than a single instruction can achieve.
  • For loops can be set up to run certain instructions only when certain conditions are met.

Common Pitfalls of C For Loops

  • If your for loop does not have an exit condition properly set up, it can cause an infinite loop.
  • If you forget to initialize your counting variable in the initialization statement, you won’t get any output from your loop.
  • If you forget to increment or decrement your counting variable in the increment/decrement statement, you will end up with an infinite loop.
  • If you don’t use braces {} inside your for loop to contain all lines of code that should be repeated in each iteration, only one line will be repeated.

Examples of C For Loops in Action

Below are some examples of how C for loops can be used in programming projects:

  • Printing characters on the screen: You can use a for loop to print out each character in a string on a new line by running it through a loop that increments through each letter in the string.
  • #include <stdio.h>#include <string.h>  // Required for string manipulation functions like 'strlen' int main() {    char str[] = "Hello World!";  // Source string    // Loop through each character in string       for (int i = 0; i < strlen(str); i++) {  // Using 'strlen' function to find length of string      printf("%c\n", str[i]);              // Print out each character in new line       }    return 0;  // Return success            }  
  • Finding values in an array: You can use a forloop to iterate through an array until it finds a specific value. For example:
  • #include <stdio.h>  int main () {    int A[] = {1, 2, 3, 4, 5}; // Source array    int searchValue = 3;       // Value to search        // Loop through each element in array     for (int i = 0; i < 5; i++) {       // Length of array 'A' is 5       if(A[i] == searchValue) {        // Check if each element is equal to 'searchValue'          printf("Found at position %d\n", i + 1);    // Print position if value found       }    }     return 0;      // Return success     }    
  • Generating output with user input: You can use a for loop to get user input and generate specific output based on this input.
  • #include <stdio.h>  int main () {    int n;              // Variable to store user input        printf("Enter number of stars: ");    scanf("%d", &n);    // Use 'scanf' function to get user input as integer and store in 'n'     printf("Printing stars...\n");   // Loop 'n' number of times and print *  each time      for (int i = 0; i < n; i++) {       // Set up 'for' loop to repeat until iterator 'i' reaches 'n'           printf("*");                    // this line will be executed 'n' number of times   }     printf("\n");                     // at end of loop, print newline character   return 0;                        // return success   																						     }     

Resources for Further Learning on C For Loops

If you’d like to go into more detail with For loops in C, we highly recommend checking out these resources:

Nisha Kumari

Nisha Kumari

Nisha Kumari, a Founding Engineer at Bito, brings a comprehensive background in software engineering, specializing in Java/J2EE, PHP, HTML, CSS, JavaScript, and web development. Her career highlights include significant roles at Accenture, where she led end-to-end project deliveries and application maintenance, and at PubMatic, where she honed her skills in online advertising and optimization. Nisha's expertise spans across SAP HANA development, project management, and technical specification, making her a versatile and skilled contributor to the tech industry.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Related Articles

Get Bito for IDE of your choice