SlideShare a Scribd company logo
1 of 28
C++ Programming
Functions – Part #1
2
C++ Programming
Objectives
• Learn about standard (predefined) functions and
discover how to use them in a program
• Learn about user-defined functions
• Examine value-returning functions, including actual
and formal parameters
• Explore how to construct and use a value-returning,
user-defined function in a program
3
C++ Programming
Functions
problem
Subprobelm1 Subprobelm2 Subprobelm3
Subprobelm1.1 Subprobelm1.2
Subprobelm3.1 Subprobelm3.3
Subprobelm3.2
4
C++ Programming
output
input
Functions (Continued)
function
5
C++ Programming
8
3
2
Functions (Continued)
pow(x, y)
17
2
5x + 7
6
C++ Programming
•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 used in more than one place in a
program or in different programs
Functions (Continued)
7
C++ Programming
• A function has a name.
•A function may has argument(s).
•A function may produce a result.
Functions (Continued)
8
C++ Programming
Predefined Functions
• In algebra, a function is defined as a rule
or correspondence between values, called
the function’s arguments, and the unique
value of the function associated with the
arguments
• If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and
f(3) = 11
• 1, 2, and 3 are arguments
• 7, 9, and 11 are the corresponding values
9
C++ Programming
Predefined Functions (Continued)
• Some of the predefined mathematical
functions are:
– sqrt(x)
– pow(x,y)
– floor(x)
– rand()
10
C++ Programming
Predefined Functions (Continued)
11
C++ Programming
Predefined Functions (Continued)
• Predefined functions are used in a
program as if they are single variables.
• When a function is used, the compiler
uses to the value that the function
produces and returns.
• A function value can be printed, used in
an assignment statement, or used as part
of an expression.
12
C++ Programming
Predefined Functions (Continued)
• cout << cos(3.1); print the value of
cos(3.1).
• y = 5*cos(3.1)–7; multiply cos(3.1) by 5
and subtract 7 to, then assign the result
to y.
• You cannot extract / assign a value to a
function.
cin >> cos(3.1); is illegal.
cos(3.1) = 5 * x + 2; is illegal.
13
C++ Programming
Predefined Functions (Continued)
• Predefined functions are organized into separate
libraries.
• To use a predefined function, the program must
include the header file that contains the
function’s specifications.
• To use the predefined math functions sqrt(),
pow(), … must have #include <cmath>
• To use the I/O functions, must have
#include <iostream>
• Example of another header file that you have
seen so far is ….
14
C++ Programming
Predefined Functions (Continued)
• The function rand() generates random one of the
numbers 0, 1, 2, 3, 4, …
• The function rand() %2 generates 0 or 1
• The function 1 + rand() %6 generates 1, 2, 3, 4, 5, 6
• The function m + rand() % (n-m+1) generates a
random number in the interval [m, n]
• To use rand() use the library #include<cstdlib>
• To generate different random numbers use
srand(time(0)) on a line by itself
• To use time(0) use the library #include<ctime>
15
C++ Programming
Write a program that reads the (x, y) coordinates of a point in the Cartesian
coordinates, converts to polar coordinates (r,  ), and prints the polar
coordinates.
𝑟 = 𝑥2 + 𝑦2, 𝜃 = 𝑡𝑎𝑛−1
𝑦
𝑥
Program: toPolar.cpp
Program: toPolar.exe
Program: CartesiantoPolar()
16
C++ Programming
User-Defined Functions
• User defined functions are like predefined
functions but the programmer has to write
them.
• Example:
– Find the max of two numbers.
17
C++ Programming
#include <iostream>
using namespace std;
double larger(double x, double y);
int main()
{
double num1, num2, maximum;
cin >> num1 >> num2;
maximum = larger(num1, num2);
cout << "The maiximum is " << maximum << endl;
return 0;
}
double larger(double x, double y)
{
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
18
C++ Programming
#include <iostream>
using namespace std;
double larger(double x, double y);
int main()
{
double num1, num2, largest;
cin >> num1 >> num2;
largest = larger(num1, num2);
cout << "The largest is " << largest << endl;
return 0;
}
double larger(double x, double y)
{ double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
Function
header/heading
Function body
Function formal
parameters
Function actual
parameters
Function
type
Function prototype
Function definition
19
C++ Programming
User-Defined Functions (Continued)
• The number of formal parameter must
match the number of actual parameters
• The data type of each actual parameter
must match its corresponding formal
parameter.
• A function call in a program results in
the execution of the body of the called
function.
20
C++ Programming
User-Defined Functions (Continued)
• The function syntax:
functionType functionName(formal parameters)
{
statements
}
• Some functions have no parameters,
such as int main().
• Some functions return nothing, so the
return value is void.
21
C++ Programming
User-Defined Functions (Continued)
• A C++ program is made out of a set of
functions.
• main() is just a user defined function.
• Execution always begins at the first statement
in the function main.
• Other functions are executed only when they
are called.
22
C++ Programming
User-Defined Functions (Continued)
• When a return statement executes
– Function immediately terminates.
– Control goes back to the caller.
– The function call statement is replaced by
the returned value.
• When a return statement executes in the
function main(), the program terminates.
23
C++ Programming
User-Defined Functions (Continued)
• A user-defined function can be placed before
the function main. In that case the function
prototype is not necessary.
• A function that returns a value is called a value-
returning functions and it must have a data
type.
• A function that does not return a value (i.e.
does not have a return statement) is called a
void function and it does not have a type (its
type is void).
void funtionName(formal parameters)
24
C++ Programming
Write a program that reads a positive integer num, calls the function
isPerfect() which checks, and prints whether num is a perfect number or not.
A perfect number is a positive integer that is equal to the sum of its proper
divisors. For example, 6 is a perfect number because 6 = 1 + 2 + 3, also 28
is a perfect number because 28 = 1 + 2 + 4 + 7 + 14.
Program: isPerfect.cpp
Program: isPerfect.exe
Program: isPerfect()
25
C++ Programming
Write a program that reads a positive integer num, calls the function
isPrime() which checks, and prints whether num is a prime number or not.
A prime number is a positive integer that is divisible by 1 and itself only. For
example, 7, 11, 13, 17, … are prime numbers, while 15 = 3 * 5 is not a prime
number.
Program: isPrime.cpp
Program: isPrime.exe
Program: isPrime()
26
C++ Programming
Write a program that reads a positive integer N, calls the function Fibonacci()
which calculates, and prints the Nth Fibonacci number.
Fibonacci numbers satisfy the following recurrence relation
𝑎0 = 1, 𝑎1 = 1, 𝑎𝑛+2 = 𝑎𝑛+1 + 𝑎𝑛, 𝑛 0
Each Fibonacci number is the sum of the two previous Fibonacci numbers.
Program: Fibonacci.cpp
Program: Fibonacci.exe
Program: Fibonacci()
27
C++ Programming
Write a program that reads two positive integers n and k, calls the function
binomial() which calculates, and prints the binomial coefficient of n and k.
Fibonacci numbers satisfy the following recurrence relation
𝐶𝑘
𝑛
=
𝑛
𝑘
=
𝑛!
𝑛 − 𝑘 ! 𝑘!
Program: binomial.cpp
Program: binomial.exe
Program: binomial()
28
C++ Programming
Write a program that prints a menu and based on the user choice, the
program preforms a job.
Program: menu.cpp
Program: myLibrary.h
Program: menu.exe
Program: Menu

More Related Content

Similar to Programming For Engineers Functions - Part #1.pptx

Similar to Programming For Engineers Functions - Part #1.pptx (20)

Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
P3
P3P3
P3
 
C++
C++C++
C++
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
L4 functions
L4 functionsL4 functions
L4 functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function
FunctionFunction
Function
 
Functions
FunctionsFunctions
Functions
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 

Recently uploaded

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Recently uploaded (20)

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Programming For Engineers Functions - Part #1.pptx

  • 2. 2 C++ Programming Objectives • Learn about standard (predefined) functions and discover how to use them in a program • Learn about user-defined functions • Examine value-returning functions, including actual and formal parameters • Explore how to construct and use a value-returning, user-defined function in a program
  • 3. 3 C++ Programming Functions problem Subprobelm1 Subprobelm2 Subprobelm3 Subprobelm1.1 Subprobelm1.2 Subprobelm3.1 Subprobelm3.3 Subprobelm3.2
  • 6. 6 C++ Programming •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 used in more than one place in a program or in different programs Functions (Continued)
  • 7. 7 C++ Programming • A function has a name. •A function may has argument(s). •A function may produce a result. Functions (Continued)
  • 8. 8 C++ Programming Predefined Functions • In algebra, a function is defined as a rule or correspondence between values, called the function’s arguments, and the unique value of the function associated with the arguments • If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11 • 1, 2, and 3 are arguments • 7, 9, and 11 are the corresponding values
  • 9. 9 C++ Programming Predefined Functions (Continued) • Some of the predefined mathematical functions are: – sqrt(x) – pow(x,y) – floor(x) – rand()
  • 11. 11 C++ Programming Predefined Functions (Continued) • Predefined functions are used in a program as if they are single variables. • When a function is used, the compiler uses to the value that the function produces and returns. • A function value can be printed, used in an assignment statement, or used as part of an expression.
  • 12. 12 C++ Programming Predefined Functions (Continued) • cout << cos(3.1); print the value of cos(3.1). • y = 5*cos(3.1)–7; multiply cos(3.1) by 5 and subtract 7 to, then assign the result to y. • You cannot extract / assign a value to a function. cin >> cos(3.1); is illegal. cos(3.1) = 5 * x + 2; is illegal.
  • 13. 13 C++ Programming Predefined Functions (Continued) • Predefined functions are organized into separate libraries. • To use a predefined function, the program must include the header file that contains the function’s specifications. • To use the predefined math functions sqrt(), pow(), … must have #include <cmath> • To use the I/O functions, must have #include <iostream> • Example of another header file that you have seen so far is ….
  • 14. 14 C++ Programming Predefined Functions (Continued) • The function rand() generates random one of the numbers 0, 1, 2, 3, 4, … • The function rand() %2 generates 0 or 1 • The function 1 + rand() %6 generates 1, 2, 3, 4, 5, 6 • The function m + rand() % (n-m+1) generates a random number in the interval [m, n] • To use rand() use the library #include<cstdlib> • To generate different random numbers use srand(time(0)) on a line by itself • To use time(0) use the library #include<ctime>
  • 15. 15 C++ Programming Write a program that reads the (x, y) coordinates of a point in the Cartesian coordinates, converts to polar coordinates (r,  ), and prints the polar coordinates. 𝑟 = 𝑥2 + 𝑦2, 𝜃 = 𝑡𝑎𝑛−1 𝑦 𝑥 Program: toPolar.cpp Program: toPolar.exe Program: CartesiantoPolar()
  • 16. 16 C++ Programming User-Defined Functions • User defined functions are like predefined functions but the programmer has to write them. • Example: – Find the max of two numbers.
  • 17. 17 C++ Programming #include <iostream> using namespace std; double larger(double x, double y); int main() { double num1, num2, maximum; cin >> num1 >> num2; maximum = larger(num1, num2); cout << "The maiximum is " << maximum << endl; return 0; } double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; }
  • 18. 18 C++ Programming #include <iostream> using namespace std; double larger(double x, double y); int main() { double num1, num2, largest; cin >> num1 >> num2; largest = larger(num1, num2); cout << "The largest is " << largest << endl; return 0; } double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; } Function header/heading Function body Function formal parameters Function actual parameters Function type Function prototype Function definition
  • 19. 19 C++ Programming User-Defined Functions (Continued) • The number of formal parameter must match the number of actual parameters • The data type of each actual parameter must match its corresponding formal parameter. • A function call in a program results in the execution of the body of the called function.
  • 20. 20 C++ Programming User-Defined Functions (Continued) • The function syntax: functionType functionName(formal parameters) { statements } • Some functions have no parameters, such as int main(). • Some functions return nothing, so the return value is void.
  • 21. 21 C++ Programming User-Defined Functions (Continued) • A C++ program is made out of a set of functions. • main() is just a user defined function. • Execution always begins at the first statement in the function main. • Other functions are executed only when they are called.
  • 22. 22 C++ Programming User-Defined Functions (Continued) • When a return statement executes – Function immediately terminates. – Control goes back to the caller. – The function call statement is replaced by the returned value. • When a return statement executes in the function main(), the program terminates.
  • 23. 23 C++ Programming User-Defined Functions (Continued) • A user-defined function can be placed before the function main. In that case the function prototype is not necessary. • A function that returns a value is called a value- returning functions and it must have a data type. • A function that does not return a value (i.e. does not have a return statement) is called a void function and it does not have a type (its type is void). void funtionName(formal parameters)
  • 24. 24 C++ Programming Write a program that reads a positive integer num, calls the function isPerfect() which checks, and prints whether num is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors. For example, 6 is a perfect number because 6 = 1 + 2 + 3, also 28 is a perfect number because 28 = 1 + 2 + 4 + 7 + 14. Program: isPerfect.cpp Program: isPerfect.exe Program: isPerfect()
  • 25. 25 C++ Programming Write a program that reads a positive integer num, calls the function isPrime() which checks, and prints whether num is a prime number or not. A prime number is a positive integer that is divisible by 1 and itself only. For example, 7, 11, 13, 17, … are prime numbers, while 15 = 3 * 5 is not a prime number. Program: isPrime.cpp Program: isPrime.exe Program: isPrime()
  • 26. 26 C++ Programming Write a program that reads a positive integer N, calls the function Fibonacci() which calculates, and prints the Nth Fibonacci number. Fibonacci numbers satisfy the following recurrence relation 𝑎0 = 1, 𝑎1 = 1, 𝑎𝑛+2 = 𝑎𝑛+1 + 𝑎𝑛, 𝑛 0 Each Fibonacci number is the sum of the two previous Fibonacci numbers. Program: Fibonacci.cpp Program: Fibonacci.exe Program: Fibonacci()
  • 27. 27 C++ Programming Write a program that reads two positive integers n and k, calls the function binomial() which calculates, and prints the binomial coefficient of n and k. Fibonacci numbers satisfy the following recurrence relation 𝐶𝑘 𝑛 = 𝑛 𝑘 = 𝑛! 𝑛 − 𝑘 ! 𝑘! Program: binomial.cpp Program: binomial.exe Program: binomial()
  • 28. 28 C++ Programming Write a program that prints a menu and based on the user choice, the program preforms a job. Program: menu.cpp Program: myLibrary.h Program: menu.exe Program: Menu