Functions with arguments
How can we extend the printRoad()
function to print a road with a certain number of segments? The answer is simple. We can let the printRoad()
function accept a parameter, called numSegments
, to print a certain number of road segments.
The following code snippet shows how that will look:
void printRoad(int numSegments) { // use a for loop to print numSegments road segments for( int i = 0; i < numSegments; i++) { cout << "* *" << endl; cout << "* | *" << endl; cout << "* | *" << endl; cout << "* *" << endl; } }
The following screenshot shows the anatomy of a function that accepts an argument:
Call this new version of printRoad()
, asking it to print four segments, as follows:
printRoad( 4 ); // function call
The 4 between the brackets of the function call
in the preceding statement gets assigned to the numSegments
variable of the printRoad(int numSegments...