Functions in cpp : In this tutorial we will learn what is mean by function, why it is used in c++ programming.
The function in cpp, are the basic building block in c++.
In programming language, function is referred as the segment or block which contains one or more instructions which performs specific task.
Function definition :- Function is a set of statement in block which is used to perform specific tasks.
It 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
1. Library function
2. User defined function
1. 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.
function example :
sqrt ();
This function in built function of math which is used to calculate square root of number.
Function program in cpp
123456789101112131415161718192021222324 | #include <iostream>#include<math.h>using namespace std;int main(){//declare variableint no,root;cout <<” Enter number :”;//Taking inputcin>>no;//Calculate square root of numberroot=sqrt(no);cout <<” Square root of number = ” <<root ; return 0;} |
Output :

Program description :
1. In above program we demonstrate sqrt() library function in cpp.
2. First we declare header files. iostream.h header file for input
and output stream function and math.h header file contains definition for mathematical operation functions such as ( sqrt () function)
3. Next we declare variable int no;
4. We take input number from user and store it to no variable.
5. Next , using library function sqrt () we calculate square root of number as sqrt(no) and store result to root variable.
6. We print the result value root .
2. 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.
Function Syntax
123456789101112131415 | function function_name(){// Statement 1// Statement 2..// Statement n} |
Function example
1234567 | void fun(){cout <<” function in cpp”;} |
User defined function program in cpp
1234567891011121314151617181920 | #include <iostream>#include<math.h>using namespace std;void fun(){cout <<” \n User defined function in cpp”;}int main(){//declare variablefun(); return 0;} |
Output :

Function in cpp