Rishi Shukla Rishi Shukla - 1 year ago 82
C Question

Do while loop with Character input

I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.

since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !

I googled and found out the problem could be due to

new line
character getting accepted with my character input so, I modified the scanf code from
scanf("%c", &choice);
scanf("%c ", &choice);
in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.

Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.

#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)

void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program

do {//Makes sure the loop isn't terminated until the user decides
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);

if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;

printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result

printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);

} while (choice =="y" || choice =="Y"); // Checks if user wants to continue


I'm a beginner in programming and I'm running this code in visual studio 2015.

Answer Source

Just modify your scanf like following:

printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after

also you should use:

} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue

NOTE: Simple quote ' is used for characters and double quote " is used for string

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download