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 1: while and do-while

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

The Power of Repetition

Computers are great at doing boring tasks millions of times without getting tired. Loops allow you to write a few lines of code that can run forever if needed.

1. The while Loop (Entry-Controlled)

The most basic loop. The condition is checked before the body runs. If the condition is false at the very start, the code inside the loop never runs once.

int i = 1;
while (i <= 5) {
    printf("Iteration %d\n", i);
    i++; // CRITICAL: Increment the counter!
}

2. The do-while Loop (Exit-Controlled)

The condition is checked after the body runs. This means the code inside is guaranteed to run at least once, no matter what the condition is. This is perfect for menus where you want to show the options at least once before checking if the user wants to quit.

int pin;
do {
    printf("Enter PIN: ");
    scanf("%d", &pin);
} while (pin != 1234);

The Three Components of a Loop

Every successful loop needs three things:

  1. Initialization: Setting up the starting state (int count = 0;).
  2. Condition: The test that determines when to stop (count < 10;).
  3. Update Step: Changing the state so that the condition eventually becomes false (count++;).

Avoiding the "Infinite Loop"

An infinite loop is a bug where the condition never becomes false. This usually happens if you forget the update step or have a logical error. Your program will "freeze" and consume 100% of your CPU until you force-quit it (Ctrl+C in terminal).

while(1) is a common way to create an intentional infinite loop, often used in embedded systems or server programs that should run until the machine is turned off.