C Tutorial

C While Loop

while repeats as long as a condition stays true. Check that the condition can become false.

Repeat while a test is true

A while loop checks a condition, runs a block, then checks again. As long as the condition is true, the block repeats. When the condition is false, C leaves the loop and continues with the next statement.

Something inside the loop must change the values the condition looks at. If nothing changes, the test never becomes false and the program does not stop.

A complete while program

This loop prints 1 through 5. n starts at 1. Each pass prints, then adds 1. Whenn becomes 6, the condition is false and the loop ends.

Example

#include <stdio.h>

int main(void) {
  int n = 1;
  while (n <= 5) {
    printf("%d\n", n);
    n = n + 1;
  }
  return 0;
}

Compile this in /c/try. Then change 5 to another small number. Keep the increment. A missing n = n + 1 is how beginners create an infinite loop.

The three parts you manage

  1. Set a starting value before the loop.
  2. Write a condition that can become false.
  3. Update that value inside the loop.

Forget step 3 and the condition stays true forever. Forget step 1 and the condition uses leftover memory. The for loop in the next chapter packs these three into one line. while leaves them visible, which is useful when the update is not a simple + 1.

do while runs the body first

A do / while loop runs the block once, then checks the condition. If the condition is true, it runs again. The body always executes at least once, even when the test starts false.

Example

#include <stdio.h>

int main(void) {
  int n = 1;
  do {
    printf("%d\n", n);
    n = n + 1;
  } while (n <= 3);
  return 0;
}

Notice the semicolon after while (n <= 3). A do / while needs that semicolon. A plain while does not.

When the body should run first

Use do / while when the first pass must happen before you know whether to continue: print a menu, then ask whether to show it again. Use plain while when you might need zero passes: process input only while there is input left.

Example

#include <stdio.h>

int main(void) {
  int n = 10;
  do {
    printf("ran once, n is %d\n", n);
  } while (n < 0);
  return 0;
}

n is 10, so n < 0 is false, but the message still prints. A plainwhile (n < 0) would print nothing.

while versus for

whilefor
Use whenYou wait on a conditionYou know the count
CounterYou set and update it yourselfInit, test, and step sit in one line
Zero passesYes, if the test starts falseYes, same idea

while (1) never becomes false on its own. Neither does a loop whose counter never changes. If the program never prints and never returns, look for a missing update. Make the condition do the stopping.

Next: the for loop, which is the usual choice for a known number of repeats.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C editor at /c/try. Change one measurement and check whether the result still has the right unit.

Physics

Half-life until the sample is small

Radioactive decay is exponential. Each half-life, on average, half the remaining nuclei have decayed. Starting at 8 g, three halvings leave 1 g. The time for one half-life is a property of the isotope, not of this loop.

while repeats until the mass drops below 1 g. The counter is how many half-lives that took in this toy model. Real decay is random; this is the deterministic envelope you sketch in class.

m = m₀ / 2ⁿ after n half-lives

Example

#include <stdio.h>

int main(void) {
  double mass = 8.0;
  int steps = 0;
  while (mass >= 1.0) {
    mass = mass / 2.0;
    steps++;
  }
  printf("after %d half-lives: %.3f g\n", steps, mass);
  return 0;
}

Maths

How many times you can halve 64

64 is 2⁶. Dividing by 2 until you reach 1 takes six steps. That count is log2(64). The same idea underlies binary search: each step throws away half the remaining interval.

Integer division is exact here because 64 stays even until 1. Try 50 and you hit a floor; the log is no longer an integer.

64 = 2⁶

Example

#include <stdio.h>

int main(void) {
  int n = 64;
  int k = 0;
  while (n > 1) {
    n = n / 2;
    k++;
  }
  printf("log2(64) = %d\n", k);
  return 0;
}

FAQ: C While Loop

Common questions about this page.

What is the StudyGrid C tutorial?

The StudyGrid C tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, pointers, structs, files, and the standard library. Each chapter has copy-and-run examples.

Should I run c while loop examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c while loop in this C C lesson (C While Loop).

Is the C editor the same as Try Python, Try HTML, or Try C++?

No. Try C compiles with gcc at /c/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. Try C++ stays at /cpp/try. C lessons never open those editors.

Do I need to install a compiler to learn C?

No. Open a chapter, click Try it in C, and compile in the browser. You can also download a .c file and compile locally with gcc.

Where should I start the C tutorial?

Start at C Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After pointers, open C Examples, then files and bitwise. Use Next at the bottom of each chapter.

Is the C tutorial free?

Yes. The C workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.