Methods or Functions

Method is a set of code which only runs when it is called. Methods are also known as Functions. Method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method. In C++, every executed instruction is performed in the context of a method. We can pass data, known as parameters, into a method(We going to study this in detail in upcoming articles).

So far we written all our codes inside { and } of int main(), where main is nothing but a Method. We can create our own method. A method is defined with the name of the method, followed by parentheses().

CODE

EG 1 . Creating a simple addition method and calling it in main method.

#include <iostream>
using namespace std;

//Method declaration
void Addition();

int main() {
    Addition(); // This is called as Calling a method or Invoking a Method
}

//Method definition
//We not yet studied what is void, we going to study it in upcoming articles.
void Addition() {
    int a = 5;
    int b = 6;
    int c = a + b;
    cout << c << endl;
}



EG 2 . Creating a multiplication table method and invoking inside main method.

#include <iostream>
using namespace std;

void MultiplicationTable();

int main() {
    MultiplicationTable();
}
void MultiplicationTable() {
    int tableNumber = 17;
    int limit = 20;
    for (int i=1; i <= limit; i++) {
        cout << tableNumber << " * " << i << " = " << tableNumber*i << endl;
    }
}




(Click Here, For more exercises)