0

The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.

#include <stdio.h>

int sum(int num);
int fact(int num);

int main(void)
{
     int x = 0;
     char choice;
     printf("Enter a number :  \n");
     scanf("%d", &x);
     printf("Enter f for factorial, s for sum \n");
     choice = getchar();

     //These lines are ignored by C
     if (choice == 'f' || choice == 'F')
     {
         printf("The factorial of %i is %i \n",x, fact(x));
     }
     else if (choice == 's' || choice == 'S')
     {
        printf("The sum from 1 to %i is %i \n",x, sum(x));
     }
}

int sum (int num)
{
     int sum =0;
     for (int i =1; i <=num; i++ )
        sum = sum+i;
        return sum;       
}

int fact (int num)
{
     int fact =1;
     for (int i =1; i <=num; i++ )
        fact = fact*i;
        return fact;       
}

Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.

shiro.asakura
  • 36
  • 1
  • 5
  • Possible duplicate of [Why doesn't getchar() wait for me to press enter after scanf()?](http://stackoverflow.com/questions/1391548/why-doesnt-getchar-wait-for-me-to-press-enter-after-scanf) – msc Apr 15 '17 at 08:55

2 Answers2

1

I think buffer problem. So, use

scanf(" %d", &x);
      ^^^
     white-space

instead of

scanf("%d", &x);

and also, use

scanf(" %c", &choice);

instead of

choice = getchar();
msc
  • 33,420
  • 29
  • 119
  • 214
0

The problem in this code is in getchar() function.

In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.

In second scanning: choice = getchar();, it reads the enter key in variable choice. And you have written only two conditions:

  1. if (choice == 'f' || choice == 'F')
  2. else if (choice == 's' || choice == 'S')

That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'

if you write 'else' part like this:

   else  printf("%d", choice);

It will print: 10 which is the ascii value of Enter / New line feed.

To avoid this, try to make following changes in your code:

int x = 0;
char choice;
printf("Enter a number :  \n");
scanf("%d", &x);     //here the integer is scanned in variable 'x'
choice = getchar();     //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice);  //here the character entered by use will be stored in variable 'choice' so it is overwritten.
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67