Calculating cube area in C++: using the function default parameter values

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Calculating cube area in C++: using the function default parameter values

To show: How to use the default function parameter values in C++ programming

 

// demonstrates the use of default parameter values

#include <iostream>

using namespace std;

 

// function prototype

// width = 25 and height = 1, are default values

int AreaOfCube(int length, int width = 25, int height = 1);

 

int main(void)

{

// Assigning new values

int length = 100;

int width = 50;

int height = 2;

int area;

 

// prompting the data

cout<<"length = 100, width = 50, height = 2, finding the area.\n";

// function call

area = AreaOfCube(length, width, height);

cout<<"\narea = AreaOfCube(length, width, height);\n";

cout<<"First time function call, area = "<<area<<"\n";

// function call again

area = AreaOfCube(length, width);

// height = 1, default value

cout<<"\narea = AreaOfCube(length, width);\n";

cout<<"Second time function call, area = "<<area<<"\n";

area = AreaOfCube(length);

// width = 25, height = 1, default values

cout<<"\narea = AreaOfCube(length);\n";

cout<<"Third time function call, area = "<<area<<"\n";

 

return 0;

}

 

// function definition

int AreaOfCube(int length, int width, int height)

{

return (length * width * height);

}

 

Output example:

 

length = 100, width = 50, height = 2, finding the area.

area = AreaOfCube(length, width, height);

First time function call, area = 10000

area = AreaOfCube(length, width);

Second time function call, area = 5000

area = AreaOfCube(length);

Third time function call, area = 2500

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index