Type void For Functions


 

 Type void For Functions

Sample program

// Outputs three random numbers
 
#include <iostream>  // Declaration of cin and cout
#include <cstdlib>   // Prototypes of srand(), rand():
                     // void srand( unsigned int seed );
                     // int rand( void );
using namespace std;
int main()
{
   unsigned int seed;
   int z1, z2, z3;
   
   cout << "   --- Random Numbers  --- \n" << endl;
   cout << "To initialize the random number generator, "
        << "\n please enter an integer value: ";
   cin  >> seed;      // Input an integer
   
   srand( seed);      // and use it as argument for a
                      // new sequence of random numbers.
   
   z1 = rand();       // Compute three random numbers.
   z2 = rand();
   z3 = rand();
   
   cout << "\nThree random numbers: "
        << z1 << "   " << z2 << "   " << z3 << endl;
   
   return 0;
} 

Note 
The statement cin >> seed; reads an integer from the keyboard, because seed is of the unsigned int type.

Sample screen output

--- Random Numbers  ---
 
To initialize the random number generator,
please enter an integer value: 7777
   
Three random numbers: 25435   6908   14579 

Functions without Return Value

You can also write functions that perform a certain action but do not return a value to the function that called them. The type void is available for functions of this type, which are also referred to as procedures in other programming languages.
Example:
void srand( unsigned int seed ); 
The standard function srand() initializes an algorithm that generates random numbers. Since the function does not return a value, it is of type void. An unsigned value is passed to the function as an argument to seed the random number generator. The value is used to create a series of random numbers.

Functions without Arguments

If a function does not expect an argument, the function prototype must be declared as void or the braces following the function name must be left empty.
Example:
int rand( void );      // or   int rand(); 
The standard function rand() is called without any arguments and returns a random number between 0 and 32767. A series of random numbers can be generated by repeating the function call.

Usage of srand() and rand()

The function prototypes for srand() and rand() can be found in both the cstdlib and stdlib.h header files.
Calling the function rand() without previously having called srand() creates the same sequence of numbers as if the following statement would have been proceeded:
srand(1); 
If you want to avoid generating the same sequence of random numbers whenever the program is executed, you must call srand() with a different value for the argument whenever the program is run.
It is common to use the current time to initialize a random number generator. See Chapter 6 for an example of this technique.

Post a Comment

0 Comments