C Loops: While, Do-While, and For Loops

Loops in C repeat a statement or block of statements while a specified condition permits execution. They are useful for processing arrays, validating input, generating number sequences, performing calculations, and repeating work without duplicating code.

C provides three primary looping statements:

  • while loop
  • do-while loop
  • for loop

The while and for loops test their conditions before executing the loop body. A do-while loop tests its condition after the body, so its body executes at least once.

How C Loop Conditions Work

A C loop continues when its controlling expression evaluates to a nonzero value. It terminates when that expression evaluates to zero. C does not require the condition to produce only 1 or 0; any nonzero result is treated as true.

Most loops contain four logical parts:

  1. Initialization: Establish the initial value of a loop-control variable.
  2. Condition: Decide whether another iteration should run.
  3. Loop body: Execute the statements that perform the repeated work.
  4. Update: Change the loop-control state so that the condition can eventually become false.

Difference Between For, While, and Do-While Loops in C

C loopCondition checkedMinimum executionsTypical use
forBefore the bodyZeroCounting and indexed iteration
whileBefore the bodyZeroRepetition controlled by a condition or event
do-whileAfter the bodyOneMenus, prompts, and validation that must run once

A for loop is usually clearer when initialization, testing, and updating belong together. A while loop is often clearer when the number of iterations is not known in advance. Use do-while when the operation must occur before its continuation condition can be tested.

C Loop Tutorials

The following tutorials cover C looping statements and the break and continue statements used to control loop execution:

  1. For Loop in C
  2. While Loop in C
  3. Do-While Loop in C
  4. Nested Loops in C
  5. Break statement in C
  6. Continue statement in C
  7. Infinite For Loop in C
  8. Infinite While Loop in C

C Programs that Use Loops

These programs demonstrate loop selection, array traversal, calculations, input handling, patterns, and other common C programming tasks:

  1. How to Write a For Loop without Initialization in C
  2. How to Write a For Loop without Condition in C
  3. How to Write a While Loop without Condition in C
  4. How to Choose Between For and While Loops in C
  5. How to Iterate Over Arrays using Loops in C
  6. How to Avoid Common Mistakes with Loops in C
  7. How to Read Multiple Inputs from User using a Loop in C
  8. How to Implement Input Validation using Loops in C
  9. How to Print Patterns using Loops in C
  10. How to Iterate Through a 2D Array using For Loop in C
  11. How to Exit Multiple Loops using Goto or Flags in C
  12. How to Compare the Performance of For and While Loops in C
  13. How to Calculate Factorials using Loops in C
  14. How to Generate Fibonacci Series using Loops in C
  15. How to Use Loop Counters and Iterators Effectively in C
  16. How to Reverse a String using Loops in C
  17. How to Reverse a Number using Loops in C
  18. How to Check for Prime Numbers using Loops in C
  19. How to Calculate the Sum of Numbers in Array using Loops in C
  20. How to Calculate the Average of Numbers in Array using Loops in C
  21. How to Find the GCD using Loops in C
  22. How to Find the LCM using Loops in C
  23. How to Count the Digits in a Number using Loops in C
  24. How to Find the Maximum Value in an Array using Loops in C
  25. How to Find the Minimum Value in an Array using Loops in C
  26. How to Convert a Decimal Number to Binary using Loops in C
  27. How to Generate a Multiplication Table using Loops in C

While, Do-While, and For Loop Examples in C

While Loop in C

A while loop repeats its body while its condition remains nonzero. Because the condition is evaluated first, the body is skipped when the condition is false on the first test.

The syntax of while loop is:

</>
Copy
while (condition) {
    //while block statement(s)
}

In the following program, i begins at zero. Each iteration prints its current value and increments it. The loop terminates after i becomes 6.

C Program

</>
Copy
#include<stdio.h>

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

Output

0
1
2
3
4
5

The values are shown on separate lines above for readability. Because the program’s printf call does not contain a space or newline, its literal terminal output is 012345.

The following C program uses a while loop to calculate the sum of the integers from 0 through 100.

C Program

</>
Copy
#include<stdio.h>

int main() {
	int i=0,sum=0;			
	while(i<=100) {	
		sum+=i;			
		i++;		
	}
	printf("Sum : %d",sum);				
	return 0;
}

Output

Sum : 5050

