C Programming Tutorial

C Programming Tutorial

While Loop in C Programming

Hello Everyone, In this article, we will cover the concept of While Loop in C Programming. We will cover how it works, While loop syntax, and some practical examples to help you understand how to effectively use this loop to repeat actions based on specific conditions. Whether you’re new to C or have some experience, this guide will help you to understand While Loops in C effectively. Let’s get started.

Basic Structure of While Loop in C

In C programming language, a while loop is a type of loop that allows you to repeatedly execute a block of code as long as a certain condition is true. Here’s the basic structure of a while loop in C:

while (condition) {
   // block of code to be executed
}

The condition is a Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the block of code within the loop is executed. After the block of code is executed, the condition is evaluated again. If it’s still true, the block of code is executed again. This process continues until the condition becomes false.

While loop that counts from 1 to 10

int i = 1;
while (i <= 10) {
   printf("%d\\n", i);
   i++;
}

In this example, the loop starts with i equal to 1. The condition i <= 10 is true, so the block of code within the loop is executed. The printf() function prints the value of i (which is currently 1) to the console. Then the i++ statement increments the value of i by 1. Now i is equal to 2. The condition i <= 10 is still true, so the block of code within the loop is executed again. This process continues until i is equal to 11, at which point the condition i <= 10 is false, and the loop terminates.

C Program that uses a while loop to print the first 10 even numbers

#include <stdio.h>int main() {
   int num = 0;
   int count = 0;

   while (count < 10) {
      num += 2;
      printf("%d ", num);
      count++;
   }

   return 0;
}

Let’s break this program down:

  1. We start by including the standard input/output library stdio.h.
  2. We declare the main function, which is the entry point of our program.
  3. We declare two integer variables, num and count, and initialize them to 0.
  4. We use a while loop with the condition count < 10, which means the loop will continue executing as long as the value of count is less than 10.
  5. Within the loop, we add 2 to the value of num and print it using printf().
  6. We increment the value of count by 1 in each iteration of the loop.
  7. Once count reaches 10, the loop terminates.
  8. Finally, we return 0 to indicate successful program completion.

When you run this program, it will output the following to the console:

2 4 6 8 10 12 14 16 18 20
Share This Article