Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Looping Part 2: The for Loop Masterclass

Lesson 14 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

The Professional's Choice

The for loop is the most popular loop among C programmers because it bundles initialization, condition, and update into one concise, easy-to-read line.

Syntax

for (initialization; condition; update) {
    // block of code to run
}

Execution Flow - Exactly how it works:

  1. Initialization runs only once at the very beginning.
  2. Condition is checked. If it's False, the loop ends immediately.
  3. If the condition is True, the Body of the loop is executed.
  4. The Update step runs (e.g., i++).
  5. Go back to Step 2.

Common Patterns

  • Counting Up: for (int i = 0; i < 10; i++)
  • Counting Down: for (int i = 10; i > 0; i--)
  • Stepping: for (int i = 0; i < 100; i += 5) (0, 5, 10, 15...)
  • Multiple variables: for (i = 0, j = 10; i < j; i++, j--)

Nested for Loops

This is how we handle 2D data like grids or images. The outer loop handles rows, and the inner loop handles columns.

for (int i = 1; i <= 3; i++) {       // Outer
    for (int j = 1; j <= 3; j++) {   // Inner
        printf("(%d,%d) ", i, j);
    }
    printf("\n");
}

The Empty For Loop

All parts of the for statement are optional.

  • for(;;) is an infinite loop (same as while(1)).
  • for(int i=0; i<10;) is valid as long as you update i inside the body.
In modern C (C99 and later), you should always declare the loop variable inside the for statement: for (int i = 0; ...). This is safer because the variable i is automatically destroyed when the loop ends, preventing you from accidentally using it elsewhere.