PL1 Lec4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Fundamental of Programming I

CSC 102 – Lec4:Functions

Ghada Khoriba
[email protected]
Reference
Main reference book:
• Problem Solving with C++, 10th Edition, Global Edition Walter Savitch
Chapters 1-9.
• On https://pearson.turingscraft.com/
CourseID (a.k.a. "Section Access Code"): SMSDEFINS-7678-0

For lectures and practice sheets, MS Teams Code: 7db8djw

2
Course
Contents
01. Introduction 03. Functions
› PROGRAMMING AND PROBLEM- › Predefined / programmer defined
SOLVING › Scope and local variables
› High-Level Languages vs low-level › Call by reference
language
› Introduction to C++ 04. Arrays
› Declaration
02. C++ Basics › With loops / functions
› Search / Sort
› Variables and assignments / Data types
and expressions
› I/O 05. Pointers and Dynamic Arrays
› Branching Mechanisms & Boolean
06. Strings and vectors
expressions / Loops
07. I/O streams, using files

3
Recap

4
Self-assessment Quiz
int number = 2;
int valueProduced = 2 * (number++);
cout << valueProduced << endl; 4
cout << number << endl; 3

int number = 2;
int valueProduced = 2 * (++number);
6
cout << valueProduced << endl; 3
cout << number << endl;

5
Self-assessment Quiz
Q1- What is the output of the following (when embedded in a complete
program)?
int n = 1;
do 123
cout << n << " ";
while (++n <= 3);

int n = 1;
do
cout << n << " ";
while (n++ <= 3) 1234

6
Self-assessment Quiz
for (double sample = 2; sample > 0; sample -= 0.5)
cout << sample << " ";

2 1.5 1. 0.5

Rewrite the following loops as for loops.


int i = 1;
while(i <= 10)
for (int i=1;i<=10;i++)
{ {
if (i < 5 && i != 2) if (i < 5 && i != 2)
cout << 'X’;
cout << 'X’;
i++; }

}
7
Write C++ program to find Armstrong numbers between 1 to n

for (i = lower + 1; i < higher; i++)


{
temp2 = i;
temp1 = i;
// number of digits calculation
while (temp1 != 0)
{
temp1 /= 10;
n++;
}
// result contains sum of nth power of its digits
while (temp2 != 0)
{
rem = temp2 % 10;
result += pow(rem,n);
temp2 /= 10;
}
// checking if number i is equal to the sum of nth power of its digits
if (result == i) {
cout<<i<<endl;
}
// resetting the values to check Armstrong number for next iteration
n = 0;
result = 0;
}
8
Top Down Design Eventually the smaller subtasks are trivial to
implement in the programming language

Break the algorithm into subtasks

Break each subtask into smaller subtasks

9
Benefits of Top Down Design

• Subtasks, or functions in C++, make programs


• Easier to understand
• Easier to change
• Easier to write
• Easier to test
• Easier to debug
• Easier for teams to develop
Function
Function Call
A function call is an expression consisting of the function name followed by
arguments enclosed in parentheses.
SYNTAX
Function_Name(Argument_List)
where the Argument_List is a comma-separated list of arguments:
Argument_1, Argument_2, ... , Argument_Last
EXAMPLES
side = sqrt(area);
cout << "2.5 to the power 3.0 is "
<< pow(2.5, 3.0);

11
e scaled by modulus and addition. For example, to simulate rolling
predefined functions, example
ided die we could use the following:
int die = (rand() % 6) + 1;

he random number modulo 6 gives us a number between 0 and 5. Add


esults in a random integer that is in the range from 1 to 6.
It is important to seed the random number generator only once. A
mon error is to invoke srand every time a random number is genera
oth srand and rand are placed in a loop, then the likely result is a seq
f identical numbers, because the computer runs quickly enough that th
alue will probably not change for repeated calls to srand.

The number of seconds elapsed since January 1, 1970 is known as Unix time.
12
DISPLAY 4.3 A Function Definition

1 #include <iostream> function declaration/function


