Close
Close

Function in C++


Imagine, you are making a game. And you need to display the score frequently. One solution is to write the whole code to display the score, again and again, whenever wanted. But there is another better solution using functions. Define that whole code in a function and call it whenever you want. Simple!

A function is nothing but a group of codes written together and given a name. And these can be called anytime in the main function without typing the whole code ( as we know the main function is executed first ).

Why Functions?


Functions make our code neat and readable and prevent us from writing the same code again and again.

Types of Functions in C++

There are two types of functions in C++.

  • Library Functions
  • User-defined Functions

Library Functions


Library functions are pre-defined functions in C++.

User Defined Functions


We can also define our own functions in C++.

Let's first see how to declare a function of our own.

How to Declare a Function?


We declare a function as follows

return_type function_name ( parameters ) ;

As an example, suppose we have to calculate the average of 2 numbers, num1 and num2. The numbers are of type integer and average is of type float. Then we will pass the numbers to a function that will return the average value of those numbers. We will declare that function as follows:

float average( int num1, int num2 );

Here, the function named 'average' is taking num1 and num2 of integer type as input and then returning the average value of type float after calculating it.

Defining Function


Syntax for defining a function is

return_type function_name ( parameters )
{
    //code
}

Let's see the average function that we defined above.

float average( int num1, int num2 )
{
    float avg; /* declaring local variable */
    avg = ( num1 + num2 )/2.0;
    return avg; /* returning the average value */
}

As seen before, variables declared inside function are called local variables. A local variable can only be used in the function in which it is declared. It has no use outside the function. For example, in our case, avg is a local variable.

While defining functions, it is necessary to specify the parameter type along with the parameters.

Therefore, we wrote 'int' along with num1 and num2.

return avg; - This means that this function will give us or return us avg which is of type float. You will understand this more clearly from examples.

Calling Function


To use a function, we need to call it. Once we call a function, it performs its operations and after that, the control again passes to the main program.

To call a function, we need to specify the function name along with its parameters.

function_name ( parameters ) ;

So we will call our average function as shown below

average( num1, num2 );

Now, let's combine all to take out the average of 2 numbers using a function.

#include <iostream>

float average( int num1, int num2 ); /* declaring function named average */

int main(){
	using namespace std;
	int num1, num2;
  	float c;
  	cout << "Enter first number" << endl;
  	cin >> num1;
  	cout << "Enter second number" << endl;
  	cin >> num2;
  	c = average( num1, num2 ); /* calling the function average and storing its value in c*/
  	cout << "Average is " << c << endl;
	return 0;
}

float average( int num1, int num2 ) /* function */
{
    	float avg; /* declaring local variable */
    	avg = ( num1 + num2 )/2.0;
   	return avg; /* returning the average value */
}
Output
Enter first number
5
Enter second number
4
Average is 4.5

float average( int num1, int num2 ); - We have declared that we have defined a function named 'average' in our program so that, 'main' function can search for it while calling that function 'main'.

Here, a function named average with 2 integer parameters (num1 and num2) and return type float is declared. This means while calling the function, we need to give two integers as input and in return, it will give us a float as output.

By writing c = average( num1, num2 );, we are calling the function 'average' with 2 parameters ( num1 and num2 ). Now, 'average' is called and it calculated and returned the average value of num1 and num2. As it is returning a float, and here it is 4.5, so, this expression will be equivalent to c = 4.50, since 4.50 is returned by the function and its value gets stored in a variable 'c'.

We can also define a function at the time of declaration as in the example below.

#include <iostream>

float average( int num1, int num2 ) /* function */
{
  	float avg; /* declaring local variable */
  	avg = ( num1 + num2 )/2.0;
  	return avg; /* returning the average value */
}

int main(){
	using namespace std;
	int num1, num2;
  	float c;
  	cout << "Enter first number" << endl;
  	cin >> num1;
  	cout << "Enter second number" << endl;
  	cin >> num2;
  	c = average( num1, num2 ); /* calling the function average and storing its value in c*/
  	cout << "Average is " << c << endl;
	return 0;
}
Output
Enter first number
5
Enter second number
4
Average is 4.5

We have defined our 'average' function before 'main'. So, in this case, while executing main, the compiler will know that there is a function named 'average'.

If a function doesn't return anything, then its return type is written as void as in the example below.

#include <iostream>

using namespace std;

void display( int n ) /* function */
{
    	cout << "Number is " << n << endl;
}

