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:

Functions with arguments

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) function. This is how the value 4 gets passed to numSegments:

Functions with arguments

An illustration of how printRoad(4) will assign the value 4 to the numSegments variable

So, numSegments gets assigned the value passed between the brackets in the call to printRoad().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.153