This is another GCD program. Everything is working correctly besides validating the inputs correctly.
My goal:
Provide a function to get a nonzero positive integer from the keyboard and return it to the caller.
int get_input()
If input is not valid, the function should output an error message and repeat the input operation.
Be sure your input function works correctly with invalid inputs.
Even inputs that are not integers
123.456 (Should return 123)
abc (Should output error message and repeat input.)
Here's the code:
Code:
#include <stdio.h>
int gcd(int x, int y);
int gcd(int x, int y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
int get_input(int x, int y)
{
while(1)
{
if (x > 0 || y > 0)
{
return 1;
}
else
{
printf("Input error");
printf("Please enter an integer greater than 0");
while(getchar() != '\n'); //Clears input buffer
}
}
}
int main()
{
int x, y, input, common;
printf("This program computes the greatest common divisor\n");
printf("of positive integers X and Y, entered by the user.\n");
printf("Inputs must be integers greater than zero.\n\n");
printf("Enter integer X: \n");
scanf("%d", &x);
printf("Enter integer Y: \n");
scanf("%d", &y);
input = get_input(x,y);
common = gcd(x, y);
printf("The GCD of %d and %d is %d\n", x, y, common);
return 0;
}
I don't think I have it validating my inputs correctly. Also, the error message doesn't show if I input zero. For example,
Enter integer X:
123.123
Enter integer Y:
The GCD of 123 and 4 is 1
It skips Y automatically and it shouldn't according to the sample output I have. I'm not sure how to fix this. Also, when I enter "abc" it just doesn't work as the sample output. Here's the sample out put.
Enter integer X: 0
Please enter an integer greater than 0
123.456
Enter integer Y: Please enter an integer greater than 0
abc
Please enter an integer greater than 0
44
The GCD of 123 and 44 is 1
I appreciate it if someone can give me tips on how to go on doing this. Thanks.