C Do/While Loop

1. What is a do...while Loop?

  • The do...while loop executes the block of code first, then checks the condition.

  • This guarantees that the loop body executes at least once, even if the condition is false.

Syntax:

do {
// code to execute
} while (condition);

Note the semicolon ; after the while(condition).


2. Simple Example

#include <stdio.h>

int main() {
int i = 1;

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

return 0;
}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5

Loop executes the block first, then checks i <= 5.


3. Difference Between while and do...while

Feature while Loop do...while Loop
Execution Condition checked first Code executed first
Minimum Iteration 0 1
Syntax while(condition){...} do{...} while(condition);

Example:

#include <stdio.h>

int main() {
int x = 10;

while (x < 5) {
printf("While: x = %d\n", x);
}

do {
printf("Do/While: x = %d\n", x);
} while (x < 5);

return 0;
}

Output:

Do/While: x = 10

while loop doesn’t execute because condition is false, but do...while executes once.


4. Using do...while for Input Validation

#include <stdio.h>

int main() {
int number;

do {
printf("Enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);

printf("You entered: %d\n", number);

return 0;
}

Sample Input/Output:

Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 10
You entered: 10

Loop keeps asking until a valid input is entered.


5. Key Points

  1. Executes at least once, unlike while.

  2. Condition is checked after the loop body.

  3. Useful for input validation, menus, or tasks that must run at least once.

  4. Remember the semicolon after while(condition);.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *