1.
Introduction
2.
Types of Functions
2.1.
Built-in Functions
2.2.
User-Defined Functions
2.3.
Void Functions
3.
Function Declaration
4.
Calling A Function
5.
Passing Parameters To Functions
5.1.
Pass by Value
5.2.
Pass by Reference
5.3.
Pass by Pointer
6.
The Main function
7.
8.
Key Takeaways
Last Updated: Mar 27, 2024

# Introduction to Functions

Basics of C++
Free guided path
9 chapters
99+ problems

## Introduction

A function is a set of all statements put together to perform a selected task. It could be statements doing some repeated duties or statements doing a little specialty task like printing etc.

One use of having functions is to simplify the code by breaking it into smaller functions. But another concept behind using functions is that it saves us from writing the same code repeatedly. We have to write one function and then call it as and when necessary without writing the same statement set again and again.

Also See,Fibonacci Series in C++

## Types of Functions

### Built-in Functions

These functions also are known as library functions. These are the functions that can be provided built-in C++, and we do not want to write them ourselves. We can directly use these functions to build our code.

These functions are placed in the header files of C++.

For Example, <cmath>, <string> are the headers that have in-built math functions and string functions respectively.

Example

``````#include <bits/stdc++.h>
using namespace std;
int main()
{
double num;
squareRoot;
cout << "Enter the number: ";
cin >> number;
squareRoot = sqrt(num);
cout << "The square root of " << number << " is: " << squareRoot;
return 0;
}``````

Output:

``````Enter the number: 36
The square root of 36 is: 6``````

### User-Defined Functions

C++ additionally allows its users to define their functions. Those are the user-described functions. We will describe the functions everywhere in the program and then name those functions from any part of the code. Just like variables, it must be declared before they are called.

Example

``````#include <bits/stdc++.h>
using namespace std;
void sayHello()
{
cout << "Hello";
}
int main()
{
sayHello();
return 0;
}``````

Output:

``Hello``

You can try by yourself with the help of online c++ compiler.

### Void Functions

We have seen that all general syntax of the function requires a return type to be defined. But if in case we've such a function that doesn't return any value, in that case, what will we specify as the return type? The answer is that we use the type "void" to indicate that the function does not return a value.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Function Declaration

A function declaration tells the compiler about the function's number of parameters, data types of parameters, and return type of function. Putting parameter names in the function declaration is optional in the function declaration, but it is necessary to put them in the definition.

Some examples of the function declaration are below for your reference.

1. int sum(int, int);

The above declaration is a function 'sum' that takes two integers as parameters and returns an integer value.

2 .void swap(int, int);

This means that the swap function takes two parameters of kind int and does not return any fee, and hence the return type is void.

3. void display();

The function display doesn't take any parameters and returns any type.

## Calling A Function

While growing a C++ function, you define what the function has to do. You may have to call or invoke that function to use a function.

While a program calls a function, program control is transferred to the called function. A called function performs the defined task, and while its return statement is executed or its function-ending closing brace is reached, it returns program control to the main program.

You simply need to pass the required parameters along with the function call to name a function. If a function returns a value, then you store the returned value.

## Passing Parameters To Functions

The parameters passed to function are called real parameters. For example, in the above programs, 10 and 20 are basic parameters.

The parameters received by the function are called the formal parameters.

There are three most popular ways to pass parameters.

### Pass by Value

Inside the program to swap integers that we discussed earlier, we have seen that we just read the integers' a' and 'b' in main and passed them to the swap function. That is the pass-by-value technique.

In the pass-by-value technique of parameters passing, the copies of values of real parameters are passed to the formal parameters. Due to this, the basic and formal parameters are saved at different memory locations. Thus, changes made to legal parameters inside the function do not reflect outside the function.

Example:

