Functions contains a block of code which runs when it is called in main function main(). Functions are of two types standard library functions which is predefined in C++ like sin(), cos() under the header file <cmath> and user defined functions which is made by users. A user defined function consists of function declaration which contains return type, function name, and parameters and definition which contains the code to be executed when function is called.
The following program shows a function which prints ‘Hello world’ when it is called.
#include <iostream>
using namespace std;
void func() {
cout<<"Hello world!";
}
int main() {
func();
return 0;
}
Output:
Hello world!
A function must be declared above the main() function. However its definition body may be below main() function. The following program shows a function declared above main() and its definition body is below main().
#include <iostream>
using namespace std;
void func();
int main() {
func();
return 0;
}
void func() {
cout<<"Hello world!";
}
Output:
Hello world!
A function can have parameters which is inside the parenthesis after the function name. Parameters are the values which are to be executed inside the function. Values are passed to the parameters as arguments when function is called. The following program shows function with parameters. Here ‘game’ and ‘NumofPlayers’ are parameters and “Football’, ’11’, ‘Basketball’ and ‘5’ are arguments.
#include <iostream>
using namespace std;
void func(string game, int NumOfPlayers) {
cout<<"Numnber of players for the game "<<game<<" is "<<NumOfPlayers<<endl;
}
int main() {
func( "Football", 11 );
func( "Basketball", 5);
return 0;
}
Output:
Numnber of players for the game Football is 11
Numnber of players for the game Basketball is 5