C While Loop Input Data Tutorial

Below is an example of C code that uses a while loop to input data.

#include <stdio.h>

int main() {
    int num;
    int sum = 0;

    printf("请输入数字(输入0结束):\n");
    while (1) {
        scanf("%d", &num);
        if (num == 0) {
            break;  // 输入0时结束循环
        }
        sum += num;
    }

    printf("所有输入数字的和为:%d\n", sum);

    return 0;
}

In the code above, an infinite loop while (1) is used, and within the loop, the scanf function is used to get the number input by the user. If the input number is 0, the break statement is used to exit the loop. Otherwise, the input number is added to the variable sum. Finally, the sum of all input numbers is output.

bannerAds