A while loop is particularly suitable when execution depends on changing input or state and the exact iteration count is not known beforehand.

Read more about C While Loop.

Do-While Loop in C

A do-while loop evaluates its condition after executing the body. The body therefore runs at least once, even when the condition is false during its first evaluation. A semicolon is required after the closing while (condition).

The syntax of do-while loop is

</>
Copy
do {
    //while block statement(s)
} while (condition);

The following C program prints the numbers from 0 through 5 using a do-while loop.

C Program

</>
Copy
#include<stdio.h>
int main() {
	int i=0;		
	do {	
		printf("\n %d",i);			
		i++;		
	} while(i<=5);			
	return 0;
}

Output

0
1
2
3
4
5

The next program reads a limit and uses a do-while loop to print each number, its square, and its cube.

C Program

</>
Copy
#include<stdio.h>
int main() {	
	int i,n;
	printf("\n Enter number:");
	scanf("%d",&n);
	i=1;
	do {
		printf("\n|\t %d \t|\t %d \t|\t %d \t",i,i*i,i*i*i);
		i++;
	}while(i<=n);
	return 0;
}

Output

Enter number:3

|        1      |        1      |        1
|        2      |        4      |        8
|        3      |        9      |        27

If the user enters zero or a negative number, this particular program still executes the body once because it uses do-while. Validate the input before entering the loop when that behavior is not wanted.

Read more about C Do-While Loop.

For Loop in C

A C for loop places initialization, condition testing, and updating in its header. This makes it a common choice for counter-controlled loops and array indexes.

For Loop Syntax in C

</>
Copy
for(initialization; condition; update) {
    // for block statement(s)
}
  • Initialization runs once before the first condition check.
  • Condition is tested before each iteration. The loop ends when it evaluates to zero.
  • Update runs after each completed iteration and before the next condition check.

The following program uses a for loop to calculate the factorial of a nonnegative integer.

C Program

</>
Copy
#include<stdio.h>
int main() {
	int fact=1,num,i;
	printf("\n Enter number:");	
	scanf("%d",&num);
	if(num==0) {
		fact=1;
	} else {
		for(i=1;i<=num;i++)
		fact=fact*i;
	}	

	printf("Factorial of %d is %d",num,fact);
	return 0;
}

Output

Enter number:5
Factorial of 5 is 120

This example is intended for small, nonnegative inputs. A negative number does not have an ordinary factorial, and sufficiently large positive values overflow an int.

Read more about C For Loop.

Nested Loops in C

A nested loop is a loop placed inside another loop. For every iteration of the outer loop, the inner loop performs all iterations permitted by its own condition. Nested loops are commonly used with matrices, two-dimensional arrays, tables, and text patterns.

Nested For Loop Pattern Example in C

</>
Copy
#include<stdio.h>

int main() {
	int i,j;
	for(i=0;i<=4;i++) {
		for(j=0;j<=i;j++) {
			printf("* ");
        }
        printf("\n");
	}
    return 0;
}

Output

*
* *
* * *
* * * *
* * * * *

Break and Continue Statements in C Loops

The break statement immediately terminates the nearest enclosing loop. Execution resumes at the first statement after that loop. The continue statement skips the remaining statements in the current iteration and proceeds with the next iteration.

</>
Copy
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i == 3) {
            continue;
        }
        if (i == 7) {
            break;
        }
        printf("%d ", i);
    }
    return 0;
}

Output

1 2 4 5 6

When i is 3, continue skips the print operation. When i is 7, break ends the loop before 7 is printed.

Infinite Loops and Common C Loop Mistakes

  • Missing update: If a loop-control variable never changes, the condition may remain true indefinitely.
  • Stray semicolon: A semicolon immediately after while or for creates an empty loop body.
  • Incorrect boundary: Confusing < with <= can cause an extra iteration or omit the final required iteration.
  • Out-of-bounds array access: For an array of length n, valid indexes run from 0 through n - 1.
  • Unsigned countdown error: An unsigned variable cannot become negative, so a condition such as i >= 0 never becomes false.
  • Unintended assignment: Writing = instead of == changes a value and then tests the assigned result.
  • Unvalidated input: If scanf fails, the expected variable may not receive a new value. Check the function’s return value before using the input.

A for (;;) statement is an intentional infinite loop because its condition is omitted. A while (1) statement has the same general effect. Such loops require a break, return statement, signal, or another external termination path when they are not meant to run for the lifetime of the program.


C Loop Interview Questions with Explanations

1 What is the output of this C while loop?

</>
Copy
#include<stdio.h>
int main() {
	int i,j;
	i=j=2,3;
	while(--i&&j++)
		printf("%d  %d",i,j);
	return 0;
}

Answer

1 3

Step-by-step explanation

  • The comma operator has lower precedence than assignment. The statement i=j=2,3; assigns 2 to both j and i; the final expression 3 is discarded.
  • During the first condition test, --i changes i from 2 to 1. Because 1 is nonzero, the right operand of && is evaluated.
  • j++ contributes the old nonzero value 2 to the condition and then changes j to 3. The loop body prints i as 1 and j as 3.
  • During the next test, --i produces zero. Short-circuit evaluation prevents j++ from running, and the loop terminates.

2 What happens when a C for loop omits all three expressions?

</>
Copy
#include<stdio.h>
int main(){
  	  for(;;) {
        	 printf("%d ",10);
  	  }
  	  return 0;
}

Answer

The program contains an infinite loop and repeatedly attempts to print 10. The return statement is not reached during normal execution.

Explanation

Refer Note provided in the earlier part of this article.

3 What does a comma expression return in a do-while condition?

</>
Copy
#include<stdio.h>
int i=40;
extern int i;
int main() {
	do {
		printf("%d",i++);
	}
	while(5,4,3,2,1,0);
	return 0;
}

Answer

40

Step-by-step explanation

The global variable i initially contains 40. The do body prints 40 and then increments i. The comma expression (5,4,3,2,1,0) evaluates its operands from left to right and has the value of its final operand, which is zero. The condition is therefore false, and the loop ends after one iteration.

4 Is this char-controlled C loop portable?

</>
Copy
#include<stdio.h>
int main(){
    char c=125;
    do
         printf("%d ",c);
    while(c++);
    return 0;
}

Answer

No single portable iteration count can be given for this program.

Explanation

  • Whether plain char is signed or unsigned is implementation-defined.
  • When char is signed and cannot represent the incremented value, converting that value back to char produces an implementation-defined result or may raise an implementation-defined signal.
  • On a common implementation with an 8-bit signed char that wraps from 127 to -128, the body executes 132 times and prints values from 125 through 127, then -128 through 0.
  • On a common implementation with an 8-bit unsigned char, the body also executes 132 times, printing 125 through 255 and then 0.
  • Use a fixed-width integer type and an explicit termination condition when the program requires predictable behavior across implementations.

C Loops Frequently Asked Questions

What is the difference between while and do-while loops in C?

A while loop checks its condition before executing its body, so it may run zero times. A do-while loop checks the condition after its body, so it always runs at least once.

When should I use a for loop instead of a while loop in C?

Use a for loop when the initialization, condition, and update form one clear counter-controlled operation. Use a while loop when repetition depends mainly on input, a sentinel value, or another changing condition. Either loop can usually be rewritten as the other without changing the algorithm.

Can initialization or updating be omitted from a C for loop?

Yes. Any of the three expressions in a for header may be omitted, but both semicolons must remain. If the condition is omitted, it is treated as true, producing a potentially infinite loop.

How do I stop an infinite loop in a C program?

Correct the condition or update so the loop can terminate, or use a deliberate exit path such as break when a defined event occurs. During terminal testing, an accidentally infinite program can usually be interrupted with the environment’s interrupt command, commonly Ctrl+C.

Does break exit every nested loop in C?

No. break exits only the nearest enclosing loop or switch. Exiting several nested loops requires additional control logic, such as a flag checked by the outer loops, a return from the current function, or a carefully placed goto.

C Loops Editorial QA Checklist

  • Confirm that each loop example states whether its condition is checked before or after the body.
  • Compile C examples with warnings enabled and review all diagnostics.
  • Verify loop boundaries with the first, final, empty, and single-item cases.
  • Match displayed output to spaces and newline characters used by each printf call.
  • Check that every non-intentional loop has a reachable termination condition.
  • Verify that array loop indexes remain within the valid range from zero through length minus one.
  • Identify examples whose results depend on integer overflow, plain char signedness, or other implementation-defined behavior.
  • Confirm that break and continue explanations refer to the nearest enclosing loop.