while Loop in C Programming
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

while Loop in C Programming – Complete Guide for Beginners

📑 On this page:
  • Introduction
  • What is a while Loop?
  • Real-World Use Cases
  • Advantages of while Loop
  • Disadvantages of while Loop
  • Flowchart of while Loop
  • Syntax of while Loop
  • Program Example
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What a while loop is and why we use it in C programming
  • How the while loop works with real examples
  • Where to use while loops in real applications
  • How to write a program using while loop
  • Complete program examples with explanations

Introduction

In this tutorial section, we will learn what a while loop is in C programming.

A while loop is one of the most important looping constructs in C. It allows you to execute a block of code repeatedly as long as a condition remains true.

What is a while Loop in C?

A while loop in C Programming is a pre-tested loop. In general, a while loop repeatedly executes a part of the code statements multiple times, depending upon a given condition.

The while loop is also known as a pre-tested or entry-controlled loop, meaning the condition is tested before the body of the loop executes.

A while loop in C language is an iterative/repeating statement and is used when a specific statement needs to be executed again and again.

💡 Key Point: A while loop is called an entry-controlled loop because first, the boolean expression is tested, and depending on the tested result, the loop is executed.

Real-World Use Cases of while Loop

Following are some real use cases of a while loop:

  • Music Player loop: While the user does NOT press 'stop' and the playlist is NOT stopped, get the next song and play the song.
  • User input loop: Ask a yes-no question to the user and get an answer. While the answer is not 'yes' and the answer is not 'no', repeat the question.
  • Username and password validation: Validate username and password until both are correct.
  • ATM PIN validation: Keep asking for PIN until the correct PIN is entered.

Advantages of Using while Loop in C Programming

1. Simple and easy to understand — The syntax is beginner-friendly

2. Repeats execution automatically — As long as the condition remains true

3. Flexible — Can handle complex conditions and logic

Disadvantages of Using while Loop in C Programming

1. Semicolon pitfall: Placing a semicolon after a while loop's condition (e.g., while(condition);) can create a problem. Although it might compile correctly, this will make the loop an infinite loop.

2. Unexpected results: A while loop can lead to unexpected results in a C program when its exit condition is not well-defined.

3. Infinite loop risk: If the condition never becomes false, the program runs forever.

Flowchart of while Loop

The flowchart below shows how the while loop works step by step:

Flowchart illustrating the step-by-step execution of a while loop in C programming

Step-by-step explanation:

1. Initialization: After step-by-step execution of the instructions, the program control enters the initialization part. In this step, the programmer declares or initializes the variable to some value.

Initialization of the variable happens outside the loop and it is not part of the while loop, but it is essential to initialize it before the loop starts because it is required when the programmer uses a variable in the condition or test expression.

2. Condition: The condition is an expression that may evaluate to either true or false. This is one of the primary and most essential steps, as it decides whether the block of code in the while loop will execute or not. The code inside the body of the while loop will be executed if and only if the tested condition is true; otherwise, control jumps outside the loop and stops the execution.

3. Body: It is a block of code or the actual set of statements that will be executed repeatedly until the specified condition is true. This block of code or statements is known as the body of the loop. It can include variables, functions, expressions, etc.

4. Updation: Updation is not part of the syntax, but we have to define it explicitly in the body of the loop. It is an expression that changes the value of the loop variable in each step of execution or iteration.

Syntax of while Loop in C

Let us study the real-world syntax of the while loop and then we will look in detail into all parts of the while loop.

/* statements outside loop */
/* initialization */
int i = 1;

while (condition) {
    /* code inside body of loop */
    /* statements to be executed */
    
    /* update expression */
    i++;
}

/* statement outside loop */

Let's break down each part:

🔹 Initialization: Variables are declared and initialized before the loop starts. This happens outside the while loop.

🔹 Condition: The condition is tested before each iteration. If true, the loop body executes. If false, the loop ends.

🔹 Body: The statements inside the loop that execute repeatedly as long as the condition is true.

🔹 Update Expression: This changes the loop control variable to ensure the loop eventually terminates.

⚠️ Important: Make sure the update expression eventually makes the condition false. Otherwise, you'll create an infinite loop.

Program to Illustrate while Loop in C

The program below displays "Inside the While loop Body" 10 times using a while loop.

#include <stdio.h>

int main() {
    /* Declaration and initialization expression */
    int n = 1;
    
    /* test the expression */
    while (n <= 10) {
        printf("\n Inside the While loop Body");
        
        /* update expression */
        n += 1;  // n++
    }
    
    return 0;
}

Sample Output:

Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body
Inside the While loop Body

Explanation:

  1. The program starts from the main() function.
  2. n is declared and initialized to 1.
  3. The condition while(n <= 10) is tested. Since 1 <= 10 is true:
    • "Inside the While loop Body" gets printed for the 1st time.
    • Updation takes place: n += 1 executes, so n becomes 2.
  4. The condition while(n <= 10) is tested again. Since 2 <= 10 is true:
    • "Inside the While loop Body" gets printed for the 2nd time.
    • Updation takes place: n += 1 executes, so n becomes 3.
  5. This process continues until n becomes 10.
  6. When n is 10, 10 <= 10 is true:
    • "Inside the While loop Body" gets printed for the 10th time.
    • Updation takes place: n += 1 executes, so n becomes 11.
  7. The condition while(n <= 10) is tested again. Since 11 <= 10 is false.
  8. Control flow goes outside the loop and return 0; stops program execution.

💻 Practice Exercise

Challenge: Write a program that asks the user to enter a number. The program should keep asking until the user enters a number greater than 100. Then display the final number.

🔍 Click to Show Solution
#include <stdio.h>

int main() {
    int num;
    
    printf("Enter a number greater than 100: ");
    scanf("%d", &num);
    
    while (num <= 100) {
        printf("Try again! Enter a number greater than 100: ");
        scanf("%d", &num);
    }
    
    printf("You entered: %d\n", num);
    return 0;
}

📝 Summary

  • A while loop is an entry-controlled or pre-tested loop
  • The condition is checked before executing the loop body
  • If the condition is false initially, the loop body never executes
  • It is useful when the number of iterations is not known in advance
  • Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops

Frequently Asked Questions About while Loop in C

1. What is the difference between while loop and do-while loop?

The main difference is that a while loop checks the condition first – if it's false, the loop never runs. A do-while loop runs the code first, then checks the condition – so it always runs at least once.

2. When should I use a while loop?

Use a while loop when you don't know how many times the loop should run, and you want to check the condition before each iteration. Examples include user input validation, reading files until EOF, and game loops.

3. Can a while loop run forever?

Yes! If the condition is always true, the loop will run forever. This is called an infinite loop. For example, if you write while(1) or forget to update the loop variable, the loop will never end.

4. What happens if the condition is false initially in while loop?

If the condition is false initially, the loop body never executes. The program skips the loop entirely and continues with the code after the loop.

5. Can I use break and continue in while loop?

Yes, you can use both break and continue in a while loop. break exits the loop immediately. continue skips the rest of the current iteration and jumps to the condition check.

💡 Tip: Always make sure the update expression changes the variable used in the condition. Otherwise, you might create an infinite loop.

📖 Related Tutorials

  • do-while Loop in C - Complete Guide
  • for Loop in C - Complete Guide
  • goto Statement in C
  • Introduction to Loops in C

Previous Topic: -->> do-while loop in C   ||   Next topic: -->> Nested while loop in C


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.