Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of While Loop in C
3.
Examples of While Loop in C
3.1.
Example 1: Counting Up
3.2.
C
3.3.
Example 2: Sum of Numbers
3.4.
C
3.5.
Example 3: Reading Input Until a Sentinel
3.6.
C
4.
While Loop Structure in C
4.1.
Initialization
4.2.
Condition
4.3.
Body
4.4.
Update
4.5.
Initialization
5.
Practical Example
5.1.
C
6.
Flowchart of While Loop in C
6.1.
Start
6.2.
Condition Check
6.3.
Loop Body
6.4.
Update Statement
6.5.
Repeat Condition Check
6.6.
End
7.
Working of While Loop in C
7.1.
Key Points to Remember
7.1.1.
Condition Check
7.1.2.
Loop Body Execution
7.1.3.
Update Mechanism
7.1.4.
Re-evaluation
7.1.5.
Practical Understanding
7.2.
Example: Loop to Echo Input
7.3.
C
8.
Infinite While Loop in C
8.1.
How Does an Infinite Loop Happen?
8.2.
Example of an Infinite Loop
8.3.
C
8.4.
Avoiding Infinite Loops
8.5.
Breaking Out of an Infinite Loop
8.6.
C
9.
Frequently Asked Questions 
9.1.
Can a while loop run forever in C?
9.2.
How do you stop a while loop?
9.3.
Is it possible to skip an iteration in a while loop?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

While Loop in C

Author Pallavi singh
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

When you're just getting started with programming, one of the first concepts you'll encounter is the loop. Think of it as the equivalent of a repetitive exercise in your daily routine, but in the world of coding. Specifically, in C programming, the 'while' loop plays a crucial role in executing a set of instructions repeatedly, as long as a certain condition remains true. 

While Loop in C

This article is going to walk you through 'while' loops in C. We'll cover the basics, learn different examples, and even explore some common structures and flowcharts related to while loops. 

Syntax of While Loop in C

Learning the 'while' loop in C is like learning the basic steps in the C programming. It's very easy to learn and very useful while writing codes. The syntax, or the way we write a 'while' loop, looks like this:

while (condition) {
    // Code to execute while the condition is true
}

Here's what happens: before each loop iteration, the condition is checked. If it's true, the code inside the loop runs. If it's false, the loop stops, and the program moves on to whatever comes next. It's important to ensure that the condition will eventually become false; otherwise, you'll end up with an infinite loop, and your program will just keep running the same code over and over.

Let's break it down a bit more:

  • while tells the program that this is a while loop.
     
  • condition is like a question that gets a yes (true) or no (false) answer. If yes, the loop keeps going. If no, it stops.
     
  • The curly braces { } hold the instructions that should repeat.
     

Remember, the condition needs to change inside the loop at some point; otherwise, the loop will never end.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples of While Loop in C

To understand better that how 'while' loops work in C, let's see some examples. 

Example 1: Counting Up

Let's start with a simple counter that goes from 1 to 5, similar to the one mentioned before. This example shows how to use a while loop to print out numbers, demonstrating the loop's basic functionality.

  • C

C

#include <stdio.h>

int main() {

   int i = 1; // Initialize counter

   while (i <= 5) {

       printf("%d ", i); // Print current number

       i++; // Increment counter

   }

   printf("\n"); // New line after loop ends

   return 0;

}

Output

Output

Example 2: Sum of Numbers

Now, let's look at a slightly more complex example where we calculate the sum of the first 10 numbers. This example demonstrates how a while loop can be used to perform calculations iteratively.

  • C

C

#include <stdio.h>

int main() {

   int sum = 0, i = 1;

   while (i <= 10) {

       sum += i; // Add i to sum

       i++; // Increment i

   }

   printf("Sum of the first 10 numbers is: %d\n", sum);

   return 0;

}

Output

Output

In this case, sum += i; is where the magic happens. Each time the loop runs, the current value of i is added to sum. By the end of the loop, sum holds the total of the first 10 numbers.

Example 3: Reading Input Until a Sentinel

This example shows how a while loop can be used to read input from the user until a specific "sentinel" value is entered. This is useful for when you don't know in advance how many inputs there will be.

  • C

C

#include <stdio.h>

int main() {

   int number, sum = 0;

   printf("Enter numbers to add to the sum. Enter -1 to stop.\n");

   scanf("%d", &number);

   while (number != -1) {

       sum += number;

       scanf("%d", &number); // Read next number

   }

   printf("Total sum is: %d\n", sum);

   return 0;

}

Output

Output

In this example, the loop continues to add numbers to sum until the user enters -1, which is the sentinel value indicating the end of input.

Each of these examples showcases a different way to utilize the while loop in C, from basic counting to conditional summing and sentinel-controlled loops. 

While Loop Structure in C


Understanding the structure of a 'while' loop is key to using it effectively in your C programs. The structure is simple but powerful, allowing for a variety of tasks to be performed repeatedly under certain conditions. Here's a breakdown of the main components of a while loop's structure:

Initialization

Before entering the loop, you typically initialize one or more variables. These variables often control the loop and are used in the loop's condition.

Condition

At the start of each iteration, the loop checks a condition. If the condition evaluates to true (non-zero), the loop's body executes. If it's false (0), the loop ends, and execution continues with the next statement after the loop.

Body

Inside the loop, you'll place the code that you want to execute repeatedly. This can include calculations, operations, function calls, or even other loops (nested loops).

Update

Within the loop's body, but typically at the end, you'll update one or more variables involved in the condition. This update is crucial for ensuring that the loop eventually terminates. Without an update that modifies the loop's condition, you might end up with an infinite loop.

Here's a visual representation of the while loop structure:

Initialization

while (Condition) {
    Body of the loop
    Update
}

Practical Example

To solidify your understanding, let's apply this structure to a practical example. Suppose you want to calculate the factorial of a number n. The factorial of a number is the product of all positive integers less than or equal to that number. For instance, the factorial of 5 (5!) is 5 * 4 * 3 * 2 * 1 = 120.

Here's how you might structure this calculation using a while loop:

  • C

C

#include <stdio.h>

int main() {

   int n = 5; // Example number

   int factorial = 1; // Initialization

while (n > 1) { // Condition

       factorial *= n; // Body: multiply the current value of factorial by n

       n--; // Update: decrement n

   }

printf("Factorial: %d\n", factorial);

   return 0;

}

Output

Output

In this example, the loop continues as long as n is greater than 1. Each iteration multiplies the current factorial value by n and then decreases n by 1. When n becomes 1, the condition n > 1 becomes false, and the loop ends.

This structure showcases the loop's ability to perform repeated tasks efficiently, with clear and concise code. Understanding this structure will help you implement while loops in a variety of situations, making your programs more effective and easier to read.

Flowchart of While Loop in C

A flowchart is a great tool to visualize the flow of control in a program, especially when it comes to loops. For a 'while' loop in C, the flowchart simplifies how each part of the loop works together. Understanding this can help you plan and debug your loops more effectively.

Here's a step-by-step breakdown of a typical while loop flowchart:

Start

This is where the loop begins, often following some initial setup or variable initialization outside the loop.

Condition Check

Before each iteration of the loop, the condition is evaluated. This decision point is crucial because it determines whether the loop continues or stops.

Loop Body

If the condition is true, the flow moves into the loop body where the actual operations specified within the loop are performed. This can include processing data, performing calculations, or even modifying the condition variable.

Update Statement

After executing the loop body, an update statement is often executed. This could be incrementing a counter, modifying a control variable, or any other operation that moves the loop towards its end condition.

Repeat Condition Check

After the update, the flow returns to the condition check. This cycle continues until the condition evaluates to false.

End

Once the condition is false, the loop terminates, and the flow of control moves to the statements that follow the loop.

To visualize, imagine a loop that counts from 1 to 5. You start with an initial value (i = 1). The condition (i <= 5) is checked. If true, you enter the loop, print the value of i, and then increment i by 1. You then check the condition again. This repeats until i is greater than 5, at which point the loop ends.

This flowchart concept not only helps in understanding and designing while loops but also assists in troubleshooting them by providing a clear visual representation of the loop's operation and flow of control.

Working of While Loop in C

Learning how a 'while' loop works in C can make your programming tasks a lot smoother. Essentially, a 'while' loop keeps running a block of code as long as a specific condition remains true. This condition is checked before each pass through the loop, which means if the condition is false to begin with, the code inside the loop might not run at all.

Key Points to Remember

Condition Check

At the start of the loop, the condition is evaluated. The loop proceeds only if the condition is true. If it's false, the loop is skipped entirely.

Loop Body Execution

If the condition is true, the statements inside the loop's body are executed.

Update Mechanism

