Functions
• A function is a block of code which runs only when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain action(s).
• Functions are useful when a block of code is to be used again
and again.
• main() is one of the pre-defined function.
1
Functions: Basics
Take the instance of
f(x) = 2x + 5
1, 2, 3 are arguments (or
Then, f(1) = 7, parameters) sent to the function
f(2) = 9, and
f(3) = 11 7, 9, 11 are returned values
Some pre-defined mathematical functions in C++
pow (x,y);
sqrt (x);
floor (x); ceil (x);
2
Functions: Pre-defined functions
floor(x): Returns the largest integer smaller than or equal to x
Examples of ceil:
Input : 2.5 Output : 2
Input : -2.1 Output : -3
Input : 2.9 Output : 2
ceil(x): Returns the smallest integer greater than or equal to x
Examples of ceil:
Input : 2.5 Output : 3
Input : -2.1 Output : -2
Input : 2.9 Output : 3
3
Functions: Syntax
void MyFunction()
{
//Function body
}
• “MyFunction” is the name of the function
• “void” signifies the function shall not return any value
• “Function body” defines the content/operation of the function
• “()” signifies that no data was passed to the function
4
Functions: Declaration and Calling
• Functions are declared before main()
• Declaration is done by defining the ‘type’ and the ‘name’ of the function
followed by a pair of parenthesis ()
• Function declaration explains how to call it
void fun() {
cout << “This is a trial function\n”;
}
What happens if you
int main () { declare fun() after main()?
fun(); //Calling the function
fun(); //Calling multiple times
fun(); //Calling multiple times
return 0;
}
5
Functions: Declaration and Calling
• Functions must be declared before main(), but can be defined after main()
• Helps in better organization of the code
• Functions are called inside the main function
• Calling is done by following the syntax of function declaration
Compilation sequence Run sequence
// Function declaration
1 void fun(); 2
// main function
2 int main() {
fun(); // calling function
1
return 0;
}
// Function definition
3 void fun() {
cout << “My first function.\n”;
3
}
6
Functions: Declaration and Calling
Function name
• Cannot be reserved keywords
• Same rules applicable as naming variables
• Multiple functions can have same name*
void fun(int x, int y)
Return type Function parameters
• Tells what value is to be returned • Tells how and what values are ‘passed’
• Same as data type of return value • It is optional to have parameters
• It is optional to return a value (void) • Call by ‘value’ or call by ‘reference’
7
Functions: Declaration and Calling
•Functions are declared before main(), but can be defined after main()
•Helps in better organization of the code
•Function declaration explains how to call it
// Function declaration // Function declaration
void fun(); void fun();
void fun(int x);
void fun(int x, int y);
// main function void fun(int x, float y, string s);
int main() {
fun(); // calling function
return 0; // Function declaration
} int fun();
int fun(int x, int y);
// Function definition
void fun() { bool fun(int x, int y)
cout << “My first function.\n”;
}
8
Functions: Parameters and Arguments
• Functions communicate with one another through parameters
• Parameter details (how many and what type) are given during function declaration
• Variables can be passed as parameters
#include <iostream>
using namespace std;
void myfunc(string fname, string place){
cout << fname << " is from " << place << endl;
}
int main(){
string s;
cin >> s; //Taking input
myfunc(s, "Roorkee"); //Calling myfunc(). Passing one variable and one value
return 0;
}
9
Functions: Parameters and Arguments
• Parameter mismatch (type or number) will result in
compilation error
#include <iostream>
using namespace std;
void myfunc(string fname, string place){
cout << fname << " is from " << place << endl;
}
int main(){
myfunc("Anjaneya"); //Invalid due to Parameter mismatch
myfunc("Anjaneya", "USA"); //Valid
return 0;
}
10
Functions: Parameters and Arguments
• Functions communicate with one another through parameters
• Parameter details (numbers and types) are given during function declaration
void myFun(parameter1, parameter2, parameter3) {
// code to be executed
}
#include <iostream>
using namespace std;
void myfunc(string fname, string place="Not provided"){
cout << fname << " is from " << place << endl;
}
int main(){ • Look carefully for the difference in these two.
myfunc("Anjaneya"); • Which do you think will operate?
myfunc("Anjaneya", "Roorkee"); • If both work, then is this mismatching?
return 0;
}
11
Functions: Returning a value
• For a two-way communication, functions can return
values to talk back
#include <iostream>
using namespace std;
//Function declaration and receiving the argument sent from main()
int FACT(int x) //Function type set to return value type
{
int fact=1;
for (int i=1; i<=x; i++)
fact*=i; //Calculating the factorial
return fact; //Returning the factorial
}
int main(){
int x; cin>>x; //Taking input
int y = FACT(x); //Calling function and passing the argument
cout << y; //Displaying the output
return 0;
}
12
Example code
#include <iostream>
#include <cmath>
using namespace std;
int myfunc(float x); int myfunc2(float x); //Declaring two functions
int main() {
float x;
cin >> x;
// cout << ceil(x) << endl << floor(x) << endl;
cout << "y= " << myfunc(x);
return 0;
}
int myfunc(float x){
//cout <<"Trial function\n";
//cout << ceil(x)+1 << endl << floor(x)+1 << endl;
int y = myfunc2(x); return y;
}
int myfunc2(float x){
int y = ceil(x)+1; return y;
}
13
Functions: Overloading
• Overloading is declaring multiple functions with same name
• Made distinct by changing the number and/or type of the arguments
• Compiler identifies relevant function by checking the argument number and type
• Only changing the return type will not allow function overloading
int FACT(int x) //Type-1
int FACT(int x, int y) //Type-2
int FACT(int x, float z) //Type-3
Conditions:
• Different types of parameters (e.g., int vs double)
• Different number of parameters (e.g., two in one function, three in another)
• Different sequence of parameters (e.g., int and double vs double and int)
void FACT (int x) vs int FACT(int x)
//Is this function overloading?
14
Functions: Overloading
#include <iostream>
using namespace std;
int FACT(int x){ //Type-1
//Function body
}
int FACT(int x, int y){ //Type-2
//Function body
}
int FACT(int x, float z){ //Type-3
//Function body
}
int main(){
int p,q; float r; cin>>p>>q>>r;
int a = FACT(p); //Calling function Type-1
int b = FACT(p,q); //Calling function Type-2
int c = FACT(p,r); //Calling function Type-3
cout << a << b << c;
return 0;
}
15
Function: Overloading
int sumInteger(int x, int y) {
return x + y;
}
double sumDouble(double x, double y) {
return x + y;
}
Overload the function
int main() {
int myNum1 = sumInteger(3, 4);
double myNum2 = sumDouble(2.1, 2.9);
return 0;
}
© Indian Institute of Technology Roorkee 16
Function: Overloading
int sum(int x, int y) {
return x + y;
}
double sum(double x, double y) {
return x + y;
}
int main() {
int myNum1 = sum(3, 4);
double myNum2 = sum(2.1, 2.9);
return 0;
}
© Indian Institute of Technology Roorkee 17
Functions: Overloading
• Overloading functions can perform automatic type Conversion
double mpg(double miles, double gallons)
//Returns miles per gallon
{
return (miles/gallons); double mpg will automatically
} convert any argument of type int
to a value of type double
int main ()
{ OUTPUT: 22.5 miles per gallon
cout << mpg(45, 2) << " miles per gallon";
return 0;
}
18
Functions: Overloading
• Overloading functions can perform automatic type Conversion
double mpg(double miles, double gallons)
//Returns miles per gallon
{
return (miles/gallons);
}
int mpg(int goals, int misses)
//Returns the Measure of Perfect Goals
{ OUTPUT:
return (goals-misses); 43 miles per gallon
} 43 perfect goals
int main ()
{ You should not use the
cout << mpg(45, 2) << " miles per gallon\n"; same function name for
cout << mpg(45, 2) << " perfect goals"; two unrelated functions
return 0;
}
19
Functions: Overloading
double the_answer(double data1, double data2); x = the_answer(5.0, 6.0);
double the_answer(float time, float count); (x is double type)
double the_answer(double data1, double data2); x = the_answer(y, 6.0);
double the_answer(double time, int count); (x, y are double type)
double the_answer(double data1, double data2); x = the_answer(5, 6);
double the_answer(double time, int count); (x is double type)
double the_answer(double data1, double data2); x = the_answer(5, 6.0);
double the_answer(double time, int count); (x is double type)
20