Reputation: 63
#include <stdio.h>
#include <math.h>
long factcalc(int num1);
int main(void)
{
int num1;
long factorial;
int d;
int out;
printf("Please enter a number that is greater than 0");
scanf_s("%d", &num1);
if (num1 < 0) {
printf("Error, number has to be greater than 0");
} else if (num1 == 0) {
printf("\nThe answer is 1");
} else {
factorial = factcalc(num1);
printf("\nThe factorial of your number is\t %ld", factorial);
}
return 0;
}
long factcalc(int num1)
{
int factorial = 1;
int c;
for (c = 1; c <= num1; c++)
factorial = factorial * c;
return factorial;
}
I was wondering, how do I make it so that the program keeps asking the user for input until the user inputs '-1'? So that even after it has calculated the factorial of one number it keeps asking for more numbers until -1 is put in by the user, same goes for when it displays the error message and such. Thanks in advance.
Upvotes: 0
Views: 4768
Reputation: 510
Yes, as suggested by @ameyCU, using loop is solution. For example,
while (1)
{
printf("Please enter a number that is greater than 0");
scanf_s("%d", &num1);
if (-1 == num1)
{
break;
}
// Find factorial of input number
...
...
// Loop back to get next input from user
}
Upvotes: 0
Reputation: 6679
There are a select few scenarios where using goto
is "okay," but this is surely not one.
First, put the relevant bits of your program into functions.
Then, monitor and use the user input like so:
int number = -1;
while (scanf("%d", &number)) {
if (-1 == number) {
break;
}
call_foo_function(number);
}
Upvotes: 1
Reputation: 75062
It can be easily achieved by introducing an infinite loop.
#include <stdio.h>
#include <math.h>
#ifndef _MSC_VER
#define scanf_s scanf
#endif
long factcalc(int num1);
int main(void)
{
int num1;
long factorial;
int d;
int out;
for (;;) {
printf("Please enter a number that is greater than 0");
scanf_s("%d", &num1);
if (num1 == -1) {
break;
}
else if (num1 < 0) {
printf("Error, number has to be greater than 0");
}
else if (num1 == 0) {
printf("\nThe answer is 1");
}
else {
factorial = factcalc(num1);
printf("\nThe factorial of your number is\t %ld", factorial);
}
}
return 0;
}
long factcalc(int num1) {
int factorial = 1;
int c;
for (c = 1; c <= num1; c++)
factorial = factorial * c;
return factorial;
}
Upvotes: 5