Chapter - 4
Chapter - 4
Functions
Function
A function is a subprogram or a block of code designed to tackle a specific problem.
Using functions we can structure our programs in a more modular way
A program written with numerous functions is easier to maintain, update and
debug than one very long program.
By programming in a modular (functional) fashion, several programmers can work
independently on separate functions which can be assembled at a later date to create
the entire project.
Each function has its own name.
When that name is encountered in a program, the execution of the program branches
to the body of that function.
When the function is finished, execution returns to the area of the program code
from which it was called, and the program continues on to the next line of code.
Function Basics
C++ functions generally adhere to the following rules.
1. Every function must have a name.
2. Function names are made up and assigned by the programmer following the
same rules that apply to naming variables. They can contain up to 32 characters,
they must begin with a letter, and they can consist of letters, numbers, and the
underscore (_) character.
3. All function names have one set of parenthesis immediately following them.
This helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after parenthesis of the function
name, must be enclosed by braces.
Creating User-Defined Functions
Sometimes the calling function supplies some values to the called function.
These are known as parameters.
The variables which supply the values to a calling function called actual
parameters or Arguments – parameters passed to a function
The variable which receive the value from called statement are termed formal
parameters or Parameters – the parameters received by the function
Calling of A Function
the function can be called using either of the following methods:
i) call by value
ii)call by reference
Call By Value
In call by value method, the called function creates its own copies of original
values sent to it.
Any changes, that are made, occur on the function’s copy of values and are not
reflected back to the calling function.
Call By Reference
In call be reference method, the called function accesses and works with the
original values using their references.
Here we pass addresses not values
Any changes, that occur, take place on the original values are reflected back to the
calling code.
Example
Call By Value Call By Reference
Consider the following program which will swap the value of two variables;
output: 10 20
output: 20 10
Function With Default Arguments
C++ allows to call a function without specifying all its arguments.
In such cases, the function assigns a default value to a parameter which does not
have a matching arguments in the function call.
Default values are specified when the function is declared.
The complier knows from the prototype how many arguments a function uses for
calling.
Example:
float result(int marks1, int marks2, int marks3=75);
a subsequent function call
average = result(60,70);
passes the value 60 to marks1, 70 to marks2 and lets the function use default
value of 75 for marks3.
The function call
average = result(60,70,80);
passes the value 80 to marks3.
Inline Function
Functions save memory space because all the calls to the function cause the
same code to be executed.
The functions body need not be duplicated in memory.
When the complier sees a function call, it normally jumps to the function.
At the end of the function. it normally jumps back to the statement following
the call.
While the sequence of events may save memory space, it takes some extra
time.
To save execution time in short functions, inline function is used.
Each time there is a function call, the actual code from the function is inserted
instead of a jump to the function.
Inline Function
The inline function is used only for shorter code.
Example
inline int cube(int r) {
return r*r*r; }
Example: Example:
void function() { int globalVar = 20; // globalVar is a global variable
int localVar = 10; // localVar is a local variable void function() {
cout << localVar << endl;
cout << globalVar << endl;
}
}
Example
#include <iostream>
using namespace std;
int globalVar = 30; // globalVar is a global variable
void displayVariables() {
int localVar = 40; // localVar is a local variable
cout << "Global Variable inside function: " << globalVar << endl;
cout << "Local Variable inside function: " << localVar << endl;
}
int main() {
int localVar = 50; // localVar in main is a local variable
cout << "Global Variable in main: " << globalVar << endl;
cout << "Local Variable in main: " << localVar << endl;
displayVariables();
// The local variable from displayVariables() is not accessible here
// cout << "Local Variable inside main: " << localVar << endl; // Error
return 0;
}
Automatic versus static variables
The terms automatic and static describe what happens to local variables when a function
returns to the calling procedure. By default, all local variables are automatic, meaning
that they are erased when their function ends. You can designate a variable as automatic
by prefixing its definition with the term auto.
Eg. The two statements after main()’s opening brace declared automatic local variables:
main() {
int i;
auto float x;
…
}
The opposite of an automatic is a static variable. All global variables are static and, as
mentioned, all static variables retain their values. Therefore, if a local variable is static,
it too retains its value when its function ends - in case this function is called a second
time.
To declare a variable as static, place the static keyword in front of the variable when you
define it.
Static variables can be declared and initialized within the function, but the initialization
will be executed only once during the first call. If static variables are not declared
explicitly, they will be declared to 0 automatically.
Automatic versus static variables
Example
void my_fun() {
static int num;
static int count = 2;
count=count*5;
num=num+4;
}
In the above example:
During the first call of the function my_fun(), the static variable count will be
initialized to 2 and will be multiplied by 5 at line three to have the value 10. During
the second call of the same function count will have 10 and will be multiplied by 5.
During the first call of the function my_fun(), the static variable num will be
initialized to 0 (as it is not explicitly initialized) and 4 will be added to it at line four
to have the value 4. During the second call of the same function num will have 4 and
4 will be add to it again.
N.B. if local variables are static, their values remain in case the function is called again.
Library Function
C++ provides many built in functions that saves the programming time.
Some of the important mathematical functions in header file math are;
Function Meaning
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1 (x) where x (measured in radians)
acos(x) Cos-1 (x) where x (measured in radians)
exp(x) Exponential function of x (ex)
log(x) logarithm of x
log 10(x) Logarithm of number x to the base 10
sqrt(x) Square root of x
pow(x, y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x
Character Functions
All the character functions require ctype header file. The following table lists
the function.
Function Meaning
It returns True if C is an uppercase letter
isalpha(c) and False if c is lowercase.
It returns True if c is a digit (0 through 9)
isdigit(c) otherwise False.
It returns True if c is a digit from 0
through 9 or an alphabetic character
isalnum(c) (either uppercase or lowercase)
otherwise False.
5! = 5 * 4 * 3 * 2 * 1 = 120
and a recursive function to calculate this in C++ could be:
Examples on Function - 1
A simple function that takes two integers as parameters, adds them, and
returns the result.
#include <iostream>
using namespace std;
int add(int x, int y); // Function declaration
int main() {
int a = 5;
int b = 10;
int sum = add(a, b); // Function call
cout << "The sum of " << a << " and " << b << " is " << sum << endl;
return 0;
}
// Function definition
int add(int x, int y) {
return x + y;
}
Argument To A Function
Consider the following example that evaluates the area of a circle.
#include<iostream>
using namespace std;
void area(float);
int main() {
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r) {
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}
#include <iostream>
uaing namespace std;
void printMessage(); // Function declaration
int main() {
printMessage(); // Function call
return 0;
}
// Function definition
void printMessage() {
cout << "Hello, World!" <<endl;
}
Examples on Function - 3
A function with default parameters.
#include <iostream>
using namespace std;
// Function declaration with default parameters
void greet(string name = "Guest");
int main() {
greet(); // Calls greet with default argument
greet("Alice"); // Calls greet with "Alice" as argument
return 0;
}
// Function definition
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
Examples on Function - 4
A recursive function to calculate the factorial of a number.
#include <iostream>
using namespace std;
int factorial(int n); // Function declaration
int main() {
int number = 5;
cout << "Factorial of " << number << " is " << factorial(number) << endl;
return 0;
}
// Function definition
int factorial(int n) {
if (n <= 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
Examples on Function - 5
This example demonstrates function overloading, where multiple functions
have the same name but different parameters.
#include <iostream>
using namespace std;
void print(int i);
void print(double f);
void print(string s);
int main() {
print(10); // Calls print(int)
print(3.14); // Calls print(double)
print("Hello"); // Calls print(string)
return 0;
}
void print(int i) {
cout << "Printing int: " << i <<endl;
}
void print(double f) {
cout << "Printing double: " << f << endl;
}
void print(string s) {
cout << "Printing string: " << s << endl; }
Examples on Function - 6
A function that uses nested for loops to print a simple pattern. *
#include <iostream>
using namespace std; **
// Function declaration
void printPattern(int rows);
***
****
int main() {
int rows = 5; *****
printPattern(rows); // Function call
return 0;
}
// Function definition
void printPattern(int rows) {
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << endl;
}
}
Exercise
1. Write an int function cube () that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two formal parameters h and w, where h
is the height and w is the length of the bases of the triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle using its two float formal
parameters h and w, where h is the height and w is the width of the rectangle
4. The formula for a line is normally given as y = mx + b. Write a function Line() that expects three float parameters, a
slop m, a y-intercept b, and an x-coordinate x. the function computes the y-coordinate associated with the line specified
by m and b at x-coordinate.
5. Write a function Intersect() with four float parameters m1,b1,m2,b2. The parameters come conceptually in two pairs.
The first pair contains the coefficients describing one line; the second pair contains coefficients describing a second
line. The function returns 1 if the two lines intersect. Otherwise, it should return 0;
6. Write a program that accepts a positive integer from the user and displays the factorial of the given number. You
should use a recursive function called factorial() to calculate the factorial of the number.
7. Write another program that accepts a number from the user and returns the Fibonacci value of that number. You
should use recursion in here.
8. Develop a program that uses the function factorial() of exercise 6 to compute an approximation of e (Euler’s number).
Base your approximation on the following formula for e: 1 + 1/1! + 1/2! + 1/3! + …
9. Write a function called isPrime() that accepts a number and determine whether the number is prime or not.
10. Write a function called isEven() that uses the remainder operator(%) to determine whether an integer is even or not.
11. Modify our calculator problem of worksheet-3 using four functions sum(),product(),quotient() and difference().
Exercise
1. Write an int function cube () that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two formal parameters h and w, where h
is the height and w is the length of the bases of the triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle using its two float formal
parameters h and w, where h is the height and w is the width of the rectangle
4. The formula for a line is normally given as y = mx + b. Write a function Line() that expects three float parameters, a
slop m, a y-intercept b, and an x-coordinate x. the function computes the y-coordinate associated with the line specified
by m and b at x-coordinate.
5. Write a function Intersect() with four float parameters m1,b1,m2,b2. The parameters come conceptually in two pairs.
The first pair contains the coefficients describing one line; the second pair contains coefficients describing a second
line. The function returns 1 if the two lines intersect. Otherwise, it should return 0;
6. Write a program that accepts a positive integer from the user and displays the factorial of the given number. You
should use a recursive function called factorial() to calculate the factorial of the number.
7. Write another program that accepts a number from the user and returns the Fibonacci value of that number. You
should use recursion in here.
8. Develop a program that uses the function factorial() of exercise 6 to compute an approximation of e (Euler’s number).
Base your approximation on the following formula for e: 1 + 1/1! + 1/2! + 1/3! + …
9. Write a function called isPrime() that accepts a number and determine whether the number is prime or not.
10. Write a function called isEven() that uses the remainder operator(%) to determine whether an integer is even or not.
11. Modify our calculator problem of worksheet-3 using four functions sum(),product(),quotient() and difference().