1

I have a question. When I try to ask a user to enter yes or no as a single character and set the char variable with brackets as I either get that Y or y is not valid in my if statement. If I do it without brackets I only get the ascii value which will evaluate in the if statement. The following code would fail to evaluate recAnswer value. When I output the value in a printf it would show that recAnswer = "Y" or "y" depending on the input. I've tried if(&recAnswer == "Y") and if(*recAnswer = "Y")

int main(int argc, char** argv)
{
  int numEntered;
  char recAnswer[1];

  while(numEntered < 1 || numEntered > 15) // Continually ask user to enter a number until the number entered is between 1 and 15 . 
  {
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } 
  printf("\nDo you want to get the factorial value recursively? Enter Y or N:"); //Ask user if they want to get the answer recursively 
  scanf(" %c",&recAnswer);
     
if(recAnswer == "y" || recAnswer == "Y")
{
  printf("The recursive value of %d is %d", numEntered, recursive(numEntered)); //Print out recursive value
}   
else
{
  printf("The non-recursive value of %d is %d", numEntered, nonRecursive(numEntered));  //Print out looped value
}
return 0;
}

Thank you for looking into this

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jose Ortiz
  • 705
  • 1
  • 9
  • 19
  • Should be `char answer;` and `if (answer == 'y' || answer == 'Y')`. You got the `scanf(" %c", &answer);` right. – user3386109 Apr 02 '21 at 19:33

1 Answers1

2

For starters this loop

  while(numEntered < 1 || numEntered > 15) // Continually ask user to enter a number until the number entered is between 1 and 15 . 
  {
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } 

invokes undefined behavior because the variable numEntered was not initialized.

int numEntered;

substitute the while loop for a do-while loop like

  do
  {
     numEntered = 0;
     printf("\nPlease enter a number between 1 and 15:");
     scanf(" %d", &numEntered);
  } while(numEntered < 1 || numEntered > 15); // Continually ask user to enter a number until the number entered is between 1 and 15 . 

Secondly if you are going to enter one character then there is no sense to declare an array with one element like

char recAnswer[1];

(Note: Moreover you are using an incorrect argument for the conversion specifier %c

scanf(" %c",&recAnswer);
            ^^^^^^^^^^^ 
  • end note)

Declare an object of the type char and initialize it for example with the constant 'n'.

char recAnswer = 'n';

And change the if statement the following way

if(recAnswer == 'y' || recAnswer == 'Y)

that is use character integer constants instead of string literals.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • This will also fix the problem that `&recAnswer` did not have the correct type in `scanf(" %c",&recAnswer);`. – nielsen Apr 02 '21 at 19:40