Functions are made up of codes which are used to in a program to perform a pre-described command.
Functions need a prototype. It explains the compiler about the function. Prototype informs about what will be the return, what will be the name of function and what type of cases will be passes by the function. A function works like a variable which can return value.
Using namespace std;
int b = rand();
‘b’ will not get change suddenly. Function will get diversity for the first time of execution and after that function will remain same.
Structure of the prototype is given here:
return-type function_name ( arg_type arg1, …, arg_type argN );values
A function can pass single or multiple arguments. If a function does not give back a value then it can be shown with empty parenthesis or void.
Structure of the function is:
int mult ( int y, int z );
The prototype shows that function can get two integers. Always use semicolon at the end.
A function starts with a prototype and ends with semicolon. A chunk of code is always there which is to be performed. Declaration of arguments is used to be done in the blocks. At the end, it is necessary to close the braces.
using namespace std;
int mult ( int y, int z);
cout<<”give 2 numbers for multiplication: "; cin>> y >> z;
cout<<"Answer is "<< mult ( y, z ) <<"\n";
int mult ( int y, int z )
return y * z;
The following program has a file with a command. std namespace has all the things in it. Prototype of function comes after that. Always remember the semicolon. Be careful about key in and key out function. You can use cin for input.
Check how cout gives output. Cout gets value from mult.
cout<<“The answer is “<< y * z <<“\n”;
If the function is described in the main underneath and its prototype is given in the upper main, then it will be taken by the compiler because it is defined. So, you will not get error. But for the execution of code, it is must to define it.
For returning a value, return is used as keyword. It can happen that the function will have no value in return. In such a case, the statement will be authentic if there would be no expression.
There are many advantages of functions. If a programmer wants to run a code for fifty times, it will be difficult for him to write it for fifty times. If he has made some mistake then he has to modify it for fifty times. If a programmer has defined a function then he has no need to define the code again and again. It will also become easy to make any change in the function.
Functions split a multifaceted program into sections. If we have to make a set of choices with a lot of selections then it will be helpful to make functions. Each and every selection will have its own function. It will make the program simple and easy to understand.