ZeroToSky
C Programming Tutorial 55 of 206
Introduction & Setup
  • Introduction to C
  • History of C
  • Features of C
  • Applications of C
  • Advantages and Limitations of C
  • C Standards and Implementations
  • How C Programs Run
  • Setting Up C Development Environment
  • Your First C Program
  • Basic Syntax of C
  • Structure of a C Program
  • Compilation Process in C

All 12 lessons →

Tokens & Basics
  • Tokens in C
  • Keywords in C
  • Identifiers in C
  • Constants in C
  • Variables in C
  • Scope Rules in C
  • Storage Classes in C
  • Comments in C

All 8 lessons →

Data Types & I/O
  • Data Types in C
  • Primitive Data Types
  • Derived Data Types
  • Type Modifiers
  • Type Conversion in C
  • Type Casting in C
  • sizeof Operator
  • Input and Output in C
  • printf() in C
  • scanf() in C
  • Character I/O: getchar and putchar
  • String I/O: gets/fgets and puts
  • Format Specifiers in C

All 13 lessons →

Operators & Expressions
  • Operators in C
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Increment and Decrement Operators
  • Conditional Operator
  • Comma Operator
  • sizeof and Address Operators
  • Operator Precedence and Associativity
  • Expression Evaluation in C
  • Short-Circuit Evaluation

All 13 lessons →

Control Flow
  • Decision Making in C
  • if Statement
  • if-else Statement
  • else-if Ladder
  • Nested if
  • switch Statement
  • Loops in C
  • for Loop
  • while Loop
  • do-while Loop
  • Nested Loops
  • break Statement
  • continue Statement
  • goto Statement

All 14 lessons →

Functions
  • Functions in C
  • Function Declaration and Definition
  • Function Arguments
  • Return Values
  • Call by Value
  • Call by Reference Using Pointers
  • Parameter Passing Techniques
  • Main Function in C
  • Recursion in C
  • Types of Recursion
  • Inline Functions
  • Nested Functions
  • Function Pointers
  • Variadic Functions

All 14 lessons →

Arrays
  • Arrays in C
  • Declaration and Initialization of Arrays
  • Accessing Array Elements
  • Traversing an Array
  • Passing Arrays to Functions
  • Array Parameters and Pointers
  • One-Dimensional Arrays in C
  • Two Dimensional Arrays
  • Multidimensional Arrays in C
  • Passing 2D Arrays to Functions
  • Array of Pointers
  • Variable Length Arrays

All 12 lessons →

Strings
  • Strings in C
  • String Declaration and Initialization
  • String Length
  • String Traversal
  • String Comparison
  • String Copy
  • String Concatenation
  • Substring Search
  • String Tokenization
  • String Reverse
  • Palindrome String in C
  • String Pattern Searching
  • String Literals

All 13 lessons →

Pointers
  • Pointers in C
  • Address and Dereference Operators
  • Pointer Arithmetic
  • Pointers and Arrays
  • Pointer to Pointer
  • Void Pointers
  • Null Pointers
  • Dangling Pointers
  • Wild Pointers
  • Constant Pointers and Pointer to Constant
  • Function Pointers
  • Array of Pointers
  • Pointers to Functions
  • Pointers to Structures
  • Pointer Type Casting

All 15 lessons →

Structures & Unions
  • Structures in C
  • Structure Members
  • Array of Structures
  • Nested Structures
  • Pointers to Structures
  • Passing Structures to Functions
  • Structure Alignment and Padding
  • Self-Referential Structures
  • Bit Fields in Structures
  • Unions in C
  • Structure vs Union
  • Enumeration in C
  • typedef in C

All 13 lessons →

Dynamic Memory & Memory
  • Program Memory Layout in C
  • Stack and Heap in C
  • malloc()
  • calloc()
  • realloc()
  • free()
  • Dynamic Arrays
  • Memory Leaks
  • Dangling Memory
  • Double Free
  • Use After Free
  • Memory Safety Best Practices

All 12 lessons →

Preprocessor & Headers
  • C Preprocessor
  • Header Files in C
  • #include Directive
  • #define and Macros
  • Function-like Macros
  • Conditional Compilation
  • #ifdef, #ifndef and #endif
  • Predefined Macros
  • Pragma Directive
  • Include Guards

All 10 lessons →

File Handling
  • File Handling in C
  • File Pointers
  • fopen() and fclose()
  • Reading a File
  • Writing to a File
  • Appending to a File
  • fgetc() and fputc()
  • fgets() and fputs()
  • fprintf() and fscanf()
  • Binary File Handling
  • EOF, getc() and feof()
  • Read/Write Structures to Files
  • Delete a File
  • File Error Handling

All 14 lessons →

Error Handling & Debugging
  • Error Handling in C
  • perror()
  • strerror()
  • errno
  • Assertions in C
  • Debugging C Programs
  • Common C Runtime Errors
  • Divide by Zero Handling
  • goto for Error Handling

All 9 lessons →

Date, Time & Misc
  • Date and Time in C
  • time() Function
  • clock() Function
  • Random Numbers in C
  • Linkage in C
  • External and Static Linkage
  • Storage Duration
  • Integer Overflow and Undefined Behavior
  • Implementation-Defined vs Undefined Behavior

All 9 lessons →

Advanced C
  • Generic Selection (_Generic)
  • Variadic Functions
  • Input/Output System Calls
  • Signals in C
  • Signal Handling
  • Socket Programming in C
  • Multithreading in C
  • Threads and Synchronization
  • Atomic Operations
  • Memory-Mapped Files
  • Low-Level Systems Programming

All 11 lessons →

Practice & Projects
  • C Programming Examples
  • C Exercises
  • C Fundamental Practice Problems
  • C Functions Practice Problems
  • C Compound Data Type Practice Problems
  • C Pattern Programs
  • C Array Programs
  • C String Programs
  • C Pointer Programs
  • C Structure and Union Programs
  • C File Handling Projects
  • C Mini Projects
  • C Interview Questions
  • Data Structures and Algorithms in C

All 14 lessons →

While Loop

Learn how the while loop in C repeatedly executes a block of code while a condition remains true.

Gaurav 3 min read Sign in to save
On this page

While Loop in C

A while loop in C is used to repeatedly execute a block of code as long as a specified condition remains true.

It is useful when the number of iterations is not known in advance and depends on a condition.

Syntax

while (condition) {
    // statements
}

The condition is checked before each iteration.


How a While Loop Works

The execution follows these steps:

  1. Check the condition.
  2. If the condition is true, execute the loop body.
  3. Update the required variable or state.
  4. Check the condition again.
  5. Stop when the condition becomes false.

Example:

int i = 1;

while (i <= 5) {
    printf("%d ", i);
    i++;
}

Output:

1 2 3 4 5

Here, i++ is important because it moves the loop toward termination.


While Loop for Array Traversal

A while loop can be used to traverse an array.

int arr[] = {10, 20, 30, 40, 50};
int i = 0;

while (i < 5) {
    printf("%d ", arr[i]);
    i++;
}

Output:

10 20 30 40 50

The loop continues until i reaches the array size.


Using a While Loop for Input

A common use is to continue processing input until a particular condition is reached.

int num;

printf("Enter a positive number: ");
scanf("%d", &num);

while (num > 0) {
    printf("%d ", num);
    num--;
}

The loop continues while num > 0.


while vs for

Both loops can perform repeated operations, but they are commonly used in different situations.

while for
Condition-based iteration Count-based iteration
Useful when iterations are uncertain Useful when iterations are known
Initialization/update can be separate Initialization, condition, and update are together
Common in pointer and input-based logic Common in array and range traversal

For example:

while (current != NULL) {
    current = current->next;
}

This pattern is commonly used when traversing a linked list.


Infinite While Loop

If the condition never becomes false, the loop continues indefinitely.

int i = 1;

while (i <= 5) {
    printf("%d ", i);
}

This is an infinite loop because i is never changed.

Correct version:

int i = 1;

while (i <= 5) {
    printf("%d ", i);
    i++;
}

Always ensure that the loop has a clear termination condition.


Using break

The break statement immediately terminates the loop.

int i = 1;

while (i <= 10) {
    if (i == 5)
        break;

    printf("%d ", i);
    i++;
}

Output:

1 2 3 4

Using continue

The continue statement skips the remaining statements of the current iteration.

int i = 0;

while (i < 5) {
    i++;

    if (i == 3)
        continue;

    printf("%d ", i);
}

Output:

1 2 4 5

Common Mistakes

Forgetting to Update the Variable

int i = 1;

while (i <= 5) {
    printf("%d ", i);
}

This creates an infinite loop.

Using the Wrong Condition

Make sure the condition correctly represents when the loop should stop.

while (i < 5)

and

while (i <= 5)

produce different iteration counts.

Array Boundary Errors

When traversing an array of size n, use:

while (i < n)

rather than:

while (i <= n)

because the last valid index is n - 1.


Time Complexity

If a while loop executes n times and each iteration performs constant-time work, its time complexity is:

O(n)

The complexity depends on how many times the loop executes and what operations are performed inside it.


Quick Reference

int i = 0;

while (i < n) {
    // process data
    i++;
}

Remember:

  • Condition is checked before execution.
  • The loop may execute zero times if the condition is initially false.
  • Update the loop state to avoid infinite loops.
  • Use break to terminate early.
  • Use continue to skip an iteration.

Key Takeaways

  • A while loop repeats code while a condition is true.
  • It is useful when the number of iterations depends on a condition.
  • It is commonly used for traversal, input processing, and pointer-based logic.
  • Always ensure that the loop can eventually terminate.
  • For n simple iterations, the typical time complexity is O(n).

Practice Questions

  1. Print numbers from 1 to N using a while loop.
  2. Find the sum of numbers from 1 to N.
  3. Reverse an integer using a while loop.
  4. Count the number of digits in a number.
  5. Traverse an array using a while loop.

What's Next?

Next, learn do-while loops, where the loop body executes at least once before the condition is checked.

Related

Found a problem on this page, or something that could be clearer?

Goes straight to the author. Not published anywhere.