0% found this document useful (0 votes)
19 views

Function Untill Overload

A function is a block of code that performs a task. There are two types of functions: library functions and user-defined functions. Functions are declared with a return type, name, and parameters. Functions can be called by value or by reference. Function overloading allows multiple functions to have the same name if they have different parameters. Function templates allow a single function to work with different data types. Inline functions may improve performance by copying the function code at the call site. Recursion is when a function calls itself.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Function Untill Overload

A function is a block of code that performs a task. There are two types of functions: library functions and user-defined functions. Functions are declared with a return type, name, and parameters. Functions can be called by value or by reference. Function overloading allows multiple functions to have the same name if they have different parameters. Function templates allow a single function to work with different data types. Inline functions may improve performance by copying the function code at the call site. Recursion is when a function calls itself.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

C++ Functions

 A function is a group of statements that together perform a task.


 A function declaration tells the compiler about a function's name, return type, and parameters.

Types of Functions
1. Library Functions: are the functions which are declared in the C++ header files such
as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.

Declaration of a function
The syntax of creating function in C++ language is given below:

return_type function_name(data_type parameter...)


{
//code to be executed
}

practical

Function Example
Let's see the simple example of C++ function.
#include <iostream>
using namespace std;
void func() {
int i=0;
int j=0;
i++,j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{ func();
func();
func();
}
Call by value and call by reference in C++
There are two ways to pass value or data to function

1. call by value
2. call by reference.

Call by Value

The call-by-value method allows you to copy the actual parameter to a formal
parameter. In this case, if we change the formal parameter then the actual parameter
doesn’t change. C++ uses call by value method by default.

practical

write a Program to implement Swapping using Call by function


#include <iostream>
using namespace std;
// Swap function to demonstrate
// call by value method
void swap(int x, int y)
{
int t = x;
x = y;
y = t;
cout << "After Swapping in function x: " << x
<< ", y: " << y << endl;
int main()
{
int x = 1, y = 2;
cout << "Before Swapping: ";
cout << "x: " << x << ", y: " << y << endl;
swap(x, y);
cout << "After Swapping: ";
cout << "x: " << x << ", y: " << y << endl;
return 0;
}

Call by refrence

What is a Pass by Reference?


When a variable is passed as a reference to a function, the address of the variable is
stored in a pointer variable inside the function.
practical
write a Program to implement Swapping using Call by function
passing by refrence

#include<iostream>
using namespace std;
void swap (int &num1, int &num2) //&num1 and &bnum2 are Reference
variables
{
int temp;
temp=num1;
num1=num2;
num2=temp;
}
int main()
{
int a=5,b=10;
cout<<"\n Before swapping"<<"\n A = "<<a<<"\n B = "<<b<<endl;
swap(a,b);
cout<<"\n After swapping"<<"\n A = "<<a<<"\n B = "<<b<<endl;
return 0;
}

Difference between call by value and call by reference


No. Call by value Call by reference
1 A copy of value is passed to the function An address of value is passed
to the function

2 Changes made inside the function is not reflected on Changes made inside the
other functions function is reflected outside
the function also
3 Actual and formal arguments will be created in Actual and formal arguments
different memory location will be created in same
memory location

Function Overloading
Two functions can have the same name if the number and/or type of arguments
passed is different.

 These functions having the same name but different arguments are
known as overloaded functions.

For example:

// same name different arguments

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Notice that the return types of all these 4 functions are not the same.

 Overloaded functions may or may not have different return types but they
must have different arguments.

For example

// Error code

int test(int a) { }

double test(int b){ }

both functions have the same name, the same type, and the same number of
arguments. Hence, the compiler will throw an error.

practical

Write Program to compute absolute value Works for both int and float
#include <iostream>

using namespace std;

// function with float type parameter

float absolute(float var){

if (var < 0.0)

var = -var;

return var;

// function with int type parameter

int absolute(int var) {

if (var < 0)

var = -var;

return var;

int main() {

// call function with int type parameter

cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter

cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;

return 0;}

Function Template
We can create a single function to work with different data types by using a
template.
 Defining a Function Template
starts with the keyword template followed by template parameter(s) inside <> which is followed by the
function definition.

template <typename T>

T functionName(T parameter1, T parameter2, ...) {

// code

T is a template argument that accepts different data types (int, float, etc.), and typename is a keyword.

When an argument of a data type is passed to functionName(), the compiler generates a new version
functionName() for the given data type.

 Calling a Function Template


we can call it in other functions or templates (such as the main() function)
with the following syntax
functionName<dataType>(parameter1, parameter2,...);

practical

Example: Adding Two Numbers Using Function Templates


#include <iostream>
using namespace std;

template <typename T>

T add(T num1, T num2)

{ return (num1 + num2);}

int main() {

int result1;

double result2;

// calling with int parameters

result1 = add<int>(2, 3);

cout << "2 + 3 = " << result1 << endl;

// calling with double parameters

result2 = add<double>(2.2, 3.3);

cout << "2.2 + 3.3 = " << result2 << endl;

return 0;

Inline Functions:
This copies the function to the location of the function call in compile-time and may make the
program execution faster.
we use the inline keyword. For syntax,

inline returnType functionName(parameters) {


// code
}
For example

#include <iostream>
using namespace std;

inline void displayNum(int num) {


cout << num << endl;
}
int main() {
// first function call
displayNum(5);

// second function call


displayNum(8);

// third function call


displayNum(666);
return 0; }

Here is how this program works:


Difference between Inline function and Normal function in C++

S.No Inline Function Normal Function


1 it is generally used to increase the execution time It is generally used to
of the program. improve the reusability of
code and make it more
maintainable.
2 It is basically a function that is used when functions It is basically a group of
are small and called very often. statements that performs a
particular task. It is used
when functions are big.
3 t requires ‘inline‘ keyword in its declaration. It does not require any
keyword in its declaration.
4 It generally executes much faster as compared to It generally executes slower
normal functions. than inline function for
small size function.
5 in this, the body of functions is copied to every In this, the body of the
context where it is used that in turn reduces the function is stored in the
time of searching the body in the storage device or storage device and when
hard disk. that particular function is
called every time, then CPU
has to load the body from
hard disk to RAM for
execution.

C++ Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

Working of Recursion in C++


Syntax The figure below shows

how recursion works by calling itself over and over again


void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

note
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and the other doesn't.

Advantages of C++ Recursion


Disadvantages of C++ Recursion

It makes our code shorter and cleaner. It takes a lot of stack space compared to an
Recursion reduce the length of code. iterative program.
It is very useful in solving the data It uses more processor time.
structure problem.
Reduce unnecessary calling of function. It can be more difficult to debug compared to
an equivalent iterative program.

Example 1: Factorial of a Number Using Recursion


// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}

C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
C++ <cmath> Header
Other functions, such as sqrt (square root), round (rounds a number) and log (natural
logarithm), can be found in the <cmath> header file:
example
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(64) << "\n";
cout << round(2.6) << "\n";
cout << log(2) << "\n";
return 0;
}

Other Math Functions


A list of other popular Math functions (from the <cmath> library) can be found in
the table below:
Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x
atan(x) Returns the arctangent of x
cbrt(x) Returns the cube root of x
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x
cosh(x) Returns the hyperbolic cosine of x
exp(x) Returns the value of Ex
expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y
floor(x) Returns the value of x rounded down to its nearest integer
hypot(x, y ) Returns sqrt(x2 +y2) without intermediate overflow or underflow
fma(x, y, z) Returns x*y+z without losing precision
fmax(x, y) Returns the highest value of a floating x and y
fmin(x, y) Returns the lowest value of a floating x and y
fmod(x, y) Returns the floating point remainder of x/y
pow(x, y) Returns the value of x to the power of y
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
tan(x) Returns the tangent of an angle
tanh(x) Returns the hyperbolic tangent of a double value

You might also like