在C語言中,while循環是一種基本的控制結構,用于重復執行一段代碼,直到給定的條件不再滿足
#include<stdio.h>
int main() {
int n, sum = 0, i = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) {
sum += i;
i++;
}
printf("Sum of all integers from 1 to %d is: %d\n", n, sum);
return 0;
}
#include<stdio.h>
#include <stdbool.h>
int main() {
int num, i = 2;
bool isPrime = true;
printf("Enter a positive integer: ");
scanf("%d", &num);
while (i * i <= num) {
if (num % i == 0) {
isPrime = false;
break;
}
i++;
}
if (isPrime && num > 1) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
#include<stdio.h>
int main() {
int arr[100], i = 0, input;
printf("Enter integers (end with -1): ");
while (1) {
scanf("%d", &input);
if (input == -1) {
break;
}
arr[i] = input;
i++;
}
printf("You entered the following integers:\n");
for (int j = 0; j < i; j++) {
printf("%d ", arr[j]);
}
printf("\n");
return 0;
}
這些示例展示了C語言中while循環的實際應用。在每個示例中,while循環都用于根據特定條件重復執行一段代碼。