userac67
userac67

Reputation: 19

Error from order of statements in a while loop

The code snippet in C:

#include <stdio.h>

int main(void)
{
      int n, sum = 0;
      printf("This program lists terms with each term being sum of previous terms and itself\n");
      printf("Enter integers (0 to terminate): ");

      scanf("%d", &n);
      
      while (n != 0) {
          sum += n;
          scanf("%d", &n);
          printf("The sum is: %d\n", sum);
      }
}

If I input 1, 2, 3; my expected output is 1, 3 and 6. However 6 is omitted unless I swap the scanf statement with printf statement in the while loop. Why is that?

Upvotes: 0

Views: 81

Answers (2)

lvella
lvella

Reputation: 13481

"unroll" your loop and you will see the problem:

scanf("%d", &n);
// <- 1

sum += n;
scanf("%d", &n);
// <- 2
printf("The sum is: %d\n", sum);
// -> The sum is: 1

sum += n;
scanf("%d", &n);
// <- 3
printf("The sum is: %d\n", sum);
// -> The sum is: 3 

// You think you are done here, but you still haven't typed 0 to terminate the program.

sum += n;
scanf("%d", &n);
// <- 0
printf("The sum is: %d\n", sum);
// -> The sum is: 6

Basically, your print delayed by one number.

Upvotes: 3

Rakesh Rebbavarapu
Rakesh Rebbavarapu

Reputation: 108

The problem with your code is after your entered 3 the program is stuck at the scanf, so it is waiting for the input. To avoid that first print the sum and then read the next input. The number is getting added to the sum but it just not printing to the console.

#include <stdio.h>

int main(void)
{
      int n, sum = 0;
      printf("This program lists terms with each term being sum of previous terms and itself\n");
      printf("Enter integers (0 to terminate): ");

      scanf("%d", &n);
      
      while (n != 0) {
          sum += n;
          printf("The sum is: %d\n", sum);
          scanf("%d", &n);
      }
}

Upvotes: 1

Related Questions