GCD Loop - "not responding"

Hey all. Trying to do a basic homework assignment which is to create a program that reads 2 integers and finds the GCD of them through a loop, not using euclid's algorithm. My program runs but once it reads the 2 integers it says the command prompt has stopped responding. Trying to figure out why, any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

// program body
void main()
{
     // variable declarations
     int num1, // input - first number inputted 
     num2, // input - second number inputted
     remain = 0; // remainder of division
     while(true)
     {
	  cout << "Enter two integers";
	  cin >> num1 >> num2;
	 	     
	  while( num1 != 0 )
	  {
	     remain = num1 % num2;
	     num1 = num2;
	     num2 = remain;
	  }
	  cout << "The GCD is " << num1 << endl << endl; 
     }
}


A good reason not to use infinite loops - there is nothing in your code to break out of that loop.

main should return an int not void:

1
2
3
4
int main () {

return 0;
}



This sort of sloppiness will cause you problems in the future:
1
2
3
int num1, // input - first number inputted 
     num2, // input - second number inputted
     remain = 0;


Declare variables on their own line.

Hope this helps.
not using euclid's algorithm
You are using Euclid's algorithm (trying at least)
it says the command prompt has stopped responding.
You are dividing by zero.

Declare variables on their own line.
meh
Okay, thanks theIdeasMan! You were right. My conditions for the while loop were incorrect, what I meant to put was:
while( num2 != 0 )

it simply wasn't exiting the loop. But I have some more questions:

Declare variables on their own line.


Is there a reason to this? I only put them on separate lines to make it easier to read and have the comments on separate lines.

main should return an int not void


Why does it have to? Is there a disadvantage to using void? I've been using void for a while now and havn't ran into much problems.


TheIdeasMan wrote:
Declare variables on their own line.


ne555 wrote:
meh


Well at least what I proposed would be better than what the OP had. And may help future traps like this:

 
int& a, b;

Is that a trap?
Well you might know, but it is a trap for some - what are the types of variables a and b?

Edit:

Perhaps it is a little more obvious like this:

int a&, b;
Last edited on
Topic archived. No new replies allowed.