Hmm
if (a <= b), the rest of your code (lines 18-25 will never run and uninitialised GCD will be some random value
if (a > b), then b%a == b, and you'll skip to line 20. From here, it runs away from you:
you're stuck in your second while loop until b == 1, at which point you'll wind up back at 17, and you'll forever be stuck between 17 and 18.
If you ever wonder why people get so passionate about code formatting, indentation and brace placement, this is why. I've reformatted the code, and it should be clearer why it's going wrong.
P.S. With this sort of problem it's better you give examples of bothe input and related output, and don't leave us guessing about whether GetInteger() is actually messing things up or not...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
/*
* File name: GCD1.c
* This program computes and displays the greatest common divisor of two numbers.
*/
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
main()
{
int a, b, c, GCD;
printf (" Enter a number: \n");
a = GetInteger();
printf (" Enter a second number: \n");
b = GetInteger ();
while (a>b)
{
if (b%a == 0)
{
GCD = b;
}
else
{
while (b%a != 1)
{
b--;
c=b%a;
if (c==0)
{
GCD = b;
}
}
}
}
printf (" The GCD of %d and %d is %d", a, b, GCD);
getchar();
}
|
I think you can clearly see that if (a <= b) you'll never into that first while look, and if (a > b) you'll never get out of it.