### 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!!

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950`` ``````#include #include 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!

 ``123`` ``````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.