I need help on my coding

I am doing Ulam sequence and I am not sure why its going infintely loop after going into void function. If i type 40, its suppose to go 40, 20, 10, 5, 16, 8, 4, 2 , 1 and than getout. But mine goes 20 infintely.

Here is my function:

void evenFunction(int number), oddFunction(int number);
int main()
{
int number;

cout << "Enter an integer. (Can't be decimal)" << endl;
cin >> number;
if (number < 1)
cout << "Error Occured" << endl;
else
do{
evenFunction(number);

} while (number != 1);
return 0;
}
void evenFunction(int number)
{
if ((number % 2) == 0)
{

number = number / 2;
cout << number << endl;
}
else
oddFunction(number);
}
void oddFunction(int number)
{
if ((number % 2) != 0)
{

number = number * 3 + 1;
cout << number << endl;
}
else
evenFunction(number);

}

Its because, the loop is not working.

evenFunction(number);

Inside the loop you are sending in is not the original number, just the value. the void functions will recieve a copy of number and work with it. So now they are performing things on a copy of number. First. Prototype your functions like this -

1
2
void evenFunction(int& number);
void oddFunction(int& number);


Put that above your main. You see the "&". if you put that where it is in the code above, then you will make a call by reference, rather than call by value, meaning you will give the functions the adress of "number". So they will be able to work on the original one!

So just put that in your functions -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void evenFunction(int& number) // Here
{
	if ((number % 2) == 0)
	{

		number = number / 2;
		cout << number << endl;
	}
	else
		oddFunction(number);
}
void oddFunction(int& number) // Here
{
	if ((number % 2) != 0)
	{

		number = number * 3 + 1;
		cout << number << endl;
	}
	else
		evenFunction(number);

}
Last edited on
Thank YOU SO MUCH !
Topic archived. No new replies allowed.