• Home
  • C++ Function With Examples

C++ Function With Examples

Functions are a fundamental concept in C++ and are used to divide a large program into smaller, more manageable chunks of code. A function is a self-contained block of code that performs a specific task and can be called from anywhere in the program. Functions can also accept input in the form of parameters and return output in the form of a return value.

Here is an example of a simple function in C++ that calculates the area of a rectangle:

#include <iostream>

using namespace std;

// Function prototype
int calcArea(int length, int width);

int main()
{
// Declare variables
int length, width, area;

// Get length and width from user
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "Enter the width of the rectangle: ";
cin >> width;

// Calculate area of rectangle
area = calcArea(length, width);

// Print area
cout << "The area of the rectangle is: " << area << endl;

return 0;
}

// Function definition
int calcArea(int length, int width)
{
return length * width;
}

In this example, the function calcArea() calculates the area of a rectangle based on its length and width, which are passed as parameters. The function returns the result as an integer. The main() function calls calcArea() and passes it the length and width of the rectangle entered by the user. The function returns the result, which is then printed to the screen.

Functions can also be defined with or without a return value, and they can accept any number of parameters of any data type. They can also be defined with default values for their parameters, which allows them to be called with fewer arguments.