while loops in C Language:
While Loops in C
The while
loop in C is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop runs as long as the condition is true.
while (condition) {
// statements
}
Basic While Loop
A basic while
loop continues to execute as long as the condition is true.
#include
int main() {
int i = 0;
while (i < 5) {
printf("i = %d\n", i);
i++;
}
return 0;
}
While Loop with Multiple Conditions
You can use logical operators to create more complex conditions.
#include
int main() {
int i = 0, j = 5;
while (i < j && j > 0) {
printf("i = %d, j = %d\n", i, j);
i++;
j--;
}
return 0;
}
Infinite While Loop
A while
loop can run indefinitely if the condition is always true.
#include
int main() {
while (1) {
printf("This loop will run forever.\n");
break; // Remove this break statement to see the infinite loop
}
return 0;
}
While Loop with Empty Body
A while
loop can have an empty body, which is useful for performing operations within the condition part.
#include
int main() {
int i = 1;
while (i++ < 5);
printf("i = %d\n", i);
return 0;
}
Nesting of While Loops
You can nest while
loops within each other to perform more complex iterations.
#include
int main() {
int i = 1, j;
while (i <= 3) {
j = 1;
while (j <= 3) {
printf("i = %d, j = %d\n", i, j);
j++;
}
i++;
}
return 0;
}
Examples
Here are some additional examples demonstrating the usage of while
loops in C:
Example: Summing Numbers
#include
int main() {
int sum = 0, i = 1;
while (i <= 10) {
sum += i;
i++;
}
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;
while (str[i] != '\0') {
i++;
}
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;
while (i < 2) {
j = 0;
while (j < 2) {
k = 0;
while (k < 2) {
c[i][j] += a[i][k] * b[k][j];
k++;
}
j++;
}
i++;
}
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}