## Functions in C++

The function in cpp, are the basic building block in c++.

In this tutorial we will learn what is mean by function, why it is used in c++ programming.

In programming language, function is referred as the segment or block which contains one or more instructions which performs specific task.

**Function** :- Function is a set of statement in block which is used to perform specific tasks.

Function in cpp is the block of code with specific task.

In c++, First we have to declare the function after that we define the function then we call the function to execute function.

In c++ program we can write one or more function which performs various task.

Their is only one and only one main function we write in program.

When executing the function instructions or statement in function are executed one after another.

In c++ programming language, their are 2 type of which are as follows

- Library function
- User defined function

### Library function

- These functions are in built functions in cpp programming.
- We can use these library functions directly by including header file and calling function directly.
- We do not write definition for that function.

**Example :- sqrt ();**

This function in built function of math which is used to calculate square root of number.

### Program to demonstrate library function in c++

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream.h> #include<math.h> void main() { //declare variable int no,root; cout <<" Enter number :"; //Taking input cin >> no; //Calculate square root of number root = sqrt(no); cout <<" Square root of number = " <<root ; getch (); } |

**Output :-**

**Enter number :**

**10**

**Square root of number = 100**

### Program description

- In above program we demonstrate sqrt() library function in cpp.
- First we declare header files. iostream.h header file for input and output stream function and math.h header file contains defination for mathematical operation functions such as ( sqrt () function)
- Next we declare variable int no;
- We take input number from user and store it to no variable.
- Next , using library function sqrt () we calculate square root of number as sqrt(no) and store result to root variable.
- We print the result value root .

### User defined function

- C++ allows programmer to create their own function which performs specific task.
- User defined function is group of statement which performs specific task . And function has its own name that of programmers choice.

**Syntax**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function function_name() { // Statement 1 // Statement 2 . . // Statement n } |

**Example**

1 2 3 4 5 6 7 |
function fun() { cout <<" function in cpp"; } |

**Output**

**Function in cpp**

## Leave a Reply