This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Monday, February 27, 2023

Give a suitable example for default argument.

 Here's an example:

#include <iostream>
using namespace std;
// function to calculate volume of a cube
double cubeVolume(double side = 1.0) {
    return side * side * side;
}
int main() {
    double side1 = 3.0; // side of cube 1
    double side2 = 4.0; // side of cube 2
    double side3 = 5.0; // side of cube 3
    
    // calculate volumes of cubes using default argument
    double volume1 = cubeVolume(); // default side = 1.0
    double volume2 = cubeVolume(side1);
    double volume3 = cubeVolume(side2);
    double volume4 = cubeVolume(side3);
    
    // display volumes of cubes
    cout << "Volume of cube with side " << side1 << " is " << volume2 << endl;
    cout << "Volume of cube with side " << side2 << " is " << volume3 << endl;
    cout << "Volume of cube with side " << side3 << " is " << volume4 << endl;
    cout << "Volume of cube with default side is " << volume1 << endl;
    
    return 0;
}

In this program, we have defined a function cubeVolume() that calculates the volume of a cube given its side length. The function has a default argument of 1.0, which means that if no argument is passed to the function, it will assume that the side length of the cube is 1.0.

In the main() function, we have created three variables side1, side2, and side3 to represent the side lengths of three cubes. We then call the cubeVolume() function four times, once without any arguments (using the default value of 1.0), and three times with the values of side1, side2, and side3, respectively.

The volumes of the cubes are then displayed using cout. Note that when we call the cubeVolume() function without any arguments, it uses the default value of 1.0 for the side length.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget