Making parts of your program into function calls is easy:
// Function prototype/declaration
// * Needs to be before the function call.
// * Ends in a semi-colon
// * The 'int' at the start is the "return-type", it can be any type
// * the things in the brackets are the "arguments", any number and type can
// be specified. Only the types are needed by the compiler, the names (like
// 'x', in this case) are for people
int MyFunction( int x );
int main()
{
int x = 2;
int y = MyFunction( x ); // Function call
std::cout << "x = " << x << " y = " << y << std::endl;
return 0;
}
// Function definition
// * Contains the details of what the function actually does.
// * The return-type and argument number and types MUST match the prototype
// * The argument names must be present, but need not match the names in the
// prototype
int MyFunction( int x )
{
// The body of the function can contain anything that you would normally
// see in main() - since main() is also a fucntion :)
return 2*x;
}
What things to make into functions is your call. In general, functions are a kind of abstraction - they remove the details of how something is done from the user. This is generally good, since the user is mainly concerned with what the function does, not how it does it. Having logic in well-named functions also allows you to alter what that logic does without affecting the rest of the program and allows a piece of logic to be repeated at multiple points in the program without actually re-typing the code.
So, in your case, you could break the program into a bunch of logical bits, as suggested above. One might be "Generate a random number". This could contain details about how the range of the number is specified, what type of random-number generator is used, what user-input is required etc:
int GenerateRandom();
/* initialize random seed: */
srand ( time(NULL) );
int main()
{
int random = GenerateRandom();
std::cout << "Random = " << random << std::endl;
return 0;
}
// The actual details of the function
int GenerateRandom()
{
const int MAX_RANGE = 100; //Setting the max range
/* generate secret number: */
int random = rand() % MAX_RANGE + 1;
return random;
}
Now, you might want a bit more flexibility, but you don't want to duplicate any of the code, if you can avoid it. So, I would consider making a series of random number generating functions (note how the second one calls the first):
int GenerateRandomInRange( int min, int max )
{
return rand() % (max - min) + min;
}
int GenerateRandomWithUserRange()
{
int userMin, userMax;
std::cout << "Enter min" << std::endl;
std::cin >> userMin;
std::cout << "Enter max" << std::endl;
std::cin >> userMax;
return GenerateRandomInRange( userMin, userMax );
}
Hope that helps a little :)