do-while loops in C Language:
Do While Loops in C
The do while
loop in C is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop will execute the code block once before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
// statements
} while (condition);
Basic Do While Loop
A basic do while
loop executes the statements at least once before checking the condition.
#include
int main() {
int i = 0;
do {
printf("i = %d\n", i);
i++;
} while (i < 5);
return 0;
}
Do While Loop with Multiple Conditions
You can use logical operators to create more complex conditions in a do while
loop.
#include
int main() {
int i = 0, j = 5;
do {
printf("i = %d, j = %d\n", i, j);
i++;
j--;
} while (i < j && j > 0);
return 0;
}
Infinite Do While Loop
A do while
loop can run indefinitely if the condition is always true.
#include
int main() {
do {
printf("This loop will run forever.\n");
break; // Remove this break statement to see the infinite loop
} while (1);
return 0;
}
Nesting of Do While Loops
You can nest do while
loops within each other to perform more complex iterations.
#include
int main() {
int i = 1, j;
do {
j = 1;
do {
printf("i = %d, j = %d\n", i, j);
j++;
} while (j <= 3);
i++;
} while (i <= 3);
return 0;
}
Examples
Here are some additional examples demonstrating the usage of do while
loops in C:
Example: Summing Numbers
#include
int main() {
int sum = 0, i = 1;
do {
sum += i;
i++;
} while (i <= 10);
printf("Sum of first 10 natural numbers is %d\n", sum);
return 0;
}
Example: Finding the Length of a String
#include
int main() {
char str[] = "Hello, world!";
int i = 0;
do {
i++;
} while (str[i] != '\0');
printf("Length of the string is %d\n", i);
return 0;
}
Example: Matrix Multiplication
#include
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{2, 0}, {1, 2}};
int c[2][2] = {0};
int i = 0, j, k;
do {
j = 0;
do {
k = 0;
do {
c[i][j] += a[i][k] * b[k][j];
k++;
} while (k < 2);
j++;
} while (j < 2);
i++;
} while (i < 2);
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}