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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
While Loop
Learn how the while loop in C repeatedly executes a block of code while a condition remains true.
On this page
- Syntax
- How a While Loop Works
- While Loop for Array Traversal
- Using a While Loop for Input
- while vs for
- Infinite While Loop
- Using break
- Using continue
- Common Mistakes
- Forgetting to Update the Variable
- Using the Wrong Condition
- Array Boundary Errors
- Time Complexity
- Quick Reference
- Key Takeaways
- Practice Questions
- What's Next?
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:
- Check the condition.
- If the condition is
true, execute the loop body. - Update the required variable or state.
- Check the condition again.
- 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
breakto terminate early. - Use
continueto skip an iteration.
Key Takeaways
- A
whileloop 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
nsimple iterations, the typical time complexity isO(n).
Practice Questions
- Print numbers from
1toNusing a while loop. - Find the sum of numbers from
1toN. - Reverse an integer using a while loop.
- Count the number of digits in a number.
- 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
-
For Loop
for Loop — part of the C Programming Tutorial.
-
Floyd's Triangle
Learn how to generate Floyd's Triangle using nested loops and understand the row-by-row numbering pattern.
-
Palindrome String in C
Learn how to check whether a string is a palindrome in C using character comparison, loops, and simple examples.
-
For Loop
Learn how for loops help DSA algorithms repeat operations, traverse data, control iterations, and solve problems with predictable time complexity.