Skip to content

Functions

Use of functions

  1. Functions are set of code wich performs somethig for you
  2. Functions are used to modularised code
  3. Functions are used to increase readability
  4. Functions are used to use same code multiple times

Type of functions

  1. void → which does not return annything
  2. parameterised
  3. non parameterised
  4. return
  5. Pass by Value
  6. Pass by Refrence

Void - Non_Parameterised

Void_Function.cpp

#include<bits/stdc++.h>
using namespace std;

void printName() {
    cout << "Akash Singh";
}

int main() {
    printName();
    return 0;
}

Output: Akash Singh

Void - Parameterised

Parameterised_Function.cpp

#include<bits/stdc++.h>
using namespace std;

void printName(string name) {
    cout << "Hello " << name;
}

int main() {
    string name;
    cin >> name;
    printName(name);
    return 0;
}

Input: Akash
Output: Hello Akash

Return - Parameterised

Return_Function.cpp

#include<bits/stdc++.h>
using namespace std;

int Sum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

int main() {
    int num1, num2;
    cin >> num1 >> num2;
    cout << Sum(num1, num2);
    return 0;
}

Input: 5 6
Output: 11

Pass by Value

Pass_by_Value.cpp

#include<bits/stdc++.h>
using namespace std;

void AddFive(int num) {
    cout << "num" << endl;
    num += 5;
    cout << "num" << endl;
    num += 5;
    cout << "num" << endl;
}

int main() {
    int num;
    cin >> num;
    AddFive(num);
    cout << num;
    return 0;
}

Input: 10
Output: 15
20
10

Pass by Refrence

Pass_by_Refrence.cpp

#include<bits/stdc++.h>
using namespace std;

void AddFive(int &num) {
    cout << "num" << endl;
    num += 5;
    cout << "num" << endl;
    num += 5;
    cout << "num" << endl;
}

int main() {
    int num;
    cin >> num;
    AddFive(num);
    cout << num;
    return 0;
}

Input: 10
Output: 15
20
20