Jose Ortiz
Jose Ortiz

Reputation: 725

Input number resets to 0 after scanf

I have a weird issue. I ask a user to enter a number between 1 and 15. Then I would ask the user would the like to get the factorial value of the number using either recursive or a for loop. When they answer that question the inputted value goes to 0. If I remove the question for testing purpose the value stays the value the user inputted.

#include <stdio.h>
    int recursive(int);
    int nonRecursive(int);
    
    int main() 
    {
      /* Variables */
      int numberSelected, returnedValue;
      char answer;
      
      do
      {
        /* Request a number between 1 and 15 */
        printf("Please enter a number between 1 and 15: ");
        scanf("%d", &numberSelected);
        printf("%d\n", numberSelected); /* This prints out the user's number */
      }while(numberSelected < 1 || numberSelected > 15); /* Loops if the value is not between 1 and 15 */
      
      /* Ask user if they want to return a recursive value or a value calculated manually */
      printf("Would you like a recusive value of the number you entered? Y or N: ");
      scanf("%s", &answer);
      if(answer == 'y' || answer == 'Y')
      {
        printf("%d\n", numberSelected); /* Here it resets to 0 */
        returnedValue = recursive(numberSelected); /* Returns the recursive value */
        printf("The recursive value of %d is %d\n", numberSelected, returnedValue);
      }
      else
      {
        printf("%d\n", numberSelected); /* Here it resets to 0 also*/
        returnedValue = nonRecursive(numberSelected); /* Returns the value from for loop */
        printf("The non recursive value of %d is %d\n", numberSelected, returnedValue);
      }
     
      
      return 0;
    }
    /* Get value using recursive */
    int recursive(int n)
    {
     if (n == 0)
     return 1; // Base case
     else
     return n * recursive(n - 1);
    }
    
    /* Get value using for loop */
    int nonRecursive(int n)
    {
      int i;
      int fact = 1;
      for(i = 1; i <= n; i++)
      {
         fact *= i;
      }
     
      return fact;
    }

Thank you for the help

Upvotes: 0

Views: 416

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

scanf("%s", &answer);

is wrong. %s is for reading strings (null-terminated sequence of characters), but answer has only room for 1 character, so out-of-bound write will occur when strings with one or more characters is read. It may break data around that.

The line should be

scanf(" %c", &answer);
  • Use %c, which reads single character.
  • Add a space before %c to have scanf() ignore whitespace characters.

Upvotes: 5

Related Questions