Functions & Ulam Sequence

Hello all,


I have an assignment to write a program, here are the instructions:

**Write a program w/ 2 functions, one to ask the user to enter an integer > 2 and the other to accept that integer and display on the console the Ulam Sequence. The Ulam sequence starts with an integer, if it is even, it is divided by 2, if it is odd it is multiplied by 3 and 1 is added. This provides the next number in the series. It will continue in this way until the sequence produces a value of 1.

** Here's what I have got so far and I cant get it to work right. Any help would be greatly appreciated!!

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
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
using namespace std;

int getInt(string msg)
{
	int num;
	do
	{
		cout << msg << endl;
		cin >> num;

	}while(num <= 2);

	return num;
	
}

int ulamSeq(int num)
{
	 do
	{
		if (num % 2 == 0)  
			num = num / 2;  

		else if (num % 2 > 0)  
			num = (num * 3) + 1;   

		return num;

	}while (num >1);	
	
}


int main()
{
	int num;

	getInt("Please enter a positive interger greater than 2");

	cin >> num;

	cout << "The Ulam Sequence gives the following results for your input value:" << endl;

	cout << ulamSeq(num) << endl;
	

	return 0;
}
A few things:

Line 29: replace return num; with cout << num << endl; A return here is not correct, because it jumps out of your function and you don't get any benefit from your while loop! Move your return statement after the while that is on line 31. Alternatively, remove the return altogether and declare that the function return void since you really don't need the value. You printed everything in your while loop!

Line 42: You're already reading a number in your getInt function. Replace
1
2
3
getInt("Please enter a positive interger greater than 2");

cin >> num;

with
 
num = getInt("Please enter a positive interger greater than 2");

That's the proper way to save a value that's being returned from a function.

And if you're doing all your printing inside the ulamSeq function, replace line 46 with a call to ulamSeq(num);. You don't need to cout anything there.
Last edited on
Thank you very much!!
Topic archived. No new replies allowed.