C++ - FUNCTION
C++ - FUNCTION
✔ Function:
✔ Introduction:
Element of function:
1.Function definition
2.Function call
3.Function declaration
Definition of function:
Name and Type – function type specifies the type of value (like float or double).
If the return type is not explicitly specified, C will assume that it is an integer
type. The function name in any valid C identifier and therefore must follow the
same rules of formation as other variable names in C. The name should be
approximate to the task performed by the function.
The parameter list declares the variable that will receive the data sent by the
calling program. They serve as input data to the function to carry out specified
task.
These parameters can also be used to send values to the calling programs.
The parameters are also known as arguments.
The parameters list contains declaration of variables separated by commas
and surrounded by parentheses.
Examples:
float quadratic (int a, int b, int c) {….}
Double power (double x, int n) {….}
float mul (float x, float y) {….}
int sum (int a, int b) {….}
Void printline(void)
{
…………….
}
▪ This function neither receives any input values nor returns back any value,many
compliers accept are empty set of parentheses, without specifying anything as in
Void printline()
Function Body
▪ The function body contains the declarations and statement necessary for
performing the required task.
▪ The body enclosed in braces, contains 3 parts, in the order given below:
1. Local declarations that specify the variables needed by the function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
A function may or may not send back any value to the calling function. If it
does, it is done through the return statement.
The return statement can take one of the following forms:
the ‘plain’ return does not return not value; it acts much as the closing brace
of the function.
Prototype
1. return type – when a function is declared to perform some sort of calculation or
any operation and is expected to provide with some result at the end.
NOTE: in case your function doesn’t return any value, the return type would be
void.
2. Function name – function name is an identifier and it specifies the name of the
function.
3. Parameter list – the parameter list declares the type and number of arguments
that the function expects when it is called.
4. Function body – the function body contains the declaration and the
statement(algorithm) necessary for performing the required task.
The body is enclosed within curly braces {….} and consists of 3 parts.
1. Local variable declaration(if required).
2. Function statement to perform the task inside the function.
3. A return statement to return the result evaluated by the function(if return
type is void, then no return statement is required).
Function calls
When a function is called, control of the program gets transferred to the function.
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
It is possible to have a function with parameters but no return type. It is not
necessary, that if a function accepts parameter(s), it must return a result too.
While declaration the function, we have declared 2 parameters a and b of
type int. therefore, while calling that function, we need to pass 2 arguments,
else we will get complication error.
And the two arguments passed should be received in the function definition,
which means that the function header in the function definition should have
the 2 parameters to hold the argument values.
These received arguments are also known as formal parameters. The name
of the variables while declaring, calling and defining a function can be
different.
PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
int multiply(int a, int b); //function declaration
int main()
{
int i, j, result;
cout<<” Enter 2 numbers you want to multiply: “;
cin>>i>>j;
result = multiply(i, j); //function call
cout<<”The result of multiplication is: ”<<result;
getch();
return 0;
}
int multiply(int a, int b)
{
return(a*b); //function definition, this can be done in one line
}
Output: Enter 2 numbers you want to multiply: 5 6
The result of multiplication is: 30
Pass by value
PROGRAM
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
In main(), two integer a and b are defined. And those integers are passed to a
function swap() by value.
Void swap(int x, int y);
Pass by pointer
PROGRAM
#include <iostream>
using namespace std;
#include<conio.h>
// function declaration
void swap(int *x, int *y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
return;
}
OUTPUT
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
In pass by reference method the actual value of the argument is not passed.
Pass by reference
PROGRAM
#include <iostream>
using namespace std;
#include<conio.h>
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
OUTPUT
#include<stdio.h>
Using namespace std;
#include<conio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // function call
return 0;
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}
OUTPUT:
Enter 2 number that you want to compare:25 45
The greater number is:45
2. Function with no arguments and a return value
We have modified the above example to make the function greatNum() return
the number which is greater amongst the 2 input numbers.
#include<stdio.h>
Using namespace std;
#include<conio.h>
int greatNum(); // function declaration
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum() // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}
▪ This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.
#include<stdio.h>
Using namespace std;
#include<conio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}
Inline functions
When a program executes the function call instructions, the CPU stores the
memory address of the instruction following the function call, copies the
arguments of the function on the stack and finally transfers control to the
specified function.
In lining is only a request to the complier, not a command.
● Advantage:
● Disadvantage:
1. The added variables from the inline function consume additional registers.
2. If too many inline functions are used then the size of the binary
executable file will be larger, because of the duplication of same code.
3. Too much inlining can also reduce our instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that
of primary memory.
PROGRAM:
#include<stdio.h>
Using namespace std;
#include<conio.h>
inline int cube(int s)
{
Return s*s*s;
}
int main()
{
Cout<<”the cube of 3 is: “<<cube(3)<<”\n”;
Getch();
Return 0;
}
OUTPUT:
The cube of 3 is: 27
Largest (a, n)
▪ The function largest is defined to take 2 arguments, the array name and the
size of the array to specify the number of elements in the array.
▪ The declaration of the formal argument array is made as follows:
Float array[];
▪ The pair of brackets informs the complier that the arguments array is an array
of numbers. It is not necessary to specify the size of the array here.
PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
//function declaration
int largest (int a[], int n);
int main()
{
int arrValues[5] = {3,-4,65,24,48};
int results = largest(arrValues, 5);
cout<<”Largest is “<<result;
getch();
return 0;
}
int largest(int a[], int n)
{
int i,max;
max = a[0];
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
return(max);
}
OUTPUT:
Largest is 65
The approach is similar to the one we did with one-dimensional arrays. The
rules are simple.
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
▪ The function given below calculates the sum of the values in a two-
dimensional matrix.
PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
//function declaration
double sum(int x[2][2], int r,int c);
int main()
{
int arrValues[2][2]={
{1, 2},
{3, 4}
};
int result = sum(arrValues, 2,2);
cout<<”sum is”<<result;
getch();
return 0;
}
double sum(int x[2][2], int r,int c)
{
int i,j;
double sum = 0.0;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sum += x[i][j];
return sum;
}
OUTPUT:
Sum is 10