Functions with parameters

Functions with parameters and no return value

The function discussed in the previous section is not very useful. It would much more useful if it was possible to tell the function how many lines to skip. That is the function should have an input parameter, which indicates how many lines should be skipped.
The function skipthree() is now changed to the function skip, which has a parameter n indicating how many lines have to be skipped as follows:

void skip(int n)
// Function skips n lines on output
{
int I;
// a local variable to this function
//now loop n times
for(I =0; i<n; i++)
cout << endl;
}
The function does not return value hence it is declared as having type void. It now takes an integer parameter n, which indicates the number of lines to be skipped. The parameter list then consists of a type and a name for this formal parameter. Inside the body of the function (enclosed in{}) a loop control variable I is declared. This variable is a local variable to the function. A local variable defined within the body of the function has no meaning, or value, except within the body of the function. It can use an identifier name that is used elsewhere in the program. Thus changing the value of the local variable I in the function skip will not affect the value of any other variable I used elsewhere in the program. Similarly changing the value of a variable I used elsewhere in the program will not affect the value of the local variable I in skip.

The function is called in the same manner as skipthree() above, but a value must be given for the parameter n. Thus all the following calls are acceptable:

void main()
{
int m=6, n=3;
…..;
skip(m);
….;
skip(m+n);
….;
skip(4);
….;
}
However the call:
skip(4.0);

would not be acceptable because the actual parameter type must match the formal parameter type given in the definition of the function.
In writing the function prototype for a function with parameters it is not necessary to detail the formal names given to the parameters of the function, only their types. Thus a suitable function prototype for the parameter version of skip would be:
void skip(int);   //function prototype

Leave a Reply

Your email address will not be published.