Within the loop, it's crucial to have some mechanism (like incrementing a counter) that will eventually make the condition false, or else the loop could run indefinitely (creating what's known as an infinite loop).

Re-evaluation

After the loop body executes, the condition is checked again. If it's still true, another iteration begins. This cycle continues until the condition becomes false.

Practical Understanding

Imagine you have a task like reading a list of numbers and stopping when you hit a zero. The 'while' loop is perfect for this. You'd set up your loop with a condition that checks if the current number is not zero. Inside the loop, you'd read a number and process it. As long as the numbers aren't zero, the loop keeps going. Once a zero comes up, the condition becomes false, and the loop stops.

Example: Loop to Echo Input

Here's a simple example to illustrate the working of a while loop, where the program echoes any input it receives until the user enters '0'.

  • C

C

#include <stdio.h>

int main() {

   int input;

   printf("Enter any number (0 to stop): ");

     scanf("%d", &input);

   while (input != 0) {

       printf("You entered: %d\n", input);

       printf("Enter another number (0 to stop): ");

       scanf("%d", &input);

   }

 printf("Loop ended because you entered 0.\n");

   return 0;

}

Output

Output

In this example, the loop continues to ask for and echo back numbers until the user inputs '0'. The condition input != 0 is checked at the beginning of each iteration, ensuring the loop only runs when the input is not '0'.

Understanding this flow and structure can help you apply while loops effectively in your C programs, automating repetitive tasks and handling scenarios where the number of iterations needed isn't known upfront.

Infinite While Loop in C

An infinite loop occurs when the loop's condition never becomes false. In the case of a 'while' loop in C, this means the condition always evaluates to true, causing the loop to run endlessly. While sometimes infinite loops are used intentionally, more often than not, they are the result of a mistake in the loop's design.

How Does an Infinite Loop Happen?

Static Condition: If the condition in a while loop is something that doesn't change, like 1 == 1, the loop will never exit because the condition is always true.

No Update Inside Loop: If the loop doesn't contain code that could change the outcome of the condition (like incrementing a counter), it will run indefinitely.

Example of an Infinite Loop

  • C

C

#include <stdio.h>

int main() {

   while (1) { // This condition is always true

       printf("This loop will run forever!\n");

   }

   return 0; // This line is never reached

}

Output

Output

In this example, the condition 1 is always true, so the loop will continue to print the message indefinitely.

Avoiding Infinite Loops

To avoid unintentional infinite loops, ensure that:

  • The loop condition is dynamic and depends on variables that are subject to change during each iteration of the loop.
     
  • The body of the loop contains code that eventually makes the condition false. For example, incrementing a counter or modifying a control variable based on some logic.

Breaking Out of an Infinite Loop

Sometimes, you might want to use a loop that appears to be infinite but break out of it under specific conditions. You can use the break statement to exit a loop immediately, regardless of the loop's condition. Here's an example:

  • C

C

#include <stdio.h>

int main() {

   int counter = 0;

   while (1) { // Initially, this looks like an infinite loop

       printf("%d\n", counter);

       counter++;

       if (counter > 5) {

           break; // Break out of the loop when counter is greater than 5

       }

   }

   printf("Loop ended after break statement.\n");

   return 0;

}

Output

Output

In this modified example, the loop runs indefinitely in theory, but the break statement is used to exit the loop once counter exceeds 5.

Frequently Asked Questions 

Can a while loop run forever in C?

Yes, a while loop can run indefinitely if the condition always evaluates to true. This is known as an infinite loop. It's crucial to ensure the loop has a clear exit condition to prevent it from running endlessly.

How do you stop a while loop?

A while loop stops when its condition evaluates to false. You can also use the break statement within the loop to exit it prematurely based on a specific condition or event.

Is it possible to skip an iteration in a while loop?

Yes, you can skip an iteration in a while loop using the continue statement. When executed, continue immediately jumps to the next iteration of the loop, skipping any code below it for the current iteration.

Conclusion

Learning 'while' loops in C is a big step forward in your journey as a programmer. These loops are fundamental to controlling the flow of your programs, allowing you to repeat tasks without unnecessary code duplication. We've learned the basics, from the simple syntax to practical examples, and even touched on the exceptions of infinite loops and how to avoid them. Remember, the key to mastering while loops—or any programming concept—is practice. Experiment with the examples we've discussed, tweak them, and watch how changes affect the loop's behavior. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass