1

Why doesn't this loop continue after I enter the letter y into the char answer?

I thought getchar() would help but it doesn't seem like its doing anything.

#include <stdio.h>

int main(void)
{
    char answer = 'y';
    int num = 0;
    printf("Enter a number: \n");
    scanf("%d", &num);

    while(answer != 'n')
    {
        int mult = 1;
        int k = 1;
        while (k <= num)
        {
            mult *= k;
            k++;
        }
        printf("%d! = %d\n", num, mult);

        printf("Would you like to try another number? \n");
        printf("Enter: y for yes | n for no\n");
        getchar();
        scanf("%c", &answer);
    }       
}
4
  • if you expect your loop to return to the printf("Enter a number: \n")-part, please note that this part is outside of the loop. What do you actually observe and what do you expect? Commented Nov 21, 2018 at 10:57
  • 1
    If you want to skip leading white-space before a character, use a format string with a space. As in " %c". Also note that with your loop condition, anything but a lower-case 'n' would continue the loop, not only 'y'. Commented Nov 21, 2018 at 10:57
  • 2
    And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result from getchar in a dummy variable so you can check that too). Commented Nov 21, 2018 at 11:00
  • I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem Commented Nov 21, 2018 at 11:04

3 Answers 3

2

I have made few corrections in your program.

  1. It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for factorial.
  2. It makes more sense to ask user again for the number if user has entered 'y'. So, I have moved required code.
  3. I don't recommend mix use of scanf and getchar in the program. So, we can just use scanf for the program. The scanf() function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.

Use " %c" with a leading blank to skip optional white space. Do not use a trailing blank in a scanf() format string.

Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.

#include <stdio.h>


unsigned long factorial(unsigned long num)
{
    unsigned long mult = 1;
    unsigned long k = 1;
    while (k <= num) {
        mult *= k;
        k++;
    }

    return mult;
}

int main(void)
{
    char answer = 'y';

    do {
        int num = 0;
        printf("Enter a number: \n");
        scanf(" %d", &num);


        unsigned long mult = factorial(num);
        printf("%d! = %lu\n", num, mult);

        printf("Would you like to try another number? \n");
        printf("Enter: y for yes | n for no\n");
        scanf(" %c", &answer);

    } while (answer != 'n');  

    return 0;   
}   
Sign up to request clarification or add additional context in comments.

Comments

0
    getchar(); // takes the user input but assigns it nowhere
    scanf("%c", &answer); // reads newline, aborts while loop

Use c = getchar(); and omit the scanf.

Also note that a more idiomatic way of doing this would be with a do-while loop instead.

1 Comment

In the first iteration that will read the newline left over from the first call to scanf.
0

Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n.

This is a one way to do it starting from your code:

    #include <stdio.h>

    int main(void)
    {
            char answer = 'y';
            int num = 0;

            while(answer != 'n')
            {
                    printf("Enter a number: \n");
                    scanf("%d", &num);
                    int mult = 1;
                    int k = 1;
                    while (k <= num)
                    {
                            mult *= k;
                            k++;
                    }
                    printf("%d! = %d\n", num, mult);

                    printf("Would you like to try another number? \n");
                    printf("Enter: any key for  yes | n for no\n");
                    getchar();
                    scanf("%c", &answer);
            }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.