Functions:

  • A function is a block of code which we separate from the main function.
  • Functions are used to perform specific tasks.
  • When we need to do that task, we call it in main function because we know that in our C++ code, execution starts from main function and ends when main function ends.
  • If we do not call function in main function, it will never be executed.

Why Functions?

As we can achieve the same functionality without using functions but it is necessary to use functions because;
  • They make out code more readable.
  • Reduce redundancy of your code.
  • Easy to find errors.

Real Life Example:

If we make a calculator in our main function and we need calculator at 10 places. We will have to write code for it 10 times. If we declare a function and write code for calculator there. And then if we need calculator at 10 places, then we just need to call calculator function, which will be a single line of code.


Steps to write a function:

  • Declare the function. Declaration of function is also called prototype of the function.
    datatype func_name(params);
  • Define the function. Function definition is the body of the function which defines its behavior.
    void print(){
        cout<<"Hi there!";
    }

Now, we will declare a function which will print "Hi, there!" on screen. Then we will call it in main function.

function.cpp
#include<iostream>
using namespace std;

void print(){
    cout<<"Hi there!";
}
int main(){
    print();//calling a function
    //you can also call function again
    print();
    return 0;
}
  

Description:

  • void print() is the declaration of the function.Return type of function is same as the value it is returning. As our function is returning nothing therefore its type is void.
  • The code written inside the curly braces is the body of the function.

Note:
We have to declare the function before the main function and we can define/write code in body of the function anywhere outside the main function.
Rules for naming functions are the same as rules for naming the variables and we can not name our user defined function "main" as we can have only one main function in our code.


Parameters / Arguments:

When there is a variable in the main function and we need it in the other function then we pass it to other function when we call it(inside parentheses). We can pass multiple arguments to the function.

Parameters: variables in parenthesis when declaring the function
Arguments: variables in parenthesis when calling the function


function.cpp
#include<iostream>
using namespace std;

void print(string g1){      
    cout<<g1;
}

int main(){
    string greetings = "Hi there!";
    print(greetings);      
    return 0;
}

Functions which return some value:

When functions are returning some value then we can assign it to a variable.

function.cpp
#include<iostream>
using namespace std;

int sum(int a, int b){
    int sum = a + b;
    return sum;
}
int main(){
    int add = sum(2, 3);
    cout<<add<<endl;
    //following line will print the same result
    cout<<sum(2,3)<<endl;
    return 0;
}

Passing values to functions:

We have studied that how can we pass data value to a function. This is called pass by value method.
We are actually passing the address of our variable, where our data is stored.


Pass by reference:

When you pass a parameter by reference, you are essentially passing a reference to the original data. If you change the data value of the variable in the function, it will be reflected in the main function either.

function.cpp
#include<iostream>
using namespace std;

int sum(int &a, int &b){
    int sum = a+b;
    return sum;
}
int main(){
    int add = sum(2,3);
    cout<<add<<endl;
}

Pass by Pointer:

When you pass a parameter by pointer, you are passing a pointer to the original data. This allows you to access and modify the original data indirectly through the pointer.

function.cpp
#include<iostream>
using namespace std;

int sum(int *a, int *b){
    int sum = *a+*b;
    return sum;
}
int main(){
    int num1=2, num2=3;
    int add = sum( &num1, &num2 );
    cout<<add<<endl;
    return 0;
}


Functions and arrays:

Functions can accept arrays as arguments, allowing you to perform operations on the array's elements.

function.cpp
#include<iostream>
using namespace std;

void printMarks(int marks[5]){
    for(int i=0; i<5; i++){
    cout<<marks[i];
    }
    cout<<endl;
}
int main(){
    int marks[5] = {10,20,30,40,50};
    printMarks(marks); 
    return 0;
}

Recursion:

Recursive functions are the functions that call themselves directly or indirectly to solve a problem.


recursion.cpp
#include <iostream>
using namespace std;

// Recursive function to calculate factorial
int factorial(int n) {
    // Base case: if n is 0 or 1, factorial is 1
    if (n == 0 || n == 1) {
      return 1;
    } else {
      // Recursive case: n! = n * (n-1)!
      return n * factorial(n - 1);
    }
}

int main() {
    int num;
    cout << "Enter a positive integer: ";
    cin >> num;

    if (num < 0) {
        cout << "Number is negative" << endl;
    } else {
        int result = factorial(num);
        cout << "Factorial: " << result << endl;
    }

    return 0;
}

Function Overloading:

Function overloading allows you to define different functions with the same name but,

  • Overloading functions must have parameters with different data types, OR
  • Number of parameters must be different, OR
  • If number of parameters is same, their sequence must be different.
  • Return type of overloading functions may or may not be different (not necessary).
Funtions with atleast one feature given above or having all the three features are said to be overloaded.
When function is called, compiler determines which version of function to invoke.



overloading.cpp
#include <iostream>
using namespace std;

int sum(int a, int b){
    return a+b;
}
float sum(float a, float b, int c){
    return a+b;
}
int main(){
  //funtion with data type int is invoked
  sum(5, 10);  
    
  //funtion with data type float is invoked
  sum(5.0, 10.0, 20);  
  //sum has all three features of overloading
}