Utilizor
Contact Us
HomeC TutorialC While Loop

CC While Loop

Looping through code.

C While Loop

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

The While Loop

The while loop loops through a block of code instructions as long as a specified condition is true:

Examples

While Loop

c example

Loops while i is less than 5.

#include <stdio.h>

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

Do/While Loop

c example

Executes the block once before checking the condition.

#include <stdio.h>

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

Test Your Knowledge

1. Which loop runs at least once?

2. What happens if you forget to increment the variable in a while loop?