0% found this document useful (0 votes)
8 views

ch4 5

Uploaded by

isramemon0786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

ch4 5

Uploaded by

isramemon0786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

1

Programming
Fundamentals
DR. RAHEEL AHMED MEMON
2

Functions
3
What is a function?

u Function is a self-contained block of


statements that perform a coherent task of
some kind.
u In C++ program an object have data
collection of functions.
u main( ) is also a function
4
Types of Functions

u Library functions
u These are the in-built functions of ‘C++ ’ library.
u These are already defined in header files.
u Example: sizeof() is a function which is used to
know the size of any datatype. It is defined in
‘climit’ file .

u User defined functions


u Programmer can create their own function in
C++ to perform specific task
5
Why use
functions?
u Writing functions avoids rewriting
of the same code again and
again in the program.
u Using function large programs can
be reduced to smaller ones. It is
easy to debug and find out the
errors in it.
u Using a function, it becomes
easier to write program to keep
track of what they are doing
6
Writing a Program

u Top Down Design


u Develop the algorithm that the program will
use
u Translate the algorithm into the programming
language
u Top Down Design
(also called stepwise refinement)
u Break the algorithm into subtasks
u Break each subtask into smaller subtasks
u Eventually the smaller subtasks are trivial to
implement in the programming language
Use Pseudocode 7

u Pseudocode is a mixture of English and


the programming language in use
u Pseudocode simplifies algorithm design
by allowing you to ignore the specific
syntax of the programming language as
you work out the details of the algorithm
u If the step is obvious, use C++
u If the step is difficult to express in C++, use
English
8
9

Pseudocode
and
Flowchart
10
Benefits of Top-Down
Design
u Subtasks, or functions in C++, make programs
u Easier to understand
u Easier to change
u Easier to write
u Easier to test
u Easier to debug
u Easier for teams to develop
11
Program Testing
u Programs that compile and run can still
produce errors
u Testing increases confidence that the program
works correctly
u Run the program with data that has known output
u You may have determined this output with pencil
and paper or a calculator
u Run the program on several different sets of data
u Your first set of data may produce correct results in
spite of a logical error in the code
u Remember the integer division problem? If
there is no fractional remainder, integer
division will give apparently correct results
12

Predefined
Functions
13
Predefined Functions

u C++ comes with libraries of predefined


functions

u Example: sqrt function


u theRoot = sqrt(9.0);
u returns, or computes, the square root
of a number
u The number, 9, is called the argument
u theRoot will contain 3.0
14
15
Function Call Syntax

u Function_name (Argument_List)
u Argument_List is a comma separated list:

(Argument_1, Argument_2, … , Argument_Last)

u Example:
u side = sqrt(area);
u cout << “2.5 to the power 3.0 is “ << pow(2.5,
3.0);
Function Libraries 16

u Predefined functions are found in libraries


u The library must be “included” in a program
to make the functions available
u An include directive tells the compiler which
library header file to include.
u To include the math library containing sqrt():

#include <cmath>
u Newer standard libraries, such as cmath, also require
the directive
using namespace std;
Other Predefined Functions 17

u abs(x) --- int value = abs(-8);


u Returns absolute value of argument x
u Return value is of type int
u Argument is of type x
u Found in the library cstdlib
u fabs(x) --- double value = fabs(-8.0);
u Returns the absolute value of argument x
u Return value is of type double
u Argument is of type double
u Found in the library cmath
18
#include <iostream>
#include <cmath>

using namespace std;

int main() {
double num;

cout << "Enter a number: ";


cin >> num;

// Using abs() for integer from <cstdlib>


int absoluteValueInt = abs(static_cast<int>(num));
cout << "Absolute value " << num << " is: " << absoluteValueInt << endl;

// Using fabs() for double from <cmath>


double absoluteValueDouble = fabs(num);
cout << "Absolute value " << num << " is: " << absoluteValueDouble << endl;

return 0;
}
Random Number 19
Generation

u Really pseudo-random numbers


u 1. Seed the random number generator
only once
#include <cstdlib>
#include <ctime>

srand(time(0));

u 2. The rand() function returns a random


integer that is greater than or equal to 0
and less than RAND_MAX
rand();
20
Random Numbers

u Use % and + to scale to the number range


you want
u For example to get a random number from 1-
6 to simulate rolling a six-sided die:

int die = (rand() % 6) + 1;

u Can you simulate rolling two dice?


u Generating a random number x where 10 < x
< 21?
21
Practice with library
functions
u toupper() // functions from <cctype>
u tolower() // functions from <cctype>
u strlen() // function from <cstring>
u pow() // function from <cmath>
u cos() // function from <cmath>
u log() // function from <cmath>
u time() // function from <ctime> try to display current time
22

Practice
with
library
functions

There are many like that, explore


more on your own…
23

Programmer-
Defined Functions
Programmer-Defined Functions 24

u Two components of a function definition


u Function declaration (or function prototype)
u Shows how the function is called
u Must appear in the code before the function can be called
u Syntax:
Type_returned Function_Name(Parameter_List);
//Comment describing what function does
;
u Function definition
u Describes how the function does its task
u Can appear before or after the function is called
u Syntax:
Type_returned Function_Name(Parameter_List)
{
//code to make the function work
}
Function 25

Declaration
u Tells the return type
u Tells the name of the function
u Tells how many arguments are needed
u Tells the types of the arguments
u Tells the formal parameter names
u Formal parameters are like placeholders for the
actual
arguments used when the function is called
u Formal parameter names can be any valid identifier
u Example:

double totalCost(int numberPar, double


pricePar);
// Compute total cost including 5% sales tax on
// numberPar items at cost of pricePar each
Function Definition 26

u Provides the same information as the declaration


u Describes how the function does its task

function header
u Example:

double totalCost(int numberPar, double pricePar)


{
const double TAX_RATE = 0.05; //5% tax
double subtotal;
subtotal = pricePar * numberPar;
return (subtotal + subtotal * TAX_RATE);
}
function body
27
The Return Statement

u Ends the function call


u Returns the value calculated by the function
u Syntax:
return expression;
u expression performs the calculation
or
u expression is a variable containing the
calculated value
u Example:
return subtotal + subtotal * TAX_RATE;
28
The Function
Call
u Tells the name of the function to use
u Lists the arguments
u Is used in a statement where the
returned value
makes sense
u Example:

double bill = totalCost(number, price);


Placing Definitions 29

u A function call must be preceded by either


u The function’s declaration
or
u The function’s definition
u If the function’s definition precedes the call, a
declaration is not needed
u Placing the function declaration prior to the
main function and the function definition
after the main function leads naturally to
building your own libraries in the future.
bool Return Values 30

u A function can return a bool value


u Such a function can be used where a boolean
expression is expected
u Makes programs easier to read
u if (((rate >=10) && ( rate < 20)) || (rate == 0))
is easier to read as
if (appropriate (rate))
u If function appropriate returns a bool value based
on the the expression above
31
Function appropriate

u To use function appropriate in the if-statement


if (appropriate (rate))
{ … }

appropriate could be defined as

bool appropriate(int rate)


{
return (((rate >=10) && ( rate < 20)) || (rate == 0));
}
In total a Programmer Defined 32

Function:

u 4 Stages
u *Function Declaration // int myfunc(int a);
u Function Definition // int myfunc(int a){ a=a+5; return a; }
u Function call // myfunc(5);
u Function Return Value // 10
33

Procedural
Abstraction
Procedural 34

Abstraction
u The Black Box Analogy
u A black box refers to something that we know
how
to use, but the method of operation is unknown
u A person using a program does not need to know
how it is coded
u A person using a program needs to know what
the
program does, not how it does it
u Functions and the Black Box Analogy
u A programmer who uses a function needs to
know
what the function does, not how it does it

u A programmer needs to know what will be


produced if the proper arguments are put into
the box
35
Information Hiding

u Designing functions as black boxes is an


example of information hiding
u The function can be used without knowing how
it is coded
u The function body can be “hidden from view”
Function 36
Implementations
and The Black Box

u Designing with the black box in mind


allows us
u To change or improve a function
definition without
forcing programmers using the function to
change
what they have done
u To know how to use a function simply by
reading the
function declaration and its comment
Procedural 37
Abstraction and
C++

u Procedural Abstraction is writing and using


functions as if they were black boxes
u Procedure is a general term meaning a
“function like”
set of instructions
u Abstraction implies that when you use a
function as
a black box, you abstract away the details of
the
code in the function body
Procedural Abstraction and 38

Functions
u Write functions so the declaration and comment
is all a programmer needs to use the function
u Function comment should tell all conditions
required of arguments to the function
u Function comment should describe the returned
value
u Variables used in the function, other than the
formal parameters, should be declared in the
function body
39
Formal Parameter
Names
u Functions are designed as self-contained
modules
u Different programmers may write each function
u Programmers choose meaningful names for
formal parameters
u Formal parameter names may or may not
match
variable names used in the main part of the
program
u It does not matter if formal parameter names
match other variable names in the program
u Remember that only the value of the
argument is
plugged into the formal parameter
40

Go through the
book for
Case study of:

Buying PIZZA
41

Local Variables
Local Variables 42

u Variables declared in a function:


u Are local to that function, they cannot be used
from outside the function
u Have the function as their scope
u Variables declared in the main part of a
program:
u Are local to the main part of the program, they
cannot be used from outside the main part
u Have the main part as their scope
43
Global Constants 44

u Global Named Constant


u Available to more than one function as well as the
main part of the program
u Declared outside any function body
u Declared outside the main function body
u Declared before any function that uses it
u Example: const double PI = 3.14159;
double volume(double);
int main()
{…}
u PI is available to the main function
and to function volume
45
Global Variables 46

u Global Variable -- rarely used when more


than one function must use a common
variable
u Declared just like a global constant except const is not used
u Generally make programs more difficult to
understand and maintain
Formal Parameters 47

are Local Variables


u Formal Parameters are actually variables that are
local to the function definition
u They are used just as if they were declared in the
function body
u Do NOT re-declare the formal parameters in the
function body, they are declared in the function
declaration
u The call-by-value mechanism
u When a function is called the formal parameters
are initialized to the values of the
arguments in the function call
48
Block Scope 49

u Local and global variables conform to the rules of Block Scope


u The code block (generally defined by the { }) where an identifier like a
variable is declared determines the scope of the identifier
u Blocks can be nested
50

The start of a file is not always the best


Namespaces
u
place
for
Revisited using namespace std;

u Different functions may use different


namespaces
u Placing using namespace std; inside the
starting
brace of a function
u Allows the use of different namespaces in
different
functions
u Makes the “using” directive local to
the function
51
52

Function
Overloading
Overloading 53

Function Names
u C++ allows more than one
definition for the
same function name
u Very convenient for situations in
which the “same”
function is needed for different
numbers or types
of arguments
u Overloading a function name
means providing
more than one declaration and
definition using
the same function name
Function Overloading in C++ 54

double ave(double n1, double n2)


{
return ((n1 + n2) / 2);
}
//-------------------------------------------------------//
double ave(double n1, double n2, double n3)
{
return (( n1 + n2 + n3) / 3);
}
//-------------------------------------------------------//
Compiler checks the number and types of arguments
in the function call to decide which function to use
cout << ave( 10, 20, 30);
uses the second definition
55
Overloading Details

u Overloaded functions
u Must have different numbers of formal
parameters
AND / OR
u Must have at least one different type of
parameter

u Must return a value of the same type


Automatic Type Conversion 56

u Given the definition


double mpg(double miles, double gallons)
{
return (miles / gallons);
}
what will happen if mpg is called in this way?

cout << mpg(45, 2) << “ miles per gallon”;


u The values of the arguments will automatically be
converted to type double (45.0 and 2.0)
57

Functions Add-ons..
void Functions
void-Functions

u In top-down design, a subtask might produce


u No value (just input or output for example)
u One value
u More than one value
u We have seen how to implement functions that
return one value
u A void-function implements a subtask that
returns no value or more than one value
void-Function Definition
u Two main differences between void-function
definitions and the definitions of functions
that return one value
u Keyword void replaces the type of the value returned
u void means that no value is returned by the function
u The return statement does not include and expression
Example:

void showResults(double f_degrees, double c_degrees)


{
using namespace std;
cout << f_degrees
<< “ degrees Fahrenheit is euivalent to “ << endl
<< c_degrees << “ degrees Celsius.” << endl;
return;
}
Using a void-Function

u void-function calls are executable statements


u They do not need to be part of another statement
u They end with a semi-colon
u Example:
showResults(32.5, 0.3);

NOT: cout << showResults(32.5, 0.3);


void-Functions Why
Use a Return?
u Is a return-statement ever needed in a
void-function since no value is returned?
u Yes!
u What if a branch of an if-else statement
requires
that the function ends to avoid producing
more
output, or creating a mathematical error?
u void-function here avoids division by zero
with a return statement
The Main Function

u The main function in a program is used like a


void function…do you have to end the program
with a return-statement?
u Because the main function is defined to return a
value of type int, the return is needed
u C++ standard says the return 0 can be omitted, but
many compilers still require it
64

Call by Reference
Call by Value 65
Call by Value 66
Call by Value 67
Call-by-Reference Parameters

u Call-by-value is not adequate when we need


a sub-task to obtain input values
u Call-by-value means that the formal parameters
receive the values of the arguments
u To obtain input values, we need to change the
variables that are arguments to the function
u Recall that we have changed the values of
formal parameters in a function body, but we have not
changed the arguments found in the function call
u Call-by-reference parameters allow us to change
the variable used in the function call
u Arguments for call-by-reference parameters must be
variables, not numbers
Call-by-Reference Example

u void getInput(double& fVariable)


{
using namespace std;
cout << “ Convert a Fahrenheit temperature”
<< “ to Celsius.\n”
<< “ Enter a temperature in Fahrenheit: “;
cin >> fVariable;
}
u ‘&’ symbol (ampersand) identifies fVariable as a
call-by-reference parameter
u Used in both declaration and definition!
70

Call by
Ref. vs.
Call by
value
Mixed Parameter Lists

u Call-by-value and call-by-reference parameters


can be mixed in the same function

u Example:
void goodStuff(int& par1, int par2, double& par3);
u par1 and par3 are call-by-reference formal
parameters
u Changes in par1 and par3 change the argument variable
u par2 is a call-by-value formal parameter
u Changes in par2 do not change the argument variable
72

Recursion
What is recursion?

u Sometimes, the best way to solve a


problem is by solving a smaller version of
the exact same problem first
u Recursion is a technique that solves a
problem by solving a smaller problem of
the same type
74

Recursion
IN ALL PATTERNS
75

Recursion
IN NATURE
Recursion

int f(int x)
{
int y;

if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
Example: 77
#include <iostream>
using namespace std;

int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1); // Recursion of sum, keep on repeating until its !=1.
}
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
int result = sum(num);
cout << "Sum of numbers from 1 to " << num << " is: " << result << endl;
return 0;
}
78

Function Testing &


Debuging
Testing and Debugging Functions

u Each function should be tested as a separate unit


u Testing individual functions facilitates finding
mistakes
u Driver programs allow testing of individual
functions
u Once a function is tested, it can be used in the
driver program to test other functions
Stubs

u When a function being tested calls other functions


that are not yet tested, use a stub
u A stub is a simplified version of a function
u Stubs are usually provide values for testing rather
than perform the intended calculation
u Stubs should be so simple that you have confidence
they will perform correctly
Stub Example 81

You might also like