IMAM ABDULRAHMAN BIN FAISAL
UNIVERSITY
College of Computer Science & IT
Department of CS
Welcome to
CS 221:Fundamentals of Programming
Weeks (4): Functions – Par 1
Chapters 9 and 10 (Zak Textbook)
Chapter 4 (Savitch Textbook)
Objectives
• Discover the Top-Down design and its relationship to
functions
• Explain what is functions in C++, and type of functions.
• Introduce standard pre-defined functions and discover how
to use them in a program.
2
CS221: Fundamentals of Programming
TOP-DOWN DESIGN
Top Down Design
• To write a program
– Develop the algorithm that the program will use
– Translate the algorithm into the programming
language
• Top Down Design
(also called stepwise refinement)
– Break the algorithm into subtasks
– Break each subtask into smaller subtasks
– Eventually the smaller subtasks are trivial to
implement in the programming language
Slide 4- 4
Top Down Design
Example: Make Movie
Slide 4- 5
Top Down Design
Example: Main Function in program
Slide 4- 6
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
Slide 4- 7
CS221: Fundamentals of Programming
FUNCTIONS
8 8
Motivation 3
o Suppose that you need to find the sum of integers from 1 to
10, from 20 to 30, and from 35 to 45, respectively.
o So, how do you solve this problem?
int sum = 0;
for (int i = 1; i <= 10; i++) sum += i;
cout << " Sum from 1 to 10 is " << sum ;
sum = 0;
for (int i = 20; i <= 30; i++) sum += i;
cout << " Sum from 20 to 30 is " << sum;
sum = 0;
for (int i = 35; i <= 45; i++) sum += i;
cout << "Sum from 35 to 45 is " << sum ;
What is Function?
• Functions are like building blocks
• They allow complicated programs to be divided into
manageable pieces
• Some advantages of functions:
– A programmer can focus on just that part of the program
and construct it, debug it, and perfect it.
– Different people can work on different functions
simultaneously.
– Can be re-used (even in different programs).
– Enhance program readability.
10
What is Function? (continued)
• Some functions are built-in functions (part of C++): defined in
language libraries
• Others, called programmer-defined functions, are written by
programmers; defined in a program
• Typically, main is used to call other functions, but any
function can call any other function. غالبًا احنا ننادي الفنكشنز في املني بس عادي نناديها في
فنكشن ثانيه
• Functions
– Called modules .
– Like small programs.
– Can be put together to form a larger program.
يعني الفنكشنز زي الوحدات وكأنها برامج صغيرة نستخدمها
عشان نسوي برامج اكبر
11
Function Syntax: Header and Definition
Or
Prototype
• Syntax:
• functionType is also called the data type or return
type
– The function can be of type void, means it does not return
any value:
• Example: void printName(string name)
– Or can be a value-retuned type, where it can returns value
of the type specified by the functionType
• Example: int FindMax(int x, int y)
12
Function Syntax: Header and Definition
• Syntax:
تاخذ القيم من االكشل باراميتر
• Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local
variables which are assigned values from the arguments when
the function is called.
انا احدد قيمتهم ملا انادي الفنكشن
• Formal parameter list can be empty:
ممكن تكون فاضيه يعني ما
تحتاج انها تاخذ مني قيم
13
Function Syntax: Function Call
Actual parameter: calيعني
• When a function is called, the values (expressions) that are passed in
the call are called the arguments or actual parameters (both terms
mean the same thing).
• At the time of the call each actual parameter is assigned to the
corresponding formal parameter in the function definition.
• The syntax of the actual parameter list is:
We can put variable or constant or expression in the actual parameter
• A call to a function with an empty actual parameter list is:
14
Function Syntax (Example)
• Heading:(Function Type, Function Name, Formal Parameters)
– Example: int abs(int number) Heading
• Formal Parameter: variable(s) declared in the heading
– Example: number // in the heading above
• Actual Parameter: variable(s) or expression(s) listed in a
call to a function
– Example:
• x = pow(u, v) // u and v are actual parameters
• int z = abs(-5) // -5 is actual parameter
15
Functions Type OR Returning Type
Returning
Type
Value
Void
returning-
16
Functions Type OR Returning Type
• Value-returning functions: have a return type
– Return a value of a specific data type using the
return statement
• Void functions: do not have a return type
– Do not use a return statement to return a value
17
Void Functions
• Void functions and value-returning functions have similar
structures
– Both have a heading part and a statement part
• A void function does not have a return type
– return statement without any value is typically used to
exit the function early ﻋﺸﺎن ﻧﺨﻠﺺ ﻣﻦ اﻟﻔﻨﻜﺸﻦreturn ﻧﻘﺪر ﻧﺤﻂ
اﺳﺮع ﺑﺲ اﻧﮭﺎ ﻣﻮ ﺿﺮورﯾﺔ
• void is a reserved word
• A call to a void function is a stand-alone statement
18
Void Functions with Parameters
• Function definition syntax:
الفرق الرئيسي
void بينهم ان
return مافيها
• Formal parameter list syntax:
• Function call syntax:
• Actual parameter list syntax:
Expression or variable or constant 19
Value-Returning Functions
• To use these functions you must:
– if the function is pre-defined, then Include the
appropriate header file in your program using the
#include statement,
– Know the following items:
• Name of the function
• Number of parameters, if any
• Data type of each parameter
• Data type of the value returned: called the type of the
function
20
Value-Returning Functions
(continued)
• Because the value returned by a value-returning
function is unique, we must:
– Save the value for further calculation
– Use the value in some calculation
– Print the value
• A value-returning function is used in an assignment or
in an output statement
21
return Statement
• Once a value-returning function computes the value,
the function returns this value via the return
statement
– It passes this value outside the function via the
return statement
22
Syntax: return Statement
• The return statement has the following syntax:
• In C++, return is a reserved word
• Expression can be any expression that must evaluate to
something compatible with the returnValueType
• When a return statement executes
– Function immediately terminates
– Control goes back to the caller
• When a return statement executes in the function
main, the program terminates
23
Syntax: return Statement
وﺣﺪة ع اﻻﻗﻞ وﻣﻤﻜﻦ اﻛﺜﺮreturn اﻟﻔﻨﻜﺸﻦ اﻟﻠﻲ ﺗﺴﻮي رﯾﺘﯿﺮن ﯾﻌﻨﻲ اي ﻓﻨﻜﺸﻦ ﻏﯿﺮ اﻟﻔﻮﯾﺪ ﻻزم ﯾﻜﻮن ﻓﯿﮭﺎ
• The body of a method that returns a value must contain
one or more return statements
ﺑﺲ ﻣﺮات ﻧﺒﻲ ﻧﺨﻠﺺ ﻣﻦ اﻟﻔﻨﻜﺸﻦ اﺳﺮع ﻣﺜﻼ ﻣﺎﻧﺒﯿﮫ ﯾﻜﻤﻞ ﺑﺎﻗﻲ اﻟﻜﻮد ﻓﻨﺤﻄﮭﺎreturn ﯾﻌﻨﻲ اﻟﻔﻮﯾﺪ ﻣﺎ ﺗﺘﻄﻠﺐ ﻧﺤﻂ
• A void method does not require a return statement,
unless there is a situation that requires the method to
end before all its code is executed.
– In this context, since it does not return a value, a
return statement is used without an expression:
return;
24
Value-Returning Functions (continued)
25
Does the following functions do
the same thing?
26
Types of Functions
Functions
Pre-defined User-defined
27
CS221: Fundamentals of Programming
PRE-DEFINED FUNCTIONS
28
Function Libraries
• Predefined functions are found in libraries
• The library must be “included” in a program
to make the functions available
• An include directive tells the compiler which
library header file to include.
– You cannot use functions without calling its header.
– In case you call function without includes its header, linking
error will appear in compilation time.
iostream cmath cctype cstdlib
cout sqrt tolower rand
cin Pow toupper abs
floor
Slide 4- 29
Includes Predefined Functions
• To include the math library containing sqrt():
#include <cmath>
• Newer standard libraries, such as cmath, also require
the directive
using namespace std;
30
Function Call Syntax
• Function_name (Argument_List)
– Argument_List is a comma separated list:
(Argument_1, Argument_2, … , Argument_Last)
• Example:
– side = sqrt(area);
– cout << “2.5 to the power 3.0 is “
<< pow(2.5, 3.0);
Slide 4- 31
Predefined Functions (continued)
• pow(x,y) calculates xy
pow and sqrt
– x and y are the parameters (or arguments) return
– Returns a value of type double
– pow(2, 3) = 8.0 double!!!
– The function has two parameters : 2 and 3
• sqrt(x) calculates the nonnegative square root of x, for
x >= 0.0
– x is the parameter (or argument)
– Returns a value of type double
– sqrt(2.25) is 1.5
– The function has only one parameter : 2.25
32
Predefined Functions (continued)
• floor(x) calculates largest whole number not greater than
x
– x is the parameter (or argument) Floor also return
– Returns a value of type double Double!!
– floor(48.79) is 48.0
– The function has only one parameter: 48.79
تطلع اكبر عدد صحيح بس
مو اكبر من الرقم نفسه
33
)Predefined Functions (continued
كلهم دبل اال absو randوخواتها و tolowerو toupper
abs(-7.33) = 7
اصغر عدد صحيح بس مو اصغر من العدد نفسه
ﺗﻮﺧﺮ اﻟﻔﺎﺻﻠﮫ ﺑﺲ اﻟﻌﺪد اﻛﺒﺮ
34
Predefined Functions (continued)
ﺗﻮﺧﺮ اﻟﻔﺎﺻﻠﮫ وﻧﻔﺲ اﻟﻌﺪد
35
Predefined Functions (code)
36
Predefined Functions (code)
• Example 6-1 sample run:
37
An Example Program
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
Int main()
{
cout<<"abs(3.5): "<<abs(3.5)<<endl;
cout<<"abs(-3.5): "<<abs(-3.5)<<endl;
cout<<"ceil(59.76): "<<ceil(59.76)<<endl;
cout<<"ceil(-59.76): "<<ceil(-59.76)<<endl;
cout<<"exp(1) : "<<exp(1)<<endl;
cout<<"fabs(3.5): "<<fabs(3.5)<<endl;
cout<<"cos(0): "<<cos(0)<<endl;
cout<<"floor(40.8): "<<floor(40.8)<<endl;
cout<<"floor(-40.8): "<<floor(-40.8)<<endl;
cout<<"tolower(65): "<<tolower(65)<<endl;
cout<<"toupper(97) : "<<toupper(97)<<endl;
Return 0;
} 38
39
40
Predefined Functions (example)
• The rand, srand, and time Functions
Positive integer number less than RAND_MAX constant in my compiler
RAND_MAX >= x >= 0
• rand():The function returns an integer that is greater than
or equal to 0 but less than or equal to the value stored in the
RAND_MAX constant, which is one of many constants built into
the C++ language.
• RAND_MAX Constant
– Varies with different compilers:
• Its value is always at least 32,767.
– To display your compiler’s RAND_MAX value:
• cout << RAND_MAX;
41
Predefined Functions (example)
Assign it to variable
Cout it
Use it in calculation
42
Predefined Functions (example)
Generate Random value within a Specific range
اصغر قيمة اكبر قيمة اصغر قيمة
Range ( 1-6 )
عشان مايعطيني صفر1+
43
Predefined Functions (example)
Generate Random value within a Specific range
44
Predefined Functions (example)
• You should initialize the random number generator in each
program in which it is used. Otherwise, it will generate the
same series of numbers each time the program is executed.
لحالها بيعطيني قيمة ثابته دائماrand ملا تكون
• Typically, the initialization task is performed at the beginning
of the program. You initialize the generator using the srand
function. rand depends on srand
وحطيت داخلها قيم مختلفة بيتغير الرقم كل مرةsrand(x) بس لو استخدمت معها
• A more common way to initialize the generator is to use the
C++ time() function with srand() function.
هذي اظن تعطيني قيم بناء على الوقت
45
Predefined Functions (example)
46
Random Number Generator (code)
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
cout << RAND_MAX;
srand(time(0));
// or srand(static_cast<int>(time(0)));
int no;
for (int j=0; j<5; j++)
{
no=rand();
cout<<endl<<"No genrated: "<<no;
} 47