C++-Lesson 4 Functions
C++-Lesson 4 Functions
FUNCTIONS
a) Refer to pdf: Chap_04
b) C++ How to program chapter 6
\
return_type function_name( parameter list ) { body of the function }
}
Why Write Functions?
i. Reusability
ii. Fewer errors introduced when code isn’t rewritten
iii. Reduces complexity of code
iv. Programs are easier to maintain
v. Programs are easier to understand
vi. Less time when re coding
return_type function_name( parameter list ) { body of the function }
Function Definition
Function Definition
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0; } //make it Dynamic
return_type function_name( parameter list ) { body of the function }
Example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number, squareRoot;
cout << "Enter Number :: ";
cin >> number;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
return_type function_name( parameter list ) { body of the function }
Function overloading
With function overloading, multiple
functions can have the same name with
different parameters:
Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
return_type function_name( parameter list ) { body of the function }
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Function Overloading
• Function overloading
– Having functions with same name and different parameters
– Should perform similar tasks ( i.e., a function to square ints,
and function to square floats).
int square( int x) {return x * x;}
float square(float x) { return x * x; }
– Program chooses function by signature
• signature determined by function name and parameter types
– Can have the same return types