int main(){
	int n;
  	cout << "Enter number" << endl;
  	cin >> n;
  	display(n); /* calling the function display*/
	return 0;
}
Output
Enter a number
5
Number is 5

'void' means that function will not return anything.

One thing to note in the above example is that we wrote using namespace std; outside our main function. This is because if we write this statement inside the main function, then it will be defined only in the main function, not in the display function.
So, either we have to write using namespace std; in both the functions (main() function and display function) separately or we can write it in the starting outside both the functions as we did in the above example.

If multiple functions use the objects defined in the std namespace, then we can write the 'using namespace std' statement in the beginning, outside all the functions.

It is also possible to define a function without any arguments. Let's see its example.

#include <iostream>

using namespace std;

void display( )
{
    	cout << "Function with no argument" << endl;
}

int main(){
	display();
	return 0;
}
Output
Function with no argument

As we saw, there is no argument given to the function display().

Calling a function inside another


Yes, we can call a function inside another function. We have already done this. We were calling our functions inside the main function. Now look at an example in which there are two user defined functions. And we will call one inside another.

#include <iostream>

using namespace std;

int div_2(int a){
  if(a%2==0){
  	return 1;
  }
  else{
    return 0;
  }
}

void div_6(int b){
  if( div_2(b)==1 && b%3 == 0 ){
    cout << "Yes, the number is divisible by 6." << endl;
  }
  else{
    cout << "No, the number is not divisible by 6." << endl;
  }
}

int main(){
  div_6(12);
  div_6(25);
  return 0;
}
Output
Yes, the number is divisible by 6.
No, the number is not divisible by 6.

A number is divisible by 6, if it is divisible by both 2 and 3. We have a function div_2 which will return 1 if the given number is divisible by 2. Another function that we have defined is div_6 which calls div_2 inside itself.
if( div_2(b)==1 && b%3 == 0 ) - In our case, b and thus a are 12 in the first case and 25 is the next case. So, if div_2 returns 1, the number is divisible by 2. And if b%3==0 is true, 'b' is divisible by 3. So if the number is divisible by both 2 and 3, then it is divisible by 6 also.

Recursion


Recursion is the calling of a function within the same function.

Let's consider an example in which we have to calculate the factorial of a number.

The factorial of a number n is the product of all the natural numbers till n. For example, the factorial of 5 is 1*2*3*4*5 = 120, the factorial of 2 is 1*2 = 2. The factorial of both 0 and 1 is 1.

#include <iostream>

using namespace std;

int factorial( int a ) /* function */
{
  if( a == 0 || a == 1)
  {
    return 1;
  }
  else
  {
    return a*factorial(a-1);
  }
}

int main(){
  int n;

  cout << "Enter number" << endl;
  cin >> n;

  int fact  = factorial(n);

  cout << "Factorial of " << n << " is " << fact << endl;

  return 0;
}
Output
Enter number
4
Factorial of 4 is 24

Since we passed n to the function factorial, therefore the value of a is that of 'n'. Thus, if the value of the integer 'a' is 0 or 1, return 1; will return 1. Otherwise if the integer 'a' is greater than 1, then a*factorial(a-1); multiplies a with the factorial of 'a-1'.
For example, if the number is 4, then 'a*factorial(a-1)' implies '4*factorial(3)'. So by writing 'a*factorial(a-1)', we are again calling the function 'factorial' inside itself but this time the argument is 'a-1' i.e. factorial(a-1).

So if we give 0 to the function factorial, it will return us 1.
If we give 1, it will again return 1.

Now, give 2.
This time the statement in the body of 'else' will be executed and it has to return 'a*factorial(a-1)' i.e. 2*factorial(1). So, it will again call 'factorial' ( as factorial(1) ) which is 1. Finally, it will return 2*1 i.e. 2.

Now, try this with 3. This time, it will return 3*factorial(2). Again it will call factorial(2) which will return 2*factorial(1). So the expression will be return 3*2*factorial(1) which is 3*2*1 ( since factorial(1) will return 1 ).

For 4, the expression will be 4*factorial(3).
Calling factorial(3) will return 4*3*factorial(2) ( since factorial(3) will return 3*factorial(2) ).
Again calling factorial(2) will return 4*3*2*factorial(1).
Thus, at last, 4*3*2*1 or 24 will be returned.

Hopefully, you have understood this. Most of the programmers find this difficult in their beginning days. So, congrats!

To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

Winning doesn't come cheaply. You have to pay a big price.
-Jeev Milkha Singh

Ask Yours
Post Yours
Doubt? Ask question