-
Some quick advice
Wondering if someone could point me in the right direction.
Below is some code which performs a simple calc on a number if it is greater the 1 and then stops and outputs the Count when the number finally reaches 1.
Now so far i've only able to make it so you input one Int and you then get the reuslt.
I would like to be able to input a number, have the code run through the numbers, output the count for that particular number, then Increase the original inputted by one and continue running, ad infinitum.
Any ideas what i should do?
rewrite the whole thing again using some For loop?, maybe these mystical array things, or am i just out of my depth :D
Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int count = 1;
int N;
int X;
cout<<"Input Number: ";
cin>> N;
cin.ignore();
X=N;
while (X != 1)
{
if (X % 2 == 0)
{
X /= 2;
}
else
{
X = X * 3 + 1;
}
++count;
}
cout << "cycle length of " << N << " is " << count << endl;
cin.get();
return 0;
}
-
im guessing just a while loop... while (cin.get()==0) perhaps? im unsure, best get somebody more knowladgeable to answer! anyway heres it properly indented (well a bit more properly).
Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int count = 1;
int N;
int X;
cout<<"Input Number: ";
cin>> N;
cin.ignore();
X=N;
while (X != 1)
{
if (X % 2 == 0)
{
X /= 2;
}
else
{
X = X * 3 + 1;
}
++count;
}
cout << "cycle length of " << N << " is " << count << endl;
cin.get();
return 0;
}
-
You are actually really close. Take all the code that uses X and put it inside a while loop. Then, increment N by 1 each time through (after the output at the end of the new loop).
So really, you don't have to rewrite the whole thing, you just have to use your existing code and add to it. If you know functions, putting the code that uses X inside a function would be perfect.
-
Thanks guys for the reply, i've got all night so best put on the coffee :D
-
All night?
Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int count = 1;
int N;
int X;
int end;
cout<<"Input Number: ";
cin>> N;
cout << "Input upper bounds: ";
cin >> end;
cin.ignore();
for (int i = N; i <= end;X++,N++,i++)
{
X=N;
while (X != 1)
{
if (X % 2 == 0)
{
X /= 2;
}
else
{
X = X * 3 + 1;
}
++count; //Make sure you know the difference between ++variable and variable++
} //end of While loop
cout << "cycle length of " << N << " is " << count << endl;
count = 1; //Resets count for next iteration
} //End of for loop
cin.get();
return 0;
}//end of main
Your for loop idea, or you can make it even 'neater' and 'nicer' by following Daved's suggestions and making it a function.
-
Wow thanks,
and yes it looks like it definately would have taken me all night :)