阅读量:0
在C语言中,while循环是一种基本的控制结构,用于重复执行一段代码,直到给定的条件不再满足
- 计算1到n之间所有整数的和:
#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; }
- 从键盘输入中读取一系列整数,并将其存储在数组中,直到用户输入-1为止:
#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循环都用于根据特定条件重复执行一段代码。