'How to make a loop continuously keep asking for user input until a given character is entered that stops the program?
I have this program:
int main(void){
int x, number, factorial;
// The objective of this program is to compute the factorial
// for a user inputted number, stopping once "-1" is entered.
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
for (x = 1; x <= number; x++){
factorial *= x;
if (x == -1){
break;
}
}
printf("factorial for %d is %d", number, factorial);
}
that is supposed to output like this:
Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24
Please enter a positive number for factorial calculation (-1 to end) :6
factorial for 6 is 720
Please enter a positive number for factorial calculation (-1 to end) :8
factorial for 8 is 40320
Please enter number for factorial calculation (-1 to end) :-1
but I keep getting this (on two different runs):
Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24
Please enter a positive number for factorial calculation (-1 to end) :-1
factorial for -1 is 1
How could I make it so that it continues to ask for more numbers until I type in -1? Also, why does typing -1 here give me the factorial for it instead of stopping the loop?
Solution 1:[1]
You could wrap the factorial calculation inside a loop like this:
int number;
int factorial = 1;
while(true) {
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
if (number == -1)
break; // or just return as you need
for (x = 1; x <= number; x++){
factorial *= x;
}
printf("factorial for %d is %d", number, factorial);
factorial = 1;
}
In this case you would receive the number as input and just begin checking what the user have input.
In your code you were checking inside the for loop for x variable to be different than -1 but that condition would never be met as you were assigning 1 to x just when you begin the loop. In that case you should check for number but it would not be all correct.
Solution 2:[2]
Use a While loop and check the value after user input to see if you need to break out of the loop:
int main(void){
int x, number, factorial;
// The objective of this program is to compute the factorial
// for a user inputted number, stopping once "-1" is entered.
while (true){
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
if (number == -1){
break;
}
for (x = 1; x <= number; x++){
factorial *= x;
}
printf("factorial for %d is %d", number, factorial);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jorge Machado |
| Solution 2 | Ryan Wilson |
