0

I'm attempting to write a program that will read positive integers and compute and print their sum using a sentinel-controlled loop. The code that I have copied below works, however it requires me to call the scanf function twice in order for the program to pause and read the input without executing the loop for a second time. When I only call one scanf function it seems to get ignored and the loop is executed again. Does anyone know why this is happening?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Use a Sentinel-Controlled Loop To Read Positive integers and compute and print their sum
    unsigned int memory;
    unsigned int accumulator = 0;
    char write;


    while (1)
    {
        //Adding a number to memory
        puts("Enter the number you would like to commit to memory:");
        scanf("%d",&memory);
        printf("Adding %d\n", memory);

        //Loading the numbeNr to the accumulator
        accumulator += memory;
        printf("Sum %d\n", accumulator);

        //Adding an additional number
        puts("Would you like to add another number? Y/N");
        scanf("%c", &write);
        scanf("%c", &write);
        if (write == 'N')
            break;
    }
}
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
  • Add a space before `%c` in your format string to skip leading whitespace. `scanf(" %c", &write);` Without it the first one reads the newline character from the previous input. – Retired Ninja May 30 '22 at 06:15

0 Answers0