C•Loops
C While and Do-While Conditional Repetition Pipelines
C provides while loops for pre-test iteration (where the condition is checked before entering the body) and do-while loops for post-test iteration (guaranteeing at least one mandatory pass). Mastering these loops is critical for hardware retries, stream consumption, and queue worker state machines.
Syntax
while (hasWork) {
processItem();
}
do {
attemptConnection();
} while (retryCount < maxRetries);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| while (cond) | Loop Control | Pre-test loop: executes 0 or more times based on condition evaluation. |
| do ... while (cond); | Loop Control | Post-test loop: guarantees at least 1 execution before evaluating condition. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C locally:
#include <stdio.h>
int main(void) {
// 1. While loop: Logarithmic queue worker pipeline
printf("=== While Loop: Worker Queue Processing ===\n");
int pendingJobs = 16;
int processedBatches = 0;
while (pendingJobs > 1) {
printf("Batch %d: Processing %d jobs (splitting queue)\n", ++processedBatches, pendingJobs);
pendingJobs /= 2; // Halves the work each iteration
}
printf("Final standalone job resolved. Remaining: %d\n", pendingJobs);
// 2. Do-While loop: Network connection retry state machine
printf("\n=== Do-While Loop: Connection Handshake Pipeline ===\n");
int connectionAttempt = 0;
int maxAttempts = 3;
int handshakeEstablished = 0;
do {
connectionAttempt++;
printf("Attempt #%d: Sending SYN packet to gateway...\n", connectionAttempt);
// Simulate successful handshake on attempt 3
if (connectionAttempt == 3) {
handshakeEstablished = 1;
printf("Attempt #%d: ACK received! Connection established.\n", connectionAttempt);
} else {
printf("Attempt #%d: Timeout. Backing off...\n", connectionAttempt);
}
} while (!handshakeEstablished && connectionAttempt < maxAttempts);
printf("Handshake Pipeline Terminated: %s\n",
handshakeEstablished ? "SUCCESS (200 OK)" : "FAILED (504 Gateway Timeout)");
return 0;
}Expected Output:
=== While Loop: Worker Queue Processing === Batch 1: Processing 16 jobs (splitting queue) Batch 2: Processing 8 jobs (splitting queue) Batch 3: Processing 4 jobs (splitting queue) Batch 4: Processing 2 jobs (splitting queue) Final standalone job resolved. Remaining: 1 === Do-While Loop: Connection Handshake Pipeline === Attempt #1: Sending SYN packet to gateway... Attempt #1: Timeout. Backing off... Attempt #2: Sending SYN packet to gateway... Attempt #2: Timeout. Backing off... Attempt #3: Sending SYN packet to gateway... Attempt #3: ACK received! Connection established. Handshake Pipeline Terminated: SUCCESS (200 OK)
How It Works: Step-by-Step
- Lines 9-14: Pre-test while loop checks pendingJobs > 1 before body; halves jobs each pass.
- Lines 22-34: Do-while guarantees attempt #1 runs immediately before evaluating retry conditions.
- Line 34: Evaluates composite condition (!handshakeEstablished && connectionAttempt < maxAttempts).
Key Concepts
- A while loop will execute 0 times if the initial test evaluates to false (0), making it ideal when work might already be finished.
- A do-while loop always executes the body at least once, making it the standard C pattern for I/O menus, socket handshakes, and input validation.
- Always ensure state mutation occurs inside the loop body (e.g. pendingJobs /= 2 or connectionAttempt++) to prevent infinite loops.
- Notice the mandatory trailing semicolon after the while (condition); in do-while syntax.
Common Mistake: Omitting the trailing semicolon on a do-while loop
Unlike for and while loops, do-while requires a terminating semicolon after the closing while condition parenthesis. Omitting it causes a syntax compilation error.
❌ Incorrect
do { doWork(); } while (retryCount < 3) // Missing semicolon compilation error!✅ Correct
do { doWork(); } while (retryCount < 3); // Valid terminating semicolonRelated C Tutorials & Compiler
C Short-Circuit Ternary Logic and Conditional Expressions
Implement short-circuit logical expressions (&&, ||) and compact ternary operators in C for defensive null checks and inline branching.
C Break and Continue Statements in Loops
Interrupt or skip loop cycles using break and continue in C.
C Arrays: Contiguous Stack Buffers and Multi-Dimensional Arrays
Learn fixed-size arrays, memory layouts, indexing, and calculating element counts.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.