(C language) There is a printf location question when using while.

Asked 1 years ago, Updated 1 years ago, 345 views

Hello, I am learning the basics of C language.

Currently, we have completed a coding that outputs several integers and then sums up and averages only a multiple of 3, and escapes by entering -1. I wonder where the printf's while is located inside and outside {}. Some programs function only when you put them inside, and some when you put them outside. (For convenience, include, main, and return were omitted)

It works when you put it inside

int num;
int sum = 0;

while (1) {
scanf_s("%d", &num);
if (num == -1)break;
if (num % 3 != 0) continue;

    sum = num / 3;
    printf("%d\n", sum); } // **Inserted in the WHILE phrase**

It works only when you leave it outside

It's a code that continues to output integers and then escapes when you add an odd sum, average, and enter zero.

 int num;
 int sum = 0, cnt = 0;
 double avg;

while (1) {
scanf_s("%d", &num);
if (num == 0) break;
if (num % 2 != 0) {
sum += num;
cnt++;
}
}
avg = (double)sum / cnt;
printf("sum of odd numbers = %d\n", sum); // **located outside of the WHILE syntax**
printf ("average of odd numbers = %").2lf\n", avg);

No matter how I look at it... It's the same type of coding. Why should one be in while, why should the other be outside while. I don't understand If you're fluent in C, please answer^

^

c

2022-10-23 16:00

1 Answers

Where is the repeat statement. Therefore, the output function within the iteration statement is repeatedly executed.

while (1) {
    scanf_s("%d", &num);
    if (num == -1)break;
    if (num % 3 != 0) continue;

    sum = num / 3;
    printf("%d\n", sum);
}

The printf in the above code is a line of repetitive statements, so it is executed every time it is repeated. If a number is entered and the input number is -1, it escapes the iteration statement, and outputs every multiple of 3.

while (1) {
    scanf_s("%d", &num);
    if (num == 0) break;
    if (num % 2 != 0) {

    sum += num;
    cnt++;
    }
}
avg = (double)sum / cnt;
printf("sum of odd numbers = %d\n", sum); // **located outside of the WHILE syntax**
printf ("average of odd numbers = %").2lf\n", avg);

The code above, on the other hand, has no output during a repeat run, and is output only once after the repeat run is complete.

Conclusion: When you have to print out every time during repetitive actions, you should write the output statement in the repetitive statement, and when you print out after all actions that are not in action, you should write the output statement outside the repetitive statement.


2022-10-23 16:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.