Lab Manual # 13: Title: Functions
Lab Manual # 13: Title: Functions
Lab Manual # 13
Title: Functions
CLO: CLO-1
Lab Submission[10] 0 1 2 3 4 5
Completeness & Correctness
Required Conclusion & Results
No of Checks
SUB TOTAL
TOTAL SCORE
______________________
Course Instructor / Lab Engineer
# include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
cout<<"Enter a number: ";
cin>>number;
/* sqrt() is a library function to calculate square root */
squareRoot = sqrt(number);
cout<<"Square root of "<<number<<" = "<<squareRoot;
return 0;
}
User-defined Function
C++ allows programmer to define their own function. A user-defined function groups code to
perform a specific task and that group of code is given a name(identifier). When that function is
invoked from any part of program, it all executes the codes defined in the body of function.
Function Declaration
Function Definition
Function Calling
Consider the figure above. When a program begins running, the system calls
the main()function, that is, the system starts executing codes from main() function. When
control of program reaches to function_name() inside main(), the control of program moves
tovoid function_name(), all codes inside void function_name() is executed and control of
program moves to code right after function_name() inside main() as shown in figure above.
# include <iostream>
usingnamespacestd;
int main(){
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin>>num1>>num2;
sum= add(num1,num2);//Function call
cout<<"Sum = "<<sum;
return0;
}
Function prototype(declaration)
Function Call
To execute the codes of function body, the user-defined function needs to be invoked(called).
In the above program, add(num1,num2); inside main() function calls the user-defined function.
In the above program, user-defined function returns an integer which is stored in variable add.
Function Definition
The function itself is referred as function definition. Function definition in the above program:
int add;
add = a+b;
Return Statement