SlideShare une entreprise Scribd logo
1  sur  39
Computer Programming II
Functions in C++
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void SquareArea()
{
double Side;
cout << "nEnter the side of the square: ";
cin >> Side;
cout << "nSquare characteristics:";
cout << "nSide = " << Side;
cout << "nArea = " << Side * Side << endl;;
}
int main(void)
{
SquareArea();
system("PAUSE");
return 0;
}
Enter the side of the square: 5
Square characteristics:
Side = 5
Area = 25
Press any key to continue . . .
Function with no return value and no parameters
Standard Name Space
Function Heading
Function Body
Function Call
Output
Computer Programming II
Techniques of Returning a Value
void Functions: A function that does
not return a value is declared and defined
as void.
#include <iostream>
#include <cstdlib>
using namespace std;
void Hello(void)
{
cout << "------------------------n"
<< "| Hello |n"
<< "-------------------------n" ;
}
int main(void)
{
Hello();
system("PAUSE");
return 0;
}
----------------------
| Hello |
--------------------------
Press any key to continue . . .
Returning a Value: If you declare a function
that is returning anything (a function that is not void),
the compiler will need to know what value the function
returns. The return value must be the same type
declared. The value is set with the return keyword.
char Answer()
{
char a;
cout << “Quit (y=Yes/n=No)? ";
cin >> a;
return a;
}
double SquareArea (double Side)
{
return (Side * Side);
}
double SquareArea(double Side)
{
double Area;
Area = Side * Side;
return Area;
}
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
int GetMajor(void)
{
int Choice;
cout << "n1 - Business Administration";
cout << "n2 - History";
cout << "n3 - Geography";
cout << "n4 - Education";
cout << "n5 - Computer Sciences";
cout << "nYour Choice: ";
cin >> Choice;
return Choice;
}
int main(void)
{
int Major;
cout << "Welcome to the student orientation program.";
cout << "Select your desired major:";
Major = GetMajor();
cout << "You select " << Major;
cout << "n";
system("PAUSE");
return 0;
}
Call GetMajor and
when done return the
results to the variable
Major
Return Value but no
Parameters
#include <iostream>
using namespace std;
double TotPrice(double ItemPrice, double TaxRate)
{
double Price;
Price = ItemPrice + (ItemPrice * TaxRate / 100);
return Price;
}
int main()
{
double ItemPrice, TaxRate;
cout << "Enter the price of the item: ";
cin >> ItemPrice;
cout << "Enter the tax rate: ";
cin >> TaxRate;
cout << "nThe final price is: "
<< TotPrice(ItemPrice, TaxRate);
cout << "nn";
return 0;
}
Enter the price of the item: 125.95
Enter the tax rate: 5.75
The final price is: 133.19
Computer Programming II
#include <iostream>
#include <string>
using namespace std;
string GetName(void)
{
string FirstName, LastName, FN;
cout << "Employee's First Name: ";
cin >> FirstName;
cout << "Employee's Last Name: ";
cin >> LastName;
FN = FirstName + " " + LastName;
return FN;
}
double GetHours(string FullName)
{
double Mon, Tue, Wed, Thu, Fri, TotalHours;
cout << endl << FullName << "'s Weekly Hoursn";
cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;
cout << "Wednesday: "; cin >> Wed;
cout << "Thursday: "; cin >> Thu;
cout << "Friday: "; cin >> Fri;
TotalHours = Mon + Tue + Wed + Thu + Fri;
return TotalHours;
}
int main(void)
{
string FullName;
double Hours;
FullName = GetName();
Hours = GetHours(FullName);
cout << "nEmployee's Name: "
<< FullName;
cout << "nWeekly Hours: "
<< Hours << " hoursnn";
system("PAUSE");
return 0;
}
Employee's First Name: sharaf
Employee's Last Name: sami
sharaf sami's Weekly Hours
Monday: 2
Tuesday: 3
Wednesday: 4
Thursday: 5
Friday: 6
Employee's Name: sharaf sami
Weekly Hours: 20 hours
Press any key to continue . . .
RUN
Computer Programming II
References in Functions
• Recall that the two primary motivations
for using references are related to their
use in functions:
– References are cleaner, and less error-
prone than pointers, especially when used
in functions
– Using references instead of pointers in
function prototypes will make their use
transparent to the calling program
Computer Programming II
Pass-By-Reference
• As an example, consider a function for
swapping the values contained in two integer
variables:
void swap (int* x, int* y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void swap (int& x, int& y)
{
int temp;
temp = x;
x = y;
y = temp;
}
Using Pointers Using References
Computer Programming II
Pass-By-Reference
• However, the simplicity of references is realized not
only in a function’s implementation, but also in its use:
Using Pointers Using References
int var1 = 10;
int var2 = 20;
swap (&var1, &var2);
int var1 = 10;
int var2 = 20;
swap (var1, var2);
• The use of references is transparent to the user!
Computer Programming II
Pass-By-Reference
• A nice side effect of the requirement that references
be initialized is that it removes the need to check for
null values in function calls
void myFunction(int* x) {…} // Must check that x != null
void myFunction(int& x) {…} // x cannot be null
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int &x, int &y);
int main()
{
int x=6, y=9;
cout << "Before the swap:n";
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
swap(x, y);
cout << "nAfter the swap:n";
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
system("PAUSE");
return 0;
}
void swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
Before the swap:
X: 6
Y: 9
After the swap:
X: 9
Y: 6
Press any key to continue . . .
Computer Programming II
#include <iostream>
#include <string>
using namespace std;
void change(int& a)
{
a = 33;
cout << "n2:" << a ;
}
void main()
{
int x = 100;
cout << "n1:" << x ;
change(x);
cout << "n3:" << x ;
}
1:100
2:33
3:33
#include <iostream>
#include <string>
using namespace std;
void change(int* a)
{
*a = 33;
cout << "n2:" << *a ;
}
void main()
{
int x = 100;
cout << "n1:" << x ;
change(&x);
cout << "n3:" << x ;
}
Using Reference Using Pointer
Computer Programming II
Pass-By-Const-Reference
• One advantage of pass-by-value is that it prevents a
function from altering the original arguments (since it
operates on copies of those arguments)
• However, we have already pointed out that creating a
copy of a large object can be very time-consuming
• C++ allows us to get the best of both worlds, by using
pass-by-const-reference
int myFunction(const int& x);
Computer Programming II
Pass-By-Const-Reference
• Using pass-by-const-reference provides both
the speed advantage of pass-by-reference and
the safety of pass-by-value
• Of course, this is not something that a user can
affect, so it is up to you to see if a function you
will be using has pass-by-const-reference
• Instead, this is really away that you, as a
programmer, can be sure that you don’t
inadvertently alter input parameters and
advertise that fact to users
Computer Programming II
#include <iostream.h>
#include <stdlib.h>
using namespace std;
int main()
{
double price, PriceAfterDiscount;
double computeDiscountedPrice (const double &price);
cout << "enter the price of the item";
cin >> price;
PriceAfterDiscount = computeDiscountedPrice(price);
cout << "the original price is $" << price << endl;
cout << "The final price after discount is $"
<< PriceAfterDiscount << endl;
system("PAUSE");
return 0;
}
double computeDiscountedPrice (const double &price)
{
double newPrice;
if (price > 100.0)
newPrice = price * .80;
else
newPrice = price * .90;
return newPrice;
}
enter the price of the item180
the original price is $180
The final price after discount is $144
Press any key to continue . . .
Computer Programming II
Returning References
• As with other data types, we can return a
reference from a function
int& myFunction() {…}
• When choosing to return a reference, it is
imperative to remember the C++ scope rules
• The object to which the reference refers to had
better exist after the function exits
Computer Programming II
Returning References
• There are two primary ways that references are safely
returned
• Return a reference to an object that was passed into
the function
int& pickANumber(int& a, int& b, int& c);
• Return a reference to an object that was dynamically
allocated within the function using new
• An interesting side effect of returning references is
that we can use the assignment operator with
functions:
int& myFunction() {…}
myFunction() = 5; // This is a valid statement!
Computer Programming II
#include <iostream.h>
#include <stdlib.h>
const int SIZE = 6;
int &put_val(int a[], int n)
{
if (n >= SIZE || n < 0)
{
cout << " Out side of boundaries";
exit(1);
}
return a[n];
}
int main()
{
int Arr[SIZE];
for (int i=0;i<SIZE;i++)
put_val(Arr,i) = i*2;
for (int j=0;j<SIZE;j++)
cout << "Arr["<<j<<"]="<<Arr[j] <<endl;
system("PAUSE");
return 0;
}
Function call is on the left
Arr[0]=0
Arr[1]=2
Arr[2]=4
Arr[3]=6
Arr[4]=8
Arr[5]=10
Press any key to continue . . .
Computer Programming II
Inline Functions
• The use of macros in C allows short
“functions” to be called without the normal
overhead associated with function calls
• There are several characteristics of macros
that makes their use unsuitable for C++
• Thus, C++ introduced the notion of inline
functions to allow users to avoid the overhead
of function calls
• With inline functions, the compiler controls the
process (as opposed to the preprocessor, as
was the case in C)
Computer Programming II
Inline Functions
• How function calls work
– Recall that the result of compiling a computer
program is a set of machine instructions (an
executable program)
– When the program is run, the OS loads the
instructions into memory (associating each
instruction with a memory address) and then
executes the instructions in order
– When a function call is encountered, the program
“jumps” to the address of the function and then
“jumps” back when the function has completed
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
inline int leap(int year);
int main()
{
int year;
cout << "Enter a year: ";
cin >> year;
if (leap(year))
cout << "The year " << year << " is a leap year" << endl;
else
cout << "The year " << year << " is not a leap year" << endl;
system("PAUSE");
return 0;
}
inline int leap(int year)
{
if (((year % 4) == 0) && (((year % 100) != 0) || ((year%400) == 0)))
return 1;
return 0;
}
Enter a year: 1999
The year 1999 is not a leap year
Press any key to continue . . .
Enter a year: 2000
The year 2000 is a leap year
Press any key to continue . . .
Computer Programming II
Inline Functions
• How functions work
– Each time the program “jumps” to execute a
function, there is associated overhead:
• “Loading” the function:
– The instruction immediately following the function call is
stored
– The function arguments are copied to a reserved region of
the stack
– Load the instruction referenced by the function call
• Terminating the function call:
– (Possibly) store a return value in a register
– Load the return instruction stored when the function was first
called
Computer Programming II
Inline Functions
• With inline functions, the compiler
replaces each instance of the function
call with the corresponding code
Computer Programming II
• The following example shows this insertion:
int main()
{
…
myFunction(2);
…
myFunction(5);
…
}
void myFunction(int n)
{
for (int i = 0; i < n; i++)
{
cout << i << “ “;
}
cout << “n”;
}
int main()
{
{ int n = 2;
for (int i = 0; i < n; i++)
{ cout << i << “ “; }
cout << “n”;
}
…..
{ int n = 5;
for (int i = 0; i < n; i++)
{ cout << i << “ “; }
cout << “n”;
}
}
Computer Programming II
Inline Functions
• The obvious overhead associated with
“jumping” to execute and return from a
function call is avoided
• However, there can be a significant memory
penalty for using inline functions
– Each time the compiler encounters an inline
function call, that call is replaced with the function
code
– Thus, if the inline function is called 20 times, 20
copies of it will be inserted into the program code
Computer Programming II
Inline Functions
• To define an inline function, insert the keyword inline
before the function definition
inline double square (double x) { return x * x; }
• Generally, inline function definitions should be placed
in a header file (for cleanliness and readability)
• When using inline functions, the function definition (or
the include statement if it’s in a header file) must be
placed before the first invocation of the function
Computer Programming II
Inline Functions
• Some notes on inline functions:
– You cannot inline recursive functions
– The keyword inline is only a suggestion to the
compiler, and may be ignore under certain
conditions, most notably if the function is
particularly large or complicated (such as functions
with frequent loops)
– Some functions that are not labeled with the inline
keyword may be inlined by the compiler
Computer Programming II
Inline Functions
• In general, using inline functions improves
program efficiency if:
– The function is small (so there is a measurable
savings realized by eliminating the function calling
overhead)
– The function is called often, but only occurs in a
small number of places in the program
• In other words, we want to realize these savings without
the memory cost associated with replicating the function
definition in many places
• An example would be a simple function that is called many
times in a loop
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap_int (int &a, int &b);
void swap_float (float &a, float &b);
void swap_char (char &a, char &b);
int main()
{
int i1 = 3, i2 = 5;
float f1 = 3.14159f, f2 = 1.23f;
char c1='A', c2='B';
cout << "Integers before swap:" << endl;
cout << i1 << ", " << i2 << endl;
swap_int(i1, i2);
cout << "Integers after swap:" << endl;
cout << i1 << ", " << i2 << endl;
cout << "Floating points before swap:" << endl;
cout << f1 << ", " << f2 << endl;
swap_float(f1, f2);
cout << "Floating points after swap:" << endl;
cout << f1 << ", " << f2 << endl;
cout << "Characters before swap:" << endl;
cout << c1 << ", " << c2 << endl;
swap_char(c1, c2);
cout << "characters after swap:" << endl;
cout << c1 << ", " << c2 << endl;
system("PAUSE");
return 0;
}
void swap_int(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void swap_float(float &a, float &b)
{
float temp = a;
a = b;
b = temp;
}
void swap_char(char &a, char &b)
{
char temp = a;
a = b;
b = temp;
}
Integers before swap:
3, 5
Integers after swap:
5, 3
Floating points before swap:
3.14159, 1.23
Floating points after swap:
1.23, 3.14159
Characters before swap:
A, B
characters after swap:
B, A
Press any key to continue . .
.
Computer Programming II
Function Overloading
• Function overloading (aka function polymorphism)
allows functions in C++ to share the same name
• For example, imagine that we have a sorting algorithm
that we wish to use to implement functions for several
types, such as int and char
• Traditionally, we would have to use different names for
these functions
void mySortInt(int array[ ]) {…}
void mySortChar(char array[ ]) {…}
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
void swap (int &a, int &b);
void swap (float &a, float &b);
void swap (char &a, char &b);
int main()
{
int i1 = 3, i2 = 5;
float f1 = 3.14159f, f2 = 1.23f;
char c1='A', c2='B';
cout << "Integers before swap:" << endl;
cout << i1 << ", " << i2 << endl;
swap(i1, i2);
cout << "Integers after swap:" << endl;
cout << i1 << ", " << i2 << endl;
cout << "Floating points before swap:" << endl;
cout << f1 << ", " << f2 << endl;
swap(f1, f2);
cout << "Floating points after swap:" << endl;
cout << f1 << ", " << f2 << endl;
cout << "Characters before swap:" << endl;
cout << c1 << ", " << c2 << endl;
swap(c1, c2);
cout << "characters after swap:" << endl;
cout << c1 << ", " << c2 << endl;
system("PAUSE");
return 0;
}
void swap (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void swap (float &a, float &b)
{
float temp = a;
a = b;
b = temp;
}
void swap (char &a, char &b)
{
char temp = a;
a = b;
b = temp;
}
Integers before swap:
3, 5
Integers after swap:
5, 3
Floating points before swap:
3.14159, 1.23
Floating points after swap:
1.23, 3.14159
Characters before swap:
A, B
characters after swap:
B, A
Press any key to continue . . .
Computer Programming II
Function Overloading
• C++ allows us to reuse function names,
provided that certain requirements are
met
void mySort(int array[]) {…}
void mySort(char array[]) {…}
• Overloaded functions are distinguished
by their argument list
void myFunction(int a) {…}
void myFunction(char a) {…}
void myFunction(int x) {…} // Not permitted
void myFunction(int x, int y) {…}
Computer Programming II
Function Overloading
• Note that the return type of a function is not taken into account
when determining valid function overloading
void myFunction(int a) {…}
int myFunction(int a) {…} // Not permitted
• There are several reasons for this, including:
• If return type is the only distinguishing aspect, how would
we determine which function to use when return type is
ignored?
myFunction(13); // Which one to use?
• If both return type and argument lists differ, determining
how to resolve overloaded functions is not straight-
forward
Computer Programming II
Operator Overloading
• Operators, such as +, -, && and ++, can be
thought of as
• another type of function in C++
– As such, they can also be overloaded (and, in fact,
already are in many cases)
• For example, there is no difference in the syntax when you
add two integers vs. when you add two floating point
numbers
– We will discuss operator overloading in more detail
after we have introduced classes
Computer Programming II
Default Arguments
• C++ allows you to define default arguments for
parameters in your function prototype
void myFunction(int x = 5); // Default value of 5 for x
• The default value is used if an actual argument
is not provided for a function call
myFunction(37); // Called with argument 37
myFunction(); // Called with default argument 5
Computer Programming II
Default Arguments
• Default arguments must be added from right to
left in a function prototype
– Examples of valid default arguments:
void myFunction(int x, int y = 5, int z = 10);
void myFunction(int x = 2, int y = 5, int z = 10);
• Examples of invalid default arguments:
void myFunction(int x, int y = 5, int z);
void myFunction(int x = 2, int y = 5, int z);
Computer Programming II
Default Arguments
• Similarly, default arguments must be used
from right to left when the function is called
void myFunction(int x = 2, int y = 5, int z = 10);
• Examples of valid calls:
myFunction(); // Uses all default arguments
myFunction(5); // Uses defaults for y(5) and z(10)
myFunction(5, 3); // Uses default for z(10)
myFunction(5, 3, 7); // Uses no default arguments
• You cannot “skip over” default arguments:
myFunction(5 , , 7); // Invalid – this will not use the
// default argument for y(5)
Computer Programming II
Default Arguments
• Using default values can reduce the number of
overloaded functions
– Consider a function which calculates your travel
time based on a distance and average speed,
which we want to default to 65 mph
float getTime(int distance); // Default speed of 65 mph
float getTime(int distance, int speed);
• Clearly, we can rewrite this using default
arguments
float getTime(int distance, int speed = 65);
Computer Programming II
Default Arguments
• Generally, default arguments should only be
used when there is an obvious (and frequently
used) default value
– Oftentimes, the use of a default value will not be
the only thing that differentiates the
implementations of overloaded functions
– Avoiding using a default argument as a “flag” to be
fed to conditional statements
Computer Programming II
#include <iostream>
#include <cstdlib>
using namespace std;
double test (double a, double b = 7)
{
return a - b;
}
int main ()
{
cout << test (14, 5) << endl;
cout << test (14) << endl;
system("PAUSE");
return 0;
}
9
7
Press any key to continue . . .

Contenu connexe

Similaire à Lecture2.ppt

Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 

Similaire à Lecture2.ppt (20)

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 

Dernier

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Dernier (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Lecture2.ppt

  • 2. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; void SquareArea() { double Side; cout << "nEnter the side of the square: "; cin >> Side; cout << "nSquare characteristics:"; cout << "nSide = " << Side; cout << "nArea = " << Side * Side << endl;; } int main(void) { SquareArea(); system("PAUSE"); return 0; } Enter the side of the square: 5 Square characteristics: Side = 5 Area = 25 Press any key to continue . . . Function with no return value and no parameters Standard Name Space Function Heading Function Body Function Call Output
  • 3. Computer Programming II Techniques of Returning a Value void Functions: A function that does not return a value is declared and defined as void. #include <iostream> #include <cstdlib> using namespace std; void Hello(void) { cout << "------------------------n" << "| Hello |n" << "-------------------------n" ; } int main(void) { Hello(); system("PAUSE"); return 0; } ---------------------- | Hello | -------------------------- Press any key to continue . . . Returning a Value: If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the function returns. The return value must be the same type declared. The value is set with the return keyword. char Answer() { char a; cout << “Quit (y=Yes/n=No)? "; cin >> a; return a; } double SquareArea (double Side) { return (Side * Side); } double SquareArea(double Side) { double Area; Area = Side * Side; return Area; }
  • 4. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; int GetMajor(void) { int Choice; cout << "n1 - Business Administration"; cout << "n2 - History"; cout << "n3 - Geography"; cout << "n4 - Education"; cout << "n5 - Computer Sciences"; cout << "nYour Choice: "; cin >> Choice; return Choice; } int main(void) { int Major; cout << "Welcome to the student orientation program."; cout << "Select your desired major:"; Major = GetMajor(); cout << "You select " << Major; cout << "n"; system("PAUSE"); return 0; } Call GetMajor and when done return the results to the variable Major Return Value but no Parameters #include <iostream> using namespace std; double TotPrice(double ItemPrice, double TaxRate) { double Price; Price = ItemPrice + (ItemPrice * TaxRate / 100); return Price; } int main() { double ItemPrice, TaxRate; cout << "Enter the price of the item: "; cin >> ItemPrice; cout << "Enter the tax rate: "; cin >> TaxRate; cout << "nThe final price is: " << TotPrice(ItemPrice, TaxRate); cout << "nn"; return 0; } Enter the price of the item: 125.95 Enter the tax rate: 5.75 The final price is: 133.19
  • 5. Computer Programming II #include <iostream> #include <string> using namespace std; string GetName(void) { string FirstName, LastName, FN; cout << "Employee's First Name: "; cin >> FirstName; cout << "Employee's Last Name: "; cin >> LastName; FN = FirstName + " " + LastName; return FN; } double GetHours(string FullName) { double Mon, Tue, Wed, Thu, Fri, TotalHours; cout << endl << FullName << "'s Weekly Hoursn"; cout << "Monday: "; cin >> Mon; cout << "Tuesday: "; cin >> Tue; cout << "Wednesday: "; cin >> Wed; cout << "Thursday: "; cin >> Thu; cout << "Friday: "; cin >> Fri; TotalHours = Mon + Tue + Wed + Thu + Fri; return TotalHours; } int main(void) { string FullName; double Hours; FullName = GetName(); Hours = GetHours(FullName); cout << "nEmployee's Name: " << FullName; cout << "nWeekly Hours: " << Hours << " hoursnn"; system("PAUSE"); return 0; } Employee's First Name: sharaf Employee's Last Name: sami sharaf sami's Weekly Hours Monday: 2 Tuesday: 3 Wednesday: 4 Thursday: 5 Friday: 6 Employee's Name: sharaf sami Weekly Hours: 20 hours Press any key to continue . . . RUN
  • 6. Computer Programming II References in Functions • Recall that the two primary motivations for using references are related to their use in functions: – References are cleaner, and less error- prone than pointers, especially when used in functions – Using references instead of pointers in function prototypes will make their use transparent to the calling program
  • 7. Computer Programming II Pass-By-Reference • As an example, consider a function for swapping the values contained in two integer variables: void swap (int* x, int* y) { int temp; temp = *x; *x = *y; *y = temp; } void swap (int& x, int& y) { int temp; temp = x; x = y; y = temp; } Using Pointers Using References
  • 8. Computer Programming II Pass-By-Reference • However, the simplicity of references is realized not only in a function’s implementation, but also in its use: Using Pointers Using References int var1 = 10; int var2 = 20; swap (&var1, &var2); int var1 = 10; int var2 = 20; swap (var1, var2); • The use of references is transparent to the user!
  • 9. Computer Programming II Pass-By-Reference • A nice side effect of the requirement that references be initialized is that it removes the need to check for null values in function calls void myFunction(int* x) {…} // Must check that x != null void myFunction(int& x) {…} // x cannot be null
  • 10. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; void swap(int &x, int &y); int main() { int x=6, y=9; cout << "Before the swap:n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; swap(x, y); cout << "nAfter the swap:n"; cout << "X: " << x << endl; cout << "Y: " << y << endl; system("PAUSE"); return 0; } void swap(int &x, int &y) { int temp = x; x = y; y = temp; } Before the swap: X: 6 Y: 9 After the swap: X: 9 Y: 6 Press any key to continue . . .
  • 11. Computer Programming II #include <iostream> #include <string> using namespace std; void change(int& a) { a = 33; cout << "n2:" << a ; } void main() { int x = 100; cout << "n1:" << x ; change(x); cout << "n3:" << x ; } 1:100 2:33 3:33 #include <iostream> #include <string> using namespace std; void change(int* a) { *a = 33; cout << "n2:" << *a ; } void main() { int x = 100; cout << "n1:" << x ; change(&x); cout << "n3:" << x ; } Using Reference Using Pointer
  • 12. Computer Programming II Pass-By-Const-Reference • One advantage of pass-by-value is that it prevents a function from altering the original arguments (since it operates on copies of those arguments) • However, we have already pointed out that creating a copy of a large object can be very time-consuming • C++ allows us to get the best of both worlds, by using pass-by-const-reference int myFunction(const int& x);
  • 13. Computer Programming II Pass-By-Const-Reference • Using pass-by-const-reference provides both the speed advantage of pass-by-reference and the safety of pass-by-value • Of course, this is not something that a user can affect, so it is up to you to see if a function you will be using has pass-by-const-reference • Instead, this is really away that you, as a programmer, can be sure that you don’t inadvertently alter input parameters and advertise that fact to users
  • 14. Computer Programming II #include <iostream.h> #include <stdlib.h> using namespace std; int main() { double price, PriceAfterDiscount; double computeDiscountedPrice (const double &price); cout << "enter the price of the item"; cin >> price; PriceAfterDiscount = computeDiscountedPrice(price); cout << "the original price is $" << price << endl; cout << "The final price after discount is $" << PriceAfterDiscount << endl; system("PAUSE"); return 0; } double computeDiscountedPrice (const double &price) { double newPrice; if (price > 100.0) newPrice = price * .80; else newPrice = price * .90; return newPrice; } enter the price of the item180 the original price is $180 The final price after discount is $144 Press any key to continue . . .
  • 15. Computer Programming II Returning References • As with other data types, we can return a reference from a function int& myFunction() {…} • When choosing to return a reference, it is imperative to remember the C++ scope rules • The object to which the reference refers to had better exist after the function exits
  • 16. Computer Programming II Returning References • There are two primary ways that references are safely returned • Return a reference to an object that was passed into the function int& pickANumber(int& a, int& b, int& c); • Return a reference to an object that was dynamically allocated within the function using new • An interesting side effect of returning references is that we can use the assignment operator with functions: int& myFunction() {…} myFunction() = 5; // This is a valid statement!
  • 17. Computer Programming II #include <iostream.h> #include <stdlib.h> const int SIZE = 6; int &put_val(int a[], int n) { if (n >= SIZE || n < 0) { cout << " Out side of boundaries"; exit(1); } return a[n]; } int main() { int Arr[SIZE]; for (int i=0;i<SIZE;i++) put_val(Arr,i) = i*2; for (int j=0;j<SIZE;j++) cout << "Arr["<<j<<"]="<<Arr[j] <<endl; system("PAUSE"); return 0; } Function call is on the left Arr[0]=0 Arr[1]=2 Arr[2]=4 Arr[3]=6 Arr[4]=8 Arr[5]=10 Press any key to continue . . .
  • 18. Computer Programming II Inline Functions • The use of macros in C allows short “functions” to be called without the normal overhead associated with function calls • There are several characteristics of macros that makes their use unsuitable for C++ • Thus, C++ introduced the notion of inline functions to allow users to avoid the overhead of function calls • With inline functions, the compiler controls the process (as opposed to the preprocessor, as was the case in C)
  • 19. Computer Programming II Inline Functions • How function calls work – Recall that the result of compiling a computer program is a set of machine instructions (an executable program) – When the program is run, the OS loads the instructions into memory (associating each instruction with a memory address) and then executes the instructions in order – When a function call is encountered, the program “jumps” to the address of the function and then “jumps” back when the function has completed
  • 20. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; inline int leap(int year); int main() { int year; cout << "Enter a year: "; cin >> year; if (leap(year)) cout << "The year " << year << " is a leap year" << endl; else cout << "The year " << year << " is not a leap year" << endl; system("PAUSE"); return 0; } inline int leap(int year) { if (((year % 4) == 0) && (((year % 100) != 0) || ((year%400) == 0))) return 1; return 0; } Enter a year: 1999 The year 1999 is not a leap year Press any key to continue . . . Enter a year: 2000 The year 2000 is a leap year Press any key to continue . . .
  • 21. Computer Programming II Inline Functions • How functions work – Each time the program “jumps” to execute a function, there is associated overhead: • “Loading” the function: – The instruction immediately following the function call is stored – The function arguments are copied to a reserved region of the stack – Load the instruction referenced by the function call • Terminating the function call: – (Possibly) store a return value in a register – Load the return instruction stored when the function was first called
  • 22. Computer Programming II Inline Functions • With inline functions, the compiler replaces each instance of the function call with the corresponding code
  • 23. Computer Programming II • The following example shows this insertion: int main() { … myFunction(2); … myFunction(5); … } void myFunction(int n) { for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “n”; } int main() { { int n = 2; for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “n”; } ….. { int n = 5; for (int i = 0; i < n; i++) { cout << i << “ “; } cout << “n”; } }
  • 24. Computer Programming II Inline Functions • The obvious overhead associated with “jumping” to execute and return from a function call is avoided • However, there can be a significant memory penalty for using inline functions – Each time the compiler encounters an inline function call, that call is replaced with the function code – Thus, if the inline function is called 20 times, 20 copies of it will be inserted into the program code
  • 25. Computer Programming II Inline Functions • To define an inline function, insert the keyword inline before the function definition inline double square (double x) { return x * x; } • Generally, inline function definitions should be placed in a header file (for cleanliness and readability) • When using inline functions, the function definition (or the include statement if it’s in a header file) must be placed before the first invocation of the function
  • 26. Computer Programming II Inline Functions • Some notes on inline functions: – You cannot inline recursive functions – The keyword inline is only a suggestion to the compiler, and may be ignore under certain conditions, most notably if the function is particularly large or complicated (such as functions with frequent loops) – Some functions that are not labeled with the inline keyword may be inlined by the compiler
  • 27. Computer Programming II Inline Functions • In general, using inline functions improves program efficiency if: – The function is small (so there is a measurable savings realized by eliminating the function calling overhead) – The function is called often, but only occurs in a small number of places in the program • In other words, we want to realize these savings without the memory cost associated with replicating the function definition in many places • An example would be a simple function that is called many times in a loop
  • 28. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; void swap_int (int &a, int &b); void swap_float (float &a, float &b); void swap_char (char &a, char &b); int main() { int i1 = 3, i2 = 5; float f1 = 3.14159f, f2 = 1.23f; char c1='A', c2='B'; cout << "Integers before swap:" << endl; cout << i1 << ", " << i2 << endl; swap_int(i1, i2); cout << "Integers after swap:" << endl; cout << i1 << ", " << i2 << endl; cout << "Floating points before swap:" << endl; cout << f1 << ", " << f2 << endl; swap_float(f1, f2); cout << "Floating points after swap:" << endl; cout << f1 << ", " << f2 << endl; cout << "Characters before swap:" << endl; cout << c1 << ", " << c2 << endl; swap_char(c1, c2); cout << "characters after swap:" << endl; cout << c1 << ", " << c2 << endl; system("PAUSE"); return 0; } void swap_int(int &a, int &b) { int temp = a; a = b; b = temp; } void swap_float(float &a, float &b) { float temp = a; a = b; b = temp; } void swap_char(char &a, char &b) { char temp = a; a = b; b = temp; } Integers before swap: 3, 5 Integers after swap: 5, 3 Floating points before swap: 3.14159, 1.23 Floating points after swap: 1.23, 3.14159 Characters before swap: A, B characters after swap: B, A Press any key to continue . . .
  • 29. Computer Programming II Function Overloading • Function overloading (aka function polymorphism) allows functions in C++ to share the same name • For example, imagine that we have a sorting algorithm that we wish to use to implement functions for several types, such as int and char • Traditionally, we would have to use different names for these functions void mySortInt(int array[ ]) {…} void mySortChar(char array[ ]) {…}
  • 30. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; void swap (int &a, int &b); void swap (float &a, float &b); void swap (char &a, char &b); int main() { int i1 = 3, i2 = 5; float f1 = 3.14159f, f2 = 1.23f; char c1='A', c2='B'; cout << "Integers before swap:" << endl; cout << i1 << ", " << i2 << endl; swap(i1, i2); cout << "Integers after swap:" << endl; cout << i1 << ", " << i2 << endl; cout << "Floating points before swap:" << endl; cout << f1 << ", " << f2 << endl; swap(f1, f2); cout << "Floating points after swap:" << endl; cout << f1 << ", " << f2 << endl; cout << "Characters before swap:" << endl; cout << c1 << ", " << c2 << endl; swap(c1, c2); cout << "characters after swap:" << endl; cout << c1 << ", " << c2 << endl; system("PAUSE"); return 0; } void swap (int &a, int &b) { int temp = a; a = b; b = temp; } void swap (float &a, float &b) { float temp = a; a = b; b = temp; } void swap (char &a, char &b) { char temp = a; a = b; b = temp; } Integers before swap: 3, 5 Integers after swap: 5, 3 Floating points before swap: 3.14159, 1.23 Floating points after swap: 1.23, 3.14159 Characters before swap: A, B characters after swap: B, A Press any key to continue . . .
  • 31. Computer Programming II Function Overloading • C++ allows us to reuse function names, provided that certain requirements are met void mySort(int array[]) {…} void mySort(char array[]) {…} • Overloaded functions are distinguished by their argument list void myFunction(int a) {…} void myFunction(char a) {…} void myFunction(int x) {…} // Not permitted void myFunction(int x, int y) {…}
  • 32. Computer Programming II Function Overloading • Note that the return type of a function is not taken into account when determining valid function overloading void myFunction(int a) {…} int myFunction(int a) {…} // Not permitted • There are several reasons for this, including: • If return type is the only distinguishing aspect, how would we determine which function to use when return type is ignored? myFunction(13); // Which one to use? • If both return type and argument lists differ, determining how to resolve overloaded functions is not straight- forward
  • 33. Computer Programming II Operator Overloading • Operators, such as +, -, && and ++, can be thought of as • another type of function in C++ – As such, they can also be overloaded (and, in fact, already are in many cases) • For example, there is no difference in the syntax when you add two integers vs. when you add two floating point numbers – We will discuss operator overloading in more detail after we have introduced classes
  • 34. Computer Programming II Default Arguments • C++ allows you to define default arguments for parameters in your function prototype void myFunction(int x = 5); // Default value of 5 for x • The default value is used if an actual argument is not provided for a function call myFunction(37); // Called with argument 37 myFunction(); // Called with default argument 5
  • 35. Computer Programming II Default Arguments • Default arguments must be added from right to left in a function prototype – Examples of valid default arguments: void myFunction(int x, int y = 5, int z = 10); void myFunction(int x = 2, int y = 5, int z = 10); • Examples of invalid default arguments: void myFunction(int x, int y = 5, int z); void myFunction(int x = 2, int y = 5, int z);
  • 36. Computer Programming II Default Arguments • Similarly, default arguments must be used from right to left when the function is called void myFunction(int x = 2, int y = 5, int z = 10); • Examples of valid calls: myFunction(); // Uses all default arguments myFunction(5); // Uses defaults for y(5) and z(10) myFunction(5, 3); // Uses default for z(10) myFunction(5, 3, 7); // Uses no default arguments • You cannot “skip over” default arguments: myFunction(5 , , 7); // Invalid – this will not use the // default argument for y(5)
  • 37. Computer Programming II Default Arguments • Using default values can reduce the number of overloaded functions – Consider a function which calculates your travel time based on a distance and average speed, which we want to default to 65 mph float getTime(int distance); // Default speed of 65 mph float getTime(int distance, int speed); • Clearly, we can rewrite this using default arguments float getTime(int distance, int speed = 65);
  • 38. Computer Programming II Default Arguments • Generally, default arguments should only be used when there is an obvious (and frequently used) default value – Oftentimes, the use of a default value will not be the only thing that differentiates the implementations of overloaded functions – Avoiding using a default argument as a “flag” to be fed to conditional statements
  • 39. Computer Programming II #include <iostream> #include <cstdlib> using namespace std; double test (double a, double b = 7) { return a - b; } int main () { cout << test (14, 5) << endl; cout << test (14) << endl; system("PAUSE"); return 0; } 9 7 Press any key to continue . . .