2 using namespace std; prototype
3
4 double totalCost(int numberPar, double pricePar);
5 //Computes the total cost, including 5% sales tax,
6 //on numberPar items at a cost of pricePar each.
7
8 int main( )
9 {
10 double price, bill;
11 int number;
12

PROGRAMMER-
13 cout << "Enter the number of items purchased: ";
14 cin >> number;
15 cout << "Enter the price per item $";
16 cin >> price; function call

DEFINED
17
18 bill = totalCost(number, price);
19

FUNCTIONS
20 cout.setf(ios::fixed);
21 cout.setf(ios::showpoint);
22 cout.precision(2);
23 cout << number << " items at "
24 << "$" << price << " each.\n"
25 << "Final bill, including tax, is $" << bill
26 << endl;
27
28 return 0; function heading
29 }
30
31 double totalCost(int numberPar, double pricePar)
32 {
33 const double TAX_RATE = 0.05; //5% sales tax
34 double subtotal; function function
35 body definition
36 subtotal = pricePar * numberPar;
37 return (subtotal + subtotal * TAX_RATE);
38 } 13
Function Definition
n Provides the same information as the declaration
n Describes how the function does its task
function header
n 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

Copyright © 2018 Pearson Education, Ltd. All rights reserved.


The Return Statement
n Ends the function call
n Returns the value calculated by the function
n Syntax:
return expression;
n expression performs the calculation

or
n expression is a variable containing the

calculated value
n Example:
return subtotal + subtotal * TAX_RATE;

Copyright © 2018 Pearson Education, Ltd. All rights reserved.


The Function Call

n Tells the name of the function to use


n Lists the arguments
n Is used in a statement where the returned value
makes sense
n Example:

double bill = totalCost(number, price);


The values of the arguments are plugged into
the formal parameters (Call-by-value mechanism
with call-by-value parameters)

Copyright © 2018 Pearson Education, Ltd. All rights reserved.


DISPLAY 4.4 Details of a Function Call

int main()
{
double price, bill;
int number; 1. Before the function is called, values of
cout << "Enter the number of items purchased: "; the variables number and price are set
cin >> number; to 2 and 10.10, by cin statements (as
cout << "Enter the price per item $"; you can see the Sample Dialogue in
cin >> price; Display 4.3)

bill = totalCost (number, price); 2. The function call executes and the value
2 10.10 of number (which is 2) plugged in for
cout.setf (ios::fixed); numberPar and value of price (which
cout.setf (ios::showpoint); is 10.10) plugged in for pricePar.
cout.precision(2);
cout << number << " items at "
<< "$" << price << " each.\n"
21.21 << "Final bill, including tax, is $" << bill
<< endl;
return 0;
} 2 10.10
double totalCost (int numberPar, double pricePar)
3. The body of the function executes
{
with numberPar set to 2 and
const double TAX_RATE = 0.05; //5% sales tax
pricePar set to 10.10, producing the
double subtotal;
value 20.20 in subtotal.
subtotal = pricePar * numberPar;
4. When the return statement is executed,
return (subtotal + subtotal * TAX_RATE);
the value of the expression after return is
}
evaluated and returned by the function. In
21.21 this case, (subtotal + subtotal *
TAX_RATE) is (20.20 + 20.20*0.05)
or 21.21.

5. The value 21.21 is returned to where the function was invoked. The result is that
totalCost (number, price) is replaced by the return value of 21.21. The
value of bill (on the left-hand side of the equal sign) is set equal to 21.21 when 17
the statement bill = totalCost (number, price); finally ends.
Function Declaration

Type_Returned Function_Name(Parameter_List);
Function_Declaration_Comment

Function Definition

Type_Returned Function_Name(Parameter_List) function


{ header
Declaration_1
Declaration_2
. . .
Declaration_Last
body Executable_Statement_1 Must include one or
Executable_Statement_2 more return
. . . statements.
Executable_Statement_Last
}

Example: Given the function declaration:


char grade(int received_par, int minScore_par);

int received = 95, minScore = 60;

cout << grade( minScore, received); Arguments in the Wrong Order

Local vs global variables


18
argument is a decimal digit; otherwise, it returns false.

14. Write a function definition for a function isRootOf that takes two arguments
of type int and returns a bool value. The function returns true if the first
argument is the square root of the second; otherwise, it returns false.

4.4 bool
PROCEDURAL
isRootOf(intABSTRACTION
rootnum, int number) {
return (number == rootnum * rootnum); }
The cause is hidden, but the result is well known.
OVID, Metamorphoses IV

The Black-Box Analogy


A person who uses a program should not need to know the details of how the
program is coded. Imagine how miserable your life would be if you had to
19

You might also like