Question

I need to create a function named hailstone that takes the starting integer as a parameter...

I need to create a function named hailstone that takes the starting integer as a parameter and returns how many steps it takes to reach 1. You will stop when you reach the first one. If the starting integer is 1, the return value should be 0. The function should just return the value not display it. You CANNOT use recursion. C++

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

int hailstone(int num) {
    int count = 0;
    while (num != 1) {
        if (num % 2 == 0)
            num /= 2;
        else
            num = 3 * num + 1;
        count++;
    }
    return count;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Number of steps = " << hailstone(num) << endl;
    return 0;
}

Add a comment
Know the answer?
Add Answer to:
I need to create a function named hailstone that takes the starting integer as a parameter...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT