Fundamentals of Structured
Programming
Lecture 2 - Functions (Pass By Value)
Agenda
• Top-down Design.
• Function Parts.
• Local vs. Global variables.
• Overloading a function name.
• Default Values.
• Built-in functions
-2-
1. Top-down Design
• If we look at a big problem as a whole, it may
seem hard to solve because it is so complex.
• Complex problems can be solved using top-down
design, where:
– We break the problem into parts.
– Then break the parts into parts.
– Soon, each of the parts will be easy to do.
3
1. Top-down Design (cont.)
• A methodology of information processing,
problem solving, and knowledge representation,
that starts at the highest level of a design concept
and proceeds towards the lowest level.
4
1. Top-down Design (cont.)
Example
• Problem: we want to automate sending
emails for students who have passed
their absence limits.
5
1. Top-down Design (cont.)
Example
• Possible solution:
1 Get students list from files
2 Sort according to absence times
3 Select those with more than 3 times
4 Send an email for each student
Send
6
1. Top-down Design (cont.)
Example
• Problem: Write a program that draws
this picture of a house.
7
1. Top-down Design (cont.)
Example
• Possible solution:
1. Draw the outline of the house
2. Draw the chimney
3. Draw the door
4. Draw the windows
Are there any parts
to divide?
8
1. Top-down Design (cont.)
Example
• Possible solution:
1. Draw the outline of the house
2. Draw the chimney
3. Draw the door
Call Draw Door Frame
Call Draw Knob
4. Draw the windows
Draw Window 1
Draw Window 2
Draw Window 3
9
1. Top-down Design (cont.)
Example
• Possible solution:
1. Draw the outline of the house
2. Draw the chimney
3. Draw the door
Call Draw Door Frame
Call Draw Knob
4. Draw the windows
Draw a Window in Location 1
Draw a Window in Location 2
Draw a Window in Location 3
Code/get code for each step.
Code reusability
10
1. Top-down Design (cont.)
• Top-down is a standard way of writing
programs.
• Programs produced using this method and
using the control structures (sequential,
selection and repetition) are called structured
programs.
• Structured programs are easier to test, modify,
and are also easier for other programmers
to understand.
11
1. Top-down Design (cont.)
Advantages
• Breaking the problem into parts helps us to
clarify what needs to be done.
• At each step of refinement, the new parts become
less complicated and, therefore, easier to figure
out.
• Breaking the problem into parts allows more than
one person to work on the solution.
• Parts of the solution may turn out to be reusable.
Typically, each part will be coded as a separate
function.
12
Functions
• Building blocks of programs in
C++: functions
• I-P-O
– Input – Processing – Output
– Sometimes a function has no
input.
– Sometimes a function returns
no output.
13
Functions
Programmer- defined
14
Programmer-defined Functions
15
Programmer-defined Functions
• Three parts in using any function:
– Function Declaration
• Information for compiler
• To properly interpret calls
– Function Definition (Body of the function)
• Actual implementation (code) of what the function does
– Function Call
• Using the function
• Transfers control to function body
• Arguments are plugged in for formal parameters
16
Declaration
Call
Definition
17
Programmer-defined Functions
(1) Function Declaration
• Syntax:
return_type Fn_name(parameter list);
• Formal parameters can be of any type and number.
• A function can return ONLY ONE value or VOID.
18
Programmer-defined Functions
(2) Function Definition (Body)
• Implementation of the function.
• Placed after main() or instead of declaration.
• Syntax:
return_type Fn_name(parameter_list)
{
// your code goes here
}
• Returned value type, and formal parameters
type, order and number should match the
function declaration.
19
Programmer-defined Functions
(2) Function Definition
Formal parameters: Variable names
refer to data in definition
A return statement sends
data back to caller and
can return only one value.
20
Programmer-defined Functions
(3) Function Call
• To execute its body.
If the function
Fn_name(arguments_list); returns nothing
result = Fn_name(arguments_list);
If the function returns A VALUE OF THE
SAME TYPE AS RESULT
• Arguments type, number and order should
match the function declaration.
• A function to execute must be called in a way
or another in the main function.
21
Programmer-
defined Functions
(3) Function Call
Arguments can be
literals, variables,
expressions, or
combination
22
Programmer-defined Functions
(3) Function Call
Call can be placed in
an expression or a
cout statement, ONLY
if the function has a
23
return value
1. Definition of the function is placed after
main() and declaration before main().
24
2. Definition of the function is placed instead
of declaration (before main()).
25
Programmer-defined Functions
Example 1 – void function
• A void function does not return a
value.
• When being called, it cannot be used
in expressions, or in assignment
statements.
• void function with void parameters
• void function with parameters
26
// declaration
void welcome ();
int main()
{
cout << "Main\n";
// call
welcome (); // No expression or assignment statement
cout << "after calling\n";
return 0;
} // end main
// definition
void welcome ()
{
int repeat;
cin >> repeat;
for (int i = 1; i <= repeat; i++)
cout << "Hi\tWelcome to my game!\n";
} // end welcome
// declaration 29 or 30 Example 2
*
double sum (double x, double y, double z);
int main()
{
double A, B, C, result;
A = 1; B = 2; C = 3; //cin >> A >> B >> C;
// processing
A++;
// call
result = sum (A, B, C); // call by value
// output
cout << “ In main , B: " << B << " and Result: "<< result << endl;
return 0;
} // end main
// definition final output:
double sum (double A, double B, double C)
4
{
B = B + 2;
2
cout << "In function sum, B: " << B << endl; 9
return A + B + C;
} // end sum 28
// declaration 29 or 30 Memory
double sum (double x, double y, double z); A 2
variables
B 2 in main
int main()
{ C 3
double A, B, C, result;
A = 1; B = 2; C = 3;
A 2
// processing function
A++; =2 B 2 4 parameters
9 // call 2 2 3 C 3
result = sum (A, B, C); // call by value
// output 2 9
cout << “ In main , B: " << B << " and Result: "<< result << endl;
return 0;
} // end main copy
values
// definition 2 2 3
double sum (double A, double B, double C)
{
B = B + 2; =4 4
cout << "In function sum, B: " << B << endl;
return A + B + C;
2 + 4 + 3 =9
29
} // end sum
Programmer-defined Functions
(5) Parameters vs Arguments
• Formal parameters
– In function declaration
– In function definition’s header
Parameters: "Variables names"
used to refer to data in definition
or declaration (optional)
30
Programmer-defined Functions
(5) Parameters vs Arguments
• Actual parameters/arguments
– In function call
Calling by value
31
Programmer-defined Functions
Function call
parameters_list
32
Programmer-defined Functions
Keep in mind: Calling/Passing by value
1. The value of the argument (not the variable)
that is plugged in for the formal parameter.
2. Arguments are plugged in for formal
parameters in the order they appear in the
function call.
3. When an argument is plugged in for a formal
parameter, it is plugged in for ALL instances of
this parameter that occur in the function body.
33
Programmer-defined Functions
(6) Local Variables
– Declared inside body of given function
– Available only within that function
• Can have variables with same names
declared in different functions
– Scope is local: "that function is its scope"
• Local variables preferred
– Functions should declare whatever local
data needed to “do their job”.
34
Programmer-defined Functions
Local Variables
• Local variables are
declared within a
scope.
• A function can
declare its own local
variables as needed.
35
Programmer-defined Functions
Local Variables
• Can have variables
with same names
declared in
different functions
• Same name BUT
they are totally
different locations
in memory.
Check
Example3
.cpp 36
Exercise
Write a program that uses a function
to take three arguments and returns
true if the three arguments are
ascendingly ordered, otherwise it
returns false.
38
#include <iostream>
using namespace std;
bool isInOrder (int, int, int); // declaration
void main()
{
int n1, n2, n3;
cout << " Enter three numbers\n";
cin >> n1 >> n2 >> n3;
bool check = isInOrder( n1, n2, n3); // call
if (check)
cout << "In order\n"; If(isInOrder( n1, n2, n3))
else
cout << "Not arranged\n";
bool isInOrder( int a, int b, int c) // definition
{
if (a <= b && b <= c) Change the program to return
return true; true whether they are ASC or
else DESC ordered.
return false;
} 39
Exercise
Write a program that reads the employee
salary and uses a function to calculate the
taxes according to the following rules.
Salary Tax
2000 - 3999 5%
Between 4000 and 6000 7%
More than 6000 10%
40
#include <iostream>
using namespace std;
float CalcTax (float salary);
void main()
{
float empSal;
cout << "Enter the salary\n";
cin >> empSal;
float tax = CalcTax (empSal);
if (tax != -1)
cout << tax << endl;
else
cout << "Invalid salary\n";
} 41
float CalcTax (float sal)
{
if (sal >= 2000 && sal < 4000)
return sal * 0.05;
else if (sal >= 4000 && sal <= 6000)
return sal * 0.07;
else if (sal > 6000)
return sal * 0.1;
else
return -1; // there is a problem
}
42
Programmer-defined Functions
(7) Global Constants/Variables
– Declared outside all functions, hence
defined for all functions below it.
43
Programmer-defined Functions
Constant needed in the
two functions
44
Constant is global to
all functions below its
declaration
45
Constant global to all
functions below its
declaration
What if we declared a local
variable with the same
name as a global one?
3.1428574
46
=6 =8
=5
=6 =5
=6
47
Built in Functions
(Self study)
Built in functions
#include library file
Call the function giving its parameters
Examples:
Math Functions
Swap
Rand
Strings, File Streams.
(For Projects – not in the exam ☺)
-49-
Built-in Function usage cmath.cpp
1 2
(1) Pay attention compiler! We’ll
use something from that file.
4 (2) Check arguments types,
number, and return type, with the
function declaration.
(3) Control transfers to the
function definition.
(4) Control returns to the caller
bringing back a value.
50
51
Built-in Functions (Mathematics)
Example 1:
Write a program that reads in 2 numbers and uses
built-in functions for calculating the 1st number
to the power of the 2nd number, Sample
execution:
Enter the base: 3
Enter the exponent: 2
3 ^2 = 9
Use: #include<math.h>
-51-
#include<iostream>
#include<math.h> /*for built-in functions only add
the header file */
using namespace std;
void main()
{
float base, exponent, number, power, root;
cout<<"Enter the base: ";
cin>>base;
cout<<"Enter the exponent: ";
cin>>exponent;
power=pow(base,exponent); /*calling*/
cout<<base<<"^"<<exponent<<"= "<<power<<endl;
52
BUILT-IN FUNCTIONS (CHARACTERS)
Example 2:
Write a program which asks the user to enter password, then it compares it
to a stored password in the program and outputs valid or invalid. The user
should be given only 3 trials then the program should terminate.
Note: As the user types the password on the screen, each
character should appear as an asterisk.
Hint: Notice the difference between getch (reads char without showing it
in the console screen) and getche (get character with echo)
Use: #include<conio.h>
53
#include<iostream>
using namespace std;
#include<conio.h> // for getch()
void main()
{
char ch;
char correct[] = "123";
int trials = 1;
bool verified = true;
do
{
cout<< "Enter your password: ";
ch = getch();
int i = 0;
verified = true;
while(ch != '\r') //continue reading till you reach Enter
{
cout<< "*";
if (ch != correct[i])
{ verified = false; i++;}
ch = getch();
}
if (!verified)
cout<<"\nWrong password!"<<endl;
else
cout<<"\nLogin successfully "<<endl;
trials++;
} while (!verified && trials <= 3); // continue as long as
didn't submit correct password and trials didn't exceed 3
}
Summary
Keep in mind:
• Procedural abstraction.
• Need to know "what" function does, not
"how" it does it!
• Think "black box"
– Device you know how to use, but not its
method of operation
• Implement functions like black box
– User of function only needs: declaration
– Does NOT need function definition
(Called Information Hiding).
56
Home Assignment 2
In our factory, we have multiple products. The details of each product are
serialNum, quantity, totalSales)
Write a C++ program that does the following:
1.Read from the user data of four products in three 1D arrays. serialNum,
quantity and totalSales arrays. The arrays’ indices represent the number of
the product.
void InputProducts ();
2. Display the serial number of the products that have less quantity than a value
entered by the user (quant).
void ProductsLessThan (int quant);
3.Function that will return the index of the product with the highest sales.
int GetIndexOfHighestSales ();
Note that the arrays will be global.
57
Please enter the four products: Serial Numbers of the Products that has less
quantity than a value entered by the user:
Enter values of product #1
Please enter the quantity: 11
Serial num : 101
Product 101
quantity: 5
Product 102
sales : 10
Product 104
Enter values of product #2
Product with the highest sales
Serial num : 102
Product 3
quantity: 10
sales : 6
Enter values of product #3
Serial num : 103
Sample
quantity: 11
sales : 20 Run
Enter values of product #4
Serial num : 104
quantity: 9
sales : 12 58
To Do list Next Time : Project Announcement!
• Sheet 2
• Home Project Assignment 2
59