Programming CPP Chapter Four 4
Programming CPP Chapter Four 4
Modular programming
Breakingdown the design of a program into individual components (modules) that
can be programmed and tested independently.
Usingfunctions, a program is divided into smaller parts, making it easier to understand,
control, test, and maintain.
A program divided into several smaller parts which can interact or work together
Modules
Can be written and tested separately
Testing is easier (smaller)
Doesn't need to be retested
Reduces length of program
Hides details (data abstraction)
Functions in C++ 3
Functions
help us in reducing code redundancy. If functionality is
performed at multiple places in software, then rather than writing the
same code, again and again, we create a function and call it
everywhere.
Functions make code modular. Consider a big file having many lines of
code. It becomes really simple to read and use the code if the code is
divided into functions.
Functions
provide abstraction. For example, we can use library functions
without worrying about their internal work.
User Defined Functions 5
As the name suggests these functions are defined and created by users / programmers.
A function is a set of statements that take inputs, do some specific computation, and
produce output.
Functions in C++ agree with the notion of functions in mathematics.
For example, they allow functional composition such as f(f(p),q,f(f)). However, C++ functions either return
one value or no value.
1. Declaration
2. Definition
3. Calling
Declaration of Functions 6
The return_type specifies the type of value that the function returns.
The function_name is the name of the function.
The parameter_list is a list of variables that are passed to the function.
The body of the function is a block of code that is executed when the function is called.
The body of the function can contain any valid C++ code.
Declaration of Functions - Prototypes 8
Value
The return statement is used to terminate immediately the execution of a
function.
All functions have a return type – default is int
If the function doesn’t have a return type void will be used
void is a reserved word
The function prototype usually placed at the beginning of the program
The definition of the prototype must be given
Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using #include
Declaration of Functions 10
Function Parameters
A function may take a list of parameters, separated by commas. Each parameter is
preceded by its type.
Note that we can omit the names of the parameters, the type is enough. For example,
we could write:
double show(char, int, float);
Function Parameters 11
However, it is better to use names, so that someone who just reads the
prototype or intends to use the function gets an idea about the
information being passed to it, in what order and the purpose of each
parameter.
void show(int x, int y); instead of void show(int, int);
Thetype of each parameter must be specified, even if several
parameters have the same type. For example, it is illegal to write:
void test(int a, b, c); instead of void test(int a, int b, int c);
Parameters 12
Function parameters are placeholders for values passed to the function. They act as
variables inside a function.
Here, x is a parameter that holds a value of 10 when it’s called.
Example 13
Defining a Function 14
E.g.
long Area(long l, long w)
{
return l * w;
}
The return statement without any value is typically used to exit the function early
C++ does not allow nested functions
The definition of one function cannot be included in the body of another function
A function definition must agree in return type and parameter list with its prototype
Defining a Function 17
} // end main
1 4 9 16 25 36 49 64 81 100
Example 19
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<endl;
Function
Each function has its own name
When that name is encountered, called function call, the execution of
the program branches to the body of that function – the called function
When the function returns, execution resumes on the next line of the
calling function
Functions can also call other functions and can even call themselves –
recursive functions
A function can be called as many times as needed.
When a function is called, the execution of the program continues with the execution of the
function’s code.
In particular, the compiler allocates memory to store the function’s parameters and the
variables that are declared within its body.
Exercises 21
Write two functions that take an integer parameter and return the square and the cube
of this number, respectively.
The restriction is that the body of the second function consists of a single statement and calls the first.
Write a program that reads an integer and uses the functions to display the sum of the
number’s square and cube.
Scope of identifier 22
The scope of a variable in C++ is the part of the program where the variable can be
accessed.
The scope of a variable is the part of the program in which the variable is accessible, or
else, it is visible from the other parts of the program.
Refers to where in the program an identifier is accessible
Determines how long it is available to your program and where it can be accessed
Two kind
Local identifier - identifiers declared within a function (or block)
Global identifier – identifiers declared outside of every function definition
Scope of identifier 23
// Function variable
void foo() { The variable function_var can only be
int function_var = 20; accessed from within the function foo().
}
// Block variable
The variable block_var can only be
{ accessed from within the block of code
int block_var = 30; where it is declared.
}
Examples 24
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
// Global variable declaration:
int main () {
int g;
// Local variable declaration:
int main () {
int a, b;
// Local variable declaration:
int c;
int a, b;
// actual initialization
// actual initialization
a = 10;
a = 10;
b = 20;
b = 20;
c = a + b;
g = a + b;
cout << c;
cout << g;
return 0;
return 0;
}
}
The same name for global and 25
local variables
A program can have same name for local and global variables but value of local variable
inside a function will take preference.
#include <iostream>
using namespace std;
// Global variable declaration: When the above code is compiled and executed, it
int g = 20; produces the following result −
int main () { 10
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Local scope 26
::
One can access an global variable even if it is over-shadowed by a local
variable of the same name.
Using :: operator
#include <iostream.h>
float num=10.8;
int main(){
float num= 9.66;
cout<<“the value of num is:”<<::num<<endl;
return 0;
}
Static and Automatic Variables 33
(continued)
Static variable - memory remains allocated as long as the program
executes
The syntax for declaring a static variable is:
static dataType identifier;
static int x; // Declares x to be a static variable of the type int
Static variables declared within a block are local to the block
Their scope is the same as any other local identifier of that block
A static variable in C++ is a variable that is declared using the keyword static. The space
for the static variable is allocated only once and this is used for the entirety of the
program. Once this variable is declared, it exists till the program executes. So, the
lifetime of a static variable is the lifetime of the program.
#include <iostream> float getavg(float newdata)
34
{
float getavg(float);
static float total = 0;
int main() static int count = 0;
{ count++;
total += newdata;
float data=1, avg; return total / count;
while( data != 0 ) }
{
cout << “Enter a number: “;
Variables declared outside of any block are static
cin >> data; variables
avg = getavg(data); By default, variables declared within a block are
cout << “New average is “ << avg << endl; automatic variables
} Declare a static variable within a block by using the
return 0; reserved word static
}
Functions Parameters 35
The parameters that are defined in the function definition are called Formal Parameters.
The parameters in the function call which are the actual values are called Actual
Parameters.
We also know that actual parameters pass values to a function which is received by the
format parameters.
If those arguments are included the default value is overwritten. Function parameters
are read from left to right, so default parameters should be placed from right to left.
Functions with Default Parameters 38
it's generally a good practice to avoid using too many default parameters,
as functions with too many optional parameters can become difficult to use
and maintain.
Parameter Passing 40
In C++, there are two ways to pass arguments to a function: pass by value and pass by
reference.
1. Pass by value means that a copy of the argument is passed to the function. Any changes made to the
argument inside the function will not affect the original argument.
2. Pass by reference means that a reference to the argument is passed to the function. Any changes made
to the argument inside the function will affect the original argument.
Call by Value
Value of the function argument passed to the formal parameter of the function
Copy of data passed to function
Changes to copy do not change original
Call by Reference
Address of the function argument passed to the formal parameter of the function
Pass/Call by Value 41
#include <stdio.h>
void swapnum(int &i, int &j) {
When the function swapnum() is called, the values of
int temp = i; the variables a and b are exchanged because they
i = j; are passed by reference.
j = temp; The output is:
}
int main(void) { A is 20 and B is 10
int a = 10;
int b = 20;
swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
Inline Function 46
Inline functions in C++ are a feature that allows the function call to be replaced by the
actual function code at the point of function call.
This can provide a performance benefit by reducing the overhead associated with
function calls.
o declare an inline function in C++, the inline keyword is used before the function
declaration
inline int square(int x) {
return x * x;
}
Recursive function in C++ 47
A recursive function is a function that calls itself directly or indirectly. This technique
provides a way to break complicated problems down into simple problems which are
easier to solve.
Recursion may be a bit difficult to understand.
The best way to figure out how it works is to experiment with it.
int factorial(int n) {
This function calculates the factorial of a number.
if (n == 0) { The base case is when n is 0. In this case, the function
return 1; returns 1.
abs(): The abs() function returns the absolute value of a number. For example, abs(-5) returns 5.
acos(): The acos() function returns the arc cosine of a number. For example, acos(0.5) returns
1.0471975512.
asin(): The asin() function returns the arc sine of a number. For example, asin(0.5) returns
0.5235987756.
atan(): The atan() function returns the arc tangent of a number. For example, atan(1) returns
0.7853981634.
atan2(): The atan2() function returns the arc tangent of two numbers. For example, atan2(1, 1)
returns 0.7853981634.
ceil(): The ceil() function returns the smallest integer value greater than or equal to a number. For
example, ceil(3.1) returns 4.
cos(): The cos() function returns the cosine of a number. For example, cos(0) returns 1.
Built in Functions (Math Library) 49
exp(): The exp() function returns the exponential of a number. For example, exp(1)
returns 2.7182818284.
fabs(): The fabs() function returns the absolute value of a floating-point number. For
example, fabs(-5.0) returns 5.0.
floor(): The floor() function returns the largest integer value less than or equal to a
number. For example, floor(3.1) returns 3.
log(): The log() function returns the logarithm of a number. For example, log(100) returns
2.
log10(): The log10() function returns the logarithm of a number to the base 10. For
example, log10(100) returns 2.
Built in Functions (Math Library) 50
pow(): The pow() function returns the power of a number to a given exponent. For
example, pow(2, 3) returns 8.
sin(): The sin() function returns the sine of a number. For example, sin(0) returns 0.
sqrt(): The sqrt() function returns the square root of a number. For example, sqrt(16)
returns 4.
tan(): The tan() function returns the tangent of a number. For example, tan(0) returns 0.
Summary 51
In real programs, we most often don’t want to look at a function body. Why would we
doing so:-
Makes it possible to use the function in more than one place in our program
Eases testing
Example Summary 52
#include <iostream>
In this example, we're defining a function
// function declaration
called add that takes two integer
int add(int a, int b); arguments and returns their sum.
REPORT OUTLINE
1. INTRODUCTION: PROVIDE AN OVERVIEW OF BUILT-IN FUNCTIONS IN C++.
2. TYPES OF BUILT-IN FUNCTIONS: DESCRIBE THE DIFFERENT TYPES OF BUILT-IN FUNCTIONS
IN C++.
3. EXAMPLES OF BUILT-IN FUNCTIONS: PROVIDE EXAMPLES OF HOW TO USE BUILT-IN
FUNCTIONS IN C++.
4. CONCLUSION: SUMMARIZE THE KEY POINTS OF THE REPORT.
54
}
End of Chapter 4
COMPUTER OF PROGRAMMING