Dremendo Tag Line

Function in C++ Programming

Function in C++

In this lesson, we will understand what is Function in C++ Programming and how to create them along with some examples.

What is Function in C++

A Function in C++ is a block of statements that is defined to perform a specific task. A function is also called a reusable code because once it is created, it can be used again and again.

To clearly understand a function let's take a real life example of a function.

In the early days, we used to wash our clothes manually by using our hands, and we used to repeat this task daily. But nowadays, we wash our clothes using a washing machine that does the same task that we used to do in our early days by hands. Here, the washing machine is a perfect example of a function, we can use it, again and again, to wash our clothes whenever required.

video-poster

Function Categories

In C++, there are two categories of functions available, and they are:

  • Built-in Functions : These functions are predefined, and we can use them any time we want in our C++ program. For example pow(), sqrt(), min(), etc.
  • User Defined Functions : These functions are defined or created by the programmer for performing a specific task in a program.

Note: In this lesson, we will learn how to create and use a user-defined function in C++.

Types of User Defined Function

The user-defined function can be of two types and they are:

  • Void Function
  • Return Type Function

Void Function

This type of function does not return any value or result to the caller program (program that calls the function). To create void function we have to used the keyword void as per the syntax given below.

Syntax of Creating a Void Function

void function_name(parameters)
{
    statement 1;
    statement 2;
    ...
}

Example 1 (without parameters)

void message()
{
    cout<<"Hello I am learning how to create void function in C++";
}

Example 2 (with parameters)

void sum(int a, int b)
{
    int c;
    c=a+b;
    cout<<"Sum of "<< a <<" and "<< b <<" is "<<c;
}

Note: Parameters are also called Arguments. Function can be created with or without parameters depending on the requirements.

Calling a Void Function

To call a void function, we have to call it by its name. See the complete example given below.

Example

#include <iostream>
#include <conio.h>

using namespace std;

void message()
{
    cout<<"Hello I am learning how to create void function in C++.\n";
}

void sum(int a, int b)
{
    int c;
    c=a+b;
    cout<<"Sum of "<< a <<" and "<< b <<" is "<<c;
}

int main()
{
    message();
    sum(10,20);
    return 0;
}

Output

Hello I am learning how to create void function in C++.
Sum of 10 and 20 is 30

In the above program, we have declared two void functions message() and sum() before the main() function. The message() function does not accept any argument but displays a text on the screen whenever we call it. On the other hand, the sum() function accept two arguments and display their sum on the screen.

We have called both the functions from within the main() function. So, main() function is known as caller function and message() and sum() are known as called function because they are called by the main() function to process the task.

Return Type Function

This type of function returns the value or result to the caller program (the program that calls the function). The function return type can be int, float, double, char or any other type depends on the requirement.

Syntax of Creating a Return Type Function

return_type function_name(parameters)
{
    statement 1;
    statement 2;
    ...
    return result:
}

Example 1 (without parameters)

float pi()
{
    return 3.142;
}

Example 2 (with parameters)

int sum(int a, int b)
{
    int c;
    c=a+b;
    return c;
}

In the above example, the sum() function returns the value of c whose data type is int. So the return type of sum() function is int. The return type of a function depends upon the return type of the final result. If the final result is float type then the return type of the function must be float.

Calling a Return Type Function

We can call a return type function just like we call a void function. See the complete example given below.

Example

#include <iostream>
#include <conio.h>

using namespace std;

float pi()
{
    return 3.142;
}

int sum(int a, int b)
{
    int c;
    c=a+b;
    return c;
}

int main()
{
    int x=10, y=20, z;
    cout<<"The value of PI is 22/7 = "<<pi()<<endl;
    z=sum(x,y);
    cout<<"Sum of "<< x <<" and "<< y <<" is "<<z;
    return 0;
}

Output

The value of PI is 22/7 = 3.142
Sum of 10 and 20 is 30

In the above program, we have declared two return type functions pi() and sum() before the main() function. The pi() function does not accept any argument but returns the value 3.142 to the caller program (main function).

The sum() function accept two arguments, we pass the values of x and y to the sum() function. The variable a and b of the sum() function received the values from x and y and returns their sum to the caller program (main function) after calculation.

Flow of Execution of Function

The Flow of Execution of Function refers to the order in which statements are executed in the main program when any function is called. Let's see the execution of the above program using a diagram.

function workflow in c++

In the above diagram, we see that when the main program calls the function pi(), the program flow goes to the body of the function pi() and execute its codes. After that, it returns the value to the main program and then calls the second function sum() by sending it two arguments (x,y), the program flow goes to the body of the function sum(), and execute its code and then returns the value to the main program. At last, the main programs end.

Passing Different Types of Arguments in Function

We can pass different types of arguments in a function like an integer, float, array, structure, etc. Let's see some examples.

Example 1 (passing integers and float)

#include <iostream>
#include <conio.h>

using namespace std;

void simpleinterest(int p,float r,int t)
{
    float si;
    si=(p*r*t)/100;
    cout<<"Simple Interest = "<<si;
}

int main()
{
    int principal,time;
    float rate;

    cout<<"Enter principal amount: ";
    cin>>principal;
    cout<<"Enter yearly rate %: ";
    cin>>rate;
    cout<<"Enter time in year: ";
    cin>>time;
    simpleinterest(principal,rate,time);
    return 0;
}

Output

Enter principal amount: 5000
Enter yearly rate : 6.25
Enter time in year: 1
Simple Interest = 312.5

Example 2 (passing one dimensional integer array)

#include <iostream>
#include <conio.h>

using namespace std;

void sum(int arr[])
{
    int s=0,i;
    for(i=0; i<5; i++)
    {
        s=s+arr[i];
    }
    cout<<"Sum of Numbers = "<<s;
}

int main()
{
    int n[5],i;

    cout<<"Enter 5 numbers\n";
    for(i=0; i<5; i++)
    {
        cin>>n[i];
    }
    sum(n);
    return 0;
}

Output

Enter 5 numbers
5
8
2
4
6
Sum of Numbers = 25

In the above program, the variable int arr[] represents a one dimensional integer array argument in the function sum(). We can use any other variable name in place of arr.

Example 3 (passing two dimensional integer array)

#include <iostream>
#include <conio.h>

using namespace std;

void sum(int num[][3])
{
    int s=0,i,j;
    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            s=s+num[i][j];
        }
    }
    cout<<"Sum of Numbers = "<<s;
}

int main()
{
    int n[3][3],i,j;

    cout<<"Enter 9 numbers\n";
    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            cin>>n[i][j];
        }
    }
    sum(n);
    return 0;
}

Output

Enter 9 numbers
12
6
8
9
14
18
21
11
5
Sum of Numbers = 104

In the above program, the variable int num[][3] represents a two dimensional integer array argument in the function sum() and 3 inside the second square brackets represents the total number of columns in each row of the array.

Example 4 (passing structure)

#include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;

typedef struct record
{
    char name[20];
    int age;
} rec;

void input(rec *x)
{
    cout<<"Enter Name: ";
    gets(x->name);
    cout<<"Enter Age: ";
    cin>>x->age;
}

void display(rec *x)
{
    cout<<"Name: "<<x->name<<endl;
    cout<<"Age: "<<x->age;
}

int main()
{
    rec a;
    input(&a);
    display(&a);
    return 0;
}

Output

Enter Name: Martin
Enter Age: 15
Name: Martin
Age: 15

In the above program, we are passing the memory address of the structure variable a to the structure pointer x in input() and display() functions. Inside the input() and display() functions, we are accessing the member variables of structure a using structure pointer x and the arrow operator ->.

Formal and Actual Arguments

The arguments or parameters used during function declaration within the round brackets ( ) are known as Formal Arguments. Whereas the arguments or parameters that are used when providing input to the function from the main program are known as Actual Arguments. Let's see an example for more understanding.

Example

#include <iostream>
#include <conio.h>

using namespace std;

float simpleinterest(int p,float r,int t)
{
    float si;
    si=(p*r*t)/100;
    return si;
}

int main()
{
    int principal,time;
    float rate,interest;

    cout<<"Enter principal amount: ";
    cin>>principal;
    cout<<"Enter yearly rate %: ";
    cin>>rate;
    cout<<"Enter time in year: ";
    cin>>time;
    interest=simpleinterest(principal,rate,time);
    cout<<"Simple Interest = "<<interest;
    return 0;
}

In the above program, variable p, r and t in function simpleinterest() are used to receive inputs from the main program, so these variables are known as Formal Argument.

The variables principal, rate and time used in the main program to provide inputs to the function simpleinterest() are known as Actual Arguments because they provide the actual inputs to the function simpleinterest().

Pass by Value or Call by Value

In Pass by Value the values of the variables are passed to the formal arguments of the function. In this case the values of the actual arguments are not affected by changing the values of the formal arguments. See the example given below.

Example of Pass by Value

#include <iostream>
#include <conio.h>

using namespace std;

void changevalue(int a,int b)
{
    a=a+2;
    b=b+2;
    cout<<"In function changes are "<< a <<" and "<< b <<endl;
}

int main()
{
    int x=10,y=20;
    cout<<"Before calling the function\n";
    cout<<"x="<< x <<" and y="<< y <<endl;
    changevalue(x,y);
    cout<<"After calling the function\n";
    cout<<"x="<< x <<" and y="<< y <<endl;
    return 0;
}

Output

Before calling the function
x=10 and y=20
In function changes are 12 and 22
After calling the function
x=10 and y=20

In the above program, the variable x and y are passed as arguments to the function changevalue(). The value of x and y is passed to a and b. The memory location of x and y are different from the memory location of a and b. Hence, when the value of a and b is incremented, there will be no effect on the value of x and y. So after calling the function the value of x and y are the same as before calling the function.

Pass by Reference or Call by Reference

In Pass by Reference the address of the variables are passed to the formal arguments of the function. In this case the values of the actual arguments are affected by changing the values of formal parameter. See the example given below.

Example of Pass by Reference

#include <iostream>
#include <conio.h>

using namespace std;

void changevalue(int *a,int *b)
{
    *a=*a+2;
    *b=*b+2;
    cout<<"In function changes are "<< *a <<" and "<< *b <<endl;
}

int main()
{
    int x=10,y=20;
    cout<<"Before calling the function\n";
    cout<<"x="<< x <<" and y="<< y <<endl;
    changevalue(&x,&y);
    cout<<"After calling the function\n";
    cout<<"x="<< x <<" and y="<< y <<endl;
    return 0;
}

Output

Before calling the function
x=10 and y=20
In function changes are 12 and 22
After calling the function
x=12 and y=22

In the above program, the memory address of variable x and y are passed as arguments to the function changevalue(). The address of x and y is passed to a and b. As a and b are pointer and holds the memory location of x and y. Hence, when the value of a and b is incremented, it will affect the value of x and y. So after calling the function the value of x and y will change.

Test Your Knowledge

Attempt the practical questions to check if the lesson is adequately clear to you.

Test Your Knowledge