``````#include <bits/stdc++.h>
using namespace std;
void swap(int a, int b)
{
b = a + b;
a = b - a;
b = b - a;
cout<<"\nAfter swapping inside Swap:\n ";
cout<<"a = "<<a;
cout<<"\tb = "<<b;
return;
}
int main()
{
int a,b;
cout<<"Enter the two numbers for swapped: ";
cin>>a>>b;
cout<<"a = "<<a;
cout<<"\tb = "<<b;
swap(a,b);
cout<<"\nAfter swapping inside Main:\n ";
cout<<"a = "<<a;
cout<<â€ť\tb = "<<b;
}``````

Output:

``````Enter the two numbers for swapped: 2 3
a = 2 b = 3
After swapping inside Swap:
a = 3 b = 2
After swapping inside Main:
a = 2 b = 3``````

### Pass by Reference

Pass by reference is yet another method used by C++ to pass parameters to functions. Instead of passing copies of actual parameters on this technique, we pass regard to actual parameters.

In the pass-by-reference technique, we use these references of actual parameters. As a result, the function's change to formal parameters is reflected in the calling function.

Example

``````#include <bits/stdc++.h>
using namespace std;
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a,b;
cout<<"Enter the two numbers for swapped: "; cin>>a>>b;
cout<<"a = "<<a;
cout<<"\tb = "<<b;
swap(a,b);
cout<<"\nAfter swapping inside Main:\n ";
cout<<"a = "<<a;
cout<<"\tb = "<<b;
}``````

Output:

``````Enter the two numbers for swapped: 10 20
a = 10 b = 20
After swapping inside Main:
a = 20 b = 10``````

### Pass by Pointer

In C++, We can pass parameters to function using pointer variables. The pass-by pointer technique produces the same results as that of pass-by-reference. This means that each formal and real parameters share the exact memory locations, and the changes made in function are reflected inside the calling function.

The only difference is that we deal with references or aliases of parameters during a pass-by-reference. In contrast, we use pointer variables to pass the parameters in a bypass by pointer technique.

Pointer variables vary with the references in which pointer variables point to a particular variable, and unlike references, we will change the variable that it factors too.

Example:

``````#include <bits/stdc++.h>
using namespace std;
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a,b;
cout<<"Enter the two numbers for swapped: "; cin>>a>>b;
cout<<"a = "<<a;
cout<<"\tb = "<<b;
swap(a,b);
cout<<"\nAfter swapping inside Main:\n ";
cout<<"a = "<<a;
cout<<"\tb = "<<b;
}``````

Output:

``````Enter the two numbers for swapped: 15 25
a = 15 b = 25
After swapping inside Main:
a = 25 b = 15``````

Check out this problem - Redundant Braces

## The Main function

The main function serves as the starting point for program execution. It typically controls program execution by directing the calls to other functions in the program. A program normally stops executing at the end of the main, although it can terminate at other points inside the program for various reasons.

Types of the Main Function:
1. With parameters:

``````int main(int argc, char * const argv[])
{
...
return 0;
}``````

2. Without parameters:

``````int main()
{
...
return 0;
}``````

1. Write a program for printing the Fibonacci sequence using functions within the C++ programming language.

``````#include<bits/stdc++.h>
using namespace std;
void fib(int n)
{
int t1 = 0;
int t2 = 1;
int nextTerm;
for (int i = 1; i <= n; i++)
{
cout<<t1<<endl;
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return;
}
int main()
{
int n;
cin>>n;
fib(n);
return 0;
}``````

2. Write a program to find the factorial of a given number by using a function in the C++ programming language.

``````#include<bits/stdc++.h>
using namespace std;
int fact(int n){
int factorial = 1;
for (int i = 2; i <= n; i++)
{
factorial =factorial* i;
}
return factorial;
}
int main()
{
int n;
cin>>n;
int ans = fact(n);
cout<<ans<<endl;
return 0;
}``````

## Key Takeaways

We learned about the type of functions and use of all. We learned functions that help us in reducing code redundancy. Functions make code modular. Don't forget a large report having many lines of code. It will become, in reality, simple to examine and use the code if the code is divided into functions. For more exercise, you can visit Interview Experiences of top tech companies for practice.

Guided path
Free
Basics of C++
9 chapters
104+ Problems