Top Banner
1 Programming Principles Programming Principles II II Lecture Notes 4 Lecture Notes 4 Functions (Returning Functions (Returning Values) Values) Andreas Savva
54

1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Jan 06, 2018

Download

Documents

Charles Bishop

3 Functions Function None or many inputparameters Exactly one return value
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

11

Programming Programming Principles IIPrinciples II

Lecture Notes 4Lecture Notes 4Functions (Returning Functions (Returning

Values)Values)

Andreas Savva

Page 2: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

22

Functions in Functions in MathematicsMathematics

f(x) = x2

Parameters

f(2) =f(-2) =f(4) =

f(x,y) = x2+y

4416

f(2,3) =f(-2,-3) =

71

f = 3

Page 3: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

33

FunctionsFunctions

FunctionFunctionNone or manyNone or many

inputinputparametersparameters

Exactly oneExactly onereturn valuereturn value

Page 4: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

44

Functions that we knowFunctions that we know

abs(-6)abs(-6) = 6= 6sqrt(16)sqrt(16) = 4= 4sin(3.14159/2)sin(3.14159/2) = 1= 1int(45.876)int(45.876) = 45= 45

absabsxx |x||x|

F(x) = |x|

Page 5: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

55

Function StructureFunction Structure<Data-type of return value> <Function Name>(<Formal parameters>){ . . . . . return <expression>;}

bool IsBigger (int a, int b){ return a > b;}

Page 6: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

66

ExampleExample

int MySqr (int x){ return x * x;}

NameName Formal parameterFormal parameterData type ofData type ofreturn valuereturn value

Return valueReturn value

Functions are executed when we call them:Functions are executed when we call them:cout << MySqr(6);cout << MySqr(6);y = 1 + MySqr(3-1);y = 1 + MySqr(3-1);n = 3 * MySqr(abs(sqrt(9)-5));n = 3 * MySqr(abs(sqrt(9)-5));

Page 7: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

77

Function - ExampleFunction - Example#include#include <iostream> <iostream>using namespace std;using namespace std;intint cube( cube(intint););int int main()main(){{ intint n, x; n, x; cout << ”Give a number: ”;cout << ”Give a number: ”; cin >> n;cin >> n; x = cube(n);x = cube(n); cout << ”The cube of ” << n << ” is ” << cout << ”The cube of ” << n << ” is ” <<

x;x; return 0;return 0;} } intint cube( cube(intint x) x){{ returnreturn x * x * x; x * x * x;}}

Page 8: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

88

#include <iostream>using namespace std;

char First (int a , int b; float c){ . . . return <expression>;}

void main() { int a = 1, b = 3, c = 7; . . . char ch = First (5 , c , a);} Actual Actual

parametersparameters

Formal parametersFormal parameters

Parameters (Arguments)Parameters (Arguments) FormalFormal ActualActual

Page 9: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

99

Function ExampleFunction Example#include <iostream>using namespace std;int max(int, int); // Function prototypeint num; // Global variablevoid main(){ cout << max(4,7); num = max(2*4-1, Sqrt(81)); cout << num; cout << max(max(4,5),8); cout << max(max(4,2),max(3,max(6,1)));}int max (int a, int b){ if (a > b) return a; else return b;}

Result Result 7986

Page 10: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1010

ReturnReturn returnreturn exits the function immediately and exits the function immediately and

returns a value.returns a value.int addone (int a){ return 1; cout << a + 1; a++; return a; cout << a;}

Statements below this line will never be

executed. Always return 1

int max(int a, int b){ if (a > b) return a; else return b;}

int max(int a, int b){ if (a > b) return a; return b;}

samesame

Page 11: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1111

Be CarefulBe Careful

int max(int a, int b){ int large;

if (a > b) large = a; else large = b;

return large;}

int max(int a, int b){ int large;

if (a > b) large = a; large = b;

return large;}

NOTNOTthethe

samesame

Page 12: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1212

Procedure Vs FunctionProcedure Vs Function#include <iostream>using namespace std;int num;void DisplayDisplay( ){ cout << ”I like college”;}int MySqrMySqr (int x){ return x * x;}void main( ) Display( )Display( ); cout << MySqrMySqr(3); num = 1 + 6 * MySqrMySqr(4);}

Does notDoes notreturnreturna valuea value

ReturnReturnssa a

valuevalue

Page 13: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1313

Returning a ClassReturning a Classclass Fraction {public: int numerator; int denominator;};

Fraction init(){ Fraction f; f.numerator = 5; f.denominator = 12; return f;}

int main(){ Fraction y; y = init(); cout << y.numerator << ’/’ << y.denominator; return 0;}

5/12

Page 14: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1414

Receiving and Returning Receiving and Returning ClassesClasses

class Fraction {public: int numerator; int denominator;};

Fraction multiply(Fraction a, Fraction b){ Fraction f; f.numerator = a.numerator * b.numerator; f.denominator = a.denominator * b.denominator; return f;}

int main(){ Fraction x = {2,3} , y = {5,7}, z; z = multiply(x, y); cout << z.numerator << ’/’ << z.denominator; return 0;}

10/21

Page 15: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1515

Constant Reference Constant Reference ParametersParameters

Value formal parameters copy in a new memory Value formal parameters copy in a new memory location the value of the actual parameter.location the value of the actual parameter.

When we have large structures it is better to use a When we have large structures it is better to use a reference formal parameter since copying could be reference formal parameter since copying could be time-consuming and we also waist additional time-consuming and we also waist additional memory.memory.

We can declare a reference formal parameter as a We can declare a reference formal parameter as a constant which will not allow as to change its value constant which will not allow as to change its value ((for safetyfor safety).).

void invalid(const int &x){ x = 5; // Syntax ERROR}

Page 16: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1616

Constant Reference Constant Reference ParametersParameters

class Fraction {public: int numerator; int denominator;};

Fraction multiply(const Fraction &a, const Fraction &b){ Fraction f; f.numerator = a.numerator * b.numerator; f.denominator = a.denominator * b.denominator; return f;}

int main(){ Fraction x = {2,3} , y = {5,7}, z; z = multiply(x, y); cout << z.numerator << ’/’ << z.denominator; return 0;}

10/21

Page 17: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1717

Returning PointersReturning Pointersint *result(int a, int b){ int *r = new int(a + b); return r;}

int main(){ int *z = result(5, 2); cout << *z; return 0;}

77

Page 18: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1818

Formal ParametersFormal Parametersvoid test(int a, int &b, int *c){ a = 12; b = 23; *c = 34;}

int main(){ int x = 2, y = 5, z = 7; test(x, y, &z); cout << x << endl << y << endl << z; return 0;}

2223233434

Page 19: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

1919

Pointer ReferencingPointer Referencingvoid test(int *&a){ a = new int(23);}

int main(){ int *p = new int(12); int *r = p; test(p); cout << *p << endl << *r; return 0;}

23231212

Page 20: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2020

main() is also a Functionmain() is also a Function

#include <cstdlib> // standard system definitions library#include <iostream>using namespace std;

int main(){ int x,y; cout << ”Please enter two numbers: ”; cin >> x >> y; int sum = x + y; cout << ”Their sum is ” << sum << endl; return EXIT_SUCCESS;}

Page 21: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2121

main() can also take main() can also take ParametersParameters

#include <iostream>using namespace std;

int main(int argc, char **argv){ if (argc > 1) if (strcmp(argv[1],”nicosia”)) cout << ”Not a valid password”; else cout << ”Logged in as administrator”; else cout << ”Regular user”; return 0;}

Page 22: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2222

The Function main()The Function main()#include <iostream>using namespace std;

int main(int argc, char **argv){ if (argc == 1) { cout << ”Enter n numbers to add\n”; exit(1); } int sum = 0; for (int i=1; i<argc; i++) sum += atoi(argv[i]); cout << ”Sum = ” << sum << endl; return 0;}

Page 23: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2323

ExerciseExercise 1 1 Write a program that will ask the Write a program that will ask the

price of a product and display the price of a product and display the discount. The discount should be discount. The discount should be returned by a function, called returned by a function, called “Discount”, that will take the price as “Discount”, that will take the price as a formal parameter and return the a formal parameter and return the discount which is 15%.discount which is 15%.

Page 24: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2424

ExerciseExercise 22 Write a program to ask the base and Write a program to ask the base and

height of a right-angle triangle and height of a right-angle triangle and display its area. The area should be display its area. The area should be calculated and returned by a function, calculated and returned by a function, called “Area”, that will take the base called “Area”, that will take the base and height as formal parametersand height as formal parameters..

Area = (Base x Height) / 2Area = (Base x Height) / 2

Page 25: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2525

ExerciseExercise 33 Write a function “Subtract” that will Write a function “Subtract” that will

take two real parameters and return take two real parameters and return their difference. Also write the their difference. Also write the program that will read the numbers, program that will read the numbers, call the function and display the call the function and display the resultresult. .

Page 26: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2626

ExerciseExercise 44 Write a functionWrite a function “Calculator”“Calculator” that will that will

take two numberstake two numbers aa andand bb and a and a character, and if the character is:character, and if the character is:

’’+’ +’ to returnto return aa + + bb’’–’–’ to returnto return aa – – bb ’’*’ *’ to return to return aa * * bb’’/’ /’ to return to return aa / / bb

Page 27: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2727

ExerciseExercise 55 Write a function “Sum”Write a function “Sum” that will take that will take

two two integer numbersinteger numbers nn andand mm and and return the sum of all the numbers from return the sum of all the numbers from nn toto mm..

i.e.i.e. Sum(1,4) = 1 + 2 + 3 + 4 = 10Sum(1,4) = 1 + 2 + 3 + 4 = 10 Sum(4,9) = 4 + 5 + 6 + 7 + 8 + 9 = 39Sum(4,9) = 4 + 5 + 6 + 7 + 8 + 9 = 39 Sum(7,7) = 7Sum(7,7) = 7 Sum(7,2) = 0Sum(7,2) = 0

Page 28: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2828

ExerciseExercise 66 Write a functionWrite a function “Month”“Month” that will that will

take the month-number and return take the month-number and return the month namethe month name..

i.ei.e.. Month(1) = “January”Month(1) = “January” Month(4) = “April”Month(4) = “April” Month(11) = “November”Month(11) = “November”

Page 29: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

2929

ExerciseExercise 77

Write a functionWrite a function “Teenager”“Teenager” that will that will take the age of a person and return take the age of a person and return truetrue if is a teenager and if is a teenager and falsefalse if not if not. . A teenager is someone who is A teenager is someone who is between between 12 12 and and 18 18 years old.years old.

Page 30: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3030

ExerciseExercise 88

Write a function “PI” that will return Write a function “PI” that will return the value ofthe value of ππ which iswhich is 3.14159. 3.14159.

Page 31: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3131

ExerciseExercise 9 9 Write a functionWrite a function “Decimal” that will return “Decimal” that will return

the decimal part of a numberthe decimal part of a number..

Example:Example: Given the numberGiven the number 13.46 13.46 the function will the function will

return the valuereturn the value 0.46. 0.46.

HintHint:: 13.46 - 13 = 0.4613.46 - 13 = 0.46

numnum int(num)int(num)

Page 32: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3232

ExerciseExercise 10 101.1. Write a function “Write a function “PowerPower” to calculate the power ” to calculate the power

of a given numberof a given number..i.ei.e..Power(2,3) = 2Power(2,3) = 233 = 8 = 8Power(4,2) = 4Power(4,2) = 422 = 16 = 16

2.2. Write a function “Write a function “EquationEquation” to calculate the ” to calculate the equation equation 3x3x339x9x55.. x is a value formal parameter. x is a value formal parameter.

3.3. Using the function “Using the function “EquationEquation” write a program ” write a program to calculate and display the equation to calculate and display the equation 336633

996655..

Page 33: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3333

What is the output of the following program?What is the output of the following program? Exercise 11Exercise 11#include <iostream>using namespace std;int StopAt(int i, int m, int n) { if (2*m-1 <= n) return i – 1; else return n – i;}void display(int n, char c) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= StopAt(i,i,n); j++) cout << ' '; cout << c; if (i*2-1 != n) { for (j = 1; j <= StopAt((2*i)%(n+1),n-i+1,n); j++) cout << ' '; cout << c; } cout << endl; }}void main() { display(5,'+'); display(7,'?'); display(6,'0');}

Page 34: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3434

ExerciseExercise 1212 Write a float function “harmonic”Write a float function “harmonic”

that will take an integer numbersthat will take an integer numbers nn and return the harmonic series of and return the harmonic series of nn which is given bywhich is given by

nnharmonic 1

31

211)(

Page 35: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3535

ExerciseExercise 1313 Write a float function “f”Write a float function “f” that will take that will take

an integer numbersan integer numbers nn and return the and return the following series:following series:

)1(1

431

321

211)(

nnnf

Page 36: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

3636

ExerciseExercise 1 144#include <iostream>using namespace std;void test(int *&a, int *&b){ int *c = a; a = b; b = c;}void main(){ int *p = new int(8); int *r = new int(5); test(p, r); cout << *p << endl << *r;}

What is the output of the following program?What is the output of the following program?

Page 37: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Function TemplatesFunction Templates

Special functions that can operate with Special functions that can operate with generic types.generic types. Their functionality can be adapted to more than one type Their functionality can be adapted to more than one type

or class without repeating code for each type.or class without repeating code for each type. In C++ this can be achieved using In C++ this can be achieved using template parameterstemplate parameters..

3737

Page 38: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Template ParametersTemplate Parameters A template parameter is a special kind of parameter A template parameter is a special kind of parameter

that can be used to pass a data-type as argument to that can be used to pass a data-type as argument to a function.a function.

The format for declaring function templates with The format for declaring function templates with type parameters is:type parameters is:

The keywords The keywords classclass and and typenametypename have exactly the have exactly the same meaning and behave exactly the same way.same meaning and behave exactly the same way.

3838

template <class template <class identifieridentifier> > function function declarationdeclaration;;template <typename template <typename identifieridentifier> > function function declarationdeclaration;;

Page 39: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Function TemplatesFunction Templates

The function The function GetMaxGetMax has has myTypemyType as its template as its template parameter. parameter. myTypemyType represents a parameter that has represents a parameter that has not yet been specified but can be used as if it is a not yet been specified but can be used as if it is a regular data-type.regular data-type.

Function CallFunction Call:: GetMaxGetMax<int><int>(4, 12);(4, 12); GetMaxGetMax<double><double>(2.56, 9.002);(2.56, 9.002);

3939

template <class myType>myType GetMax(myType a, myType b){ return (a>b?a:b);}

Page 40: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Function Templates – ExampleFunction Templates – Example

4040

#include <iostream>using namespace std;

template <class T>T GetMax(T a, T b){ T result; result = (a>b?a:b); return result;}

int main(){ double f = 5.87; cout << GetMax<int>(4,9) << endl; cout << GetMax<double>(f,3.14) << endl; cout << GetMax<char>(’A’,’Z’) << endl; return 0;}

Can also declare new objects of

type T

995.875.87ZZ

Page 41: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Without Specifying Template Without Specifying Template TypeType

4141

#include <iostream>using namespace std;template <class T>T GetMax(T a, T b){ return (a>b?a:b);}int main(){ int a=4, b=8; float x=5.87, y=2.146; cout << GetMax(a,b) << endl; cout << GetMax(x,y) << endl; return 0;}

885.875.87

Notice that the Notice that the GetMaxGetMax is called without explicitly specifying the is called without explicitly specifying the data-type. The compiler automatically determines the appropriate data-type. The compiler automatically determines the appropriate instantiation from the arguments passed to the function.instantiation from the arguments passed to the function.

Page 42: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Passing Different Data-TypesPassing Different Data-Types

4242

template <class T>T GetMax(T a, T b){ return (a>b?a:b);}

Error:Error:int a = 8;long b = 10;k = GetMax(a,b);

Page 43: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Multi-Template parametersMulti-Template parameters

4343

template <class T, class U>T GetMax(T a, U b){ return (a>b?a:b);}

Correct:Correct:int a = 8;long k, b = 10;k = GetMax<long,int>(b,a);

Correct:Correct:int a = 8;long k, b = 10;k = GetMax(b,a);

Page 44: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

NamespacesNamespaces

4444

namespace myGlobals{ int a, b = 6;}

namespace identifier{ entities}

Namespaces allow to group entities like classes, objects and Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be functions under a name. This way the global scope can be divided into “sub-scopes”, each one with its own name.divided into “sub-scopes”, each one with its own name.

FormatFormat ::

ExampleExample ::

Variables a and b are normal variables declared within a Variables a and b are normal variables declared within a namespace. They can be accessed using the namespace. They can be accessed using the scopescope operator operator ::::, i.e. , i.e.

myGlobals::amyGlobals::b

Page 45: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Namespaces – Example 1Namespaces – Example 1

4545

#include <iostream>using namespace std;

namespace myGlobals{ int a, b = 6;}

int main(){ myGlobals::a = 23; cout << myGlobals::a << endl; cout << myGlobals::b << endl; return 0;}

232366

Page 46: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Namespaces – Example 2Namespaces – Example 2

4646

#include <iostream>using namespace std;

namespace first { int var = 5;}

namespace second { double var = 3.14159;}

int main(){ cout << first::var << endl; cout << second::var << endl; return 0;}

553.141593.14159

Page 47: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

The Keyword “The Keyword “usingusing””

4747

#include <iostream>using namespace std;

namespace first { int x = 5, y = 12;}

namespace second { double x = 3.14159, y = 2.718;}

int main(){ using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0;}

552.7182.71812123.141593.14159

The keyword “using” is used to introduce a name from a The keyword “using” is used to introduce a name from a namespace into the current declarative region.namespace into the current declarative region.

Page 48: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

The Keywords “The Keywords “using using namespacenamespace””

4848

#include <iostream>using namespace std;

namespace first { int x = 5, y = 12;}

namespace second { double x = 3.14159, y = 2.718;}

int main(){ using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0;}

5512123.141593.141592.7182.718

The keyword “using” can also be used as a directive to The keyword “using” can also be used as a directive to introduce an entire namespace.introduce an entire namespace.

Page 49: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

The Keywords “The Keywords “using using namespacenamespace””

4949

#include <iostream>using namespace std;

namespace first { int x = 5;}

namespace second { double x = 3.14159;}

int main(){ using namespace first; using namespace second; cout << x << endl; return 0;}

Ambiguous

Identifier

#include <iostream>using namespace std;

namespace first { int x = 5;}

namespace second { double x = 3.14159;}

int main(){ using namespace first; using namespace second; cout << first::x << endl; return 0;}

Error:Error: Correct:Correct:

55

Page 50: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

The Keywords “The Keywords “using using namespacenamespace””

5050

#include <iostream>using namespace std;

namespace first { int x = 5;}

namespace second { double x = 3.14159;}

int main(){ { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0;}

Correct:Correct:

553.141593.14159

Page 51: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Namespace AliasNamespace Alias

5151

#include <iostream>using namespace std;

namespace myGlobals{ int a = 6;}

int main(){ namespace Num = myGlobals; Num::a = 199; cout << myGlobals::a << endl; return 0;}

199199

Alternative names for existing namespaces can be declared Alternative names for existing namespaces can be declared as:as:

namespace new_name = current_name;

Page 52: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

The “The “stdstd” ” NamespaceNamespace

5252

#include <iostream>namespace myPrint = std;

int main(){ myPrint::cout << ”Hello world” << myprint::endl; return 0;}

All the files in the C++ standard library declare all of its All the files in the C++ standard library declare all of its entities within the entities within the stdstd namespace. That is why the “ namespace. That is why the “using using namespace stdnamespace std” statement is generally included in all ” statement is generally included in all programs that use any entity defined in programs that use any entity defined in iostreamiostream..

#include <iostream>namespace myPrint = std;using namespace myPrint;

int main(){ cout << ”Hello world” << endl; return 0;}

Page 53: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Functions as parameters to Functions as parameters to FunctionsFunctions

PointersPointers to functions can also be passed as to functions can also be passed as parameters to another function.parameters to another function.

5353

#include <iostream>using namespace std;void myFunction(void (*f)(int), int); // Prototypevoid print(int); // Prototypeint main(){ myFunction(print, 5); return 0;}void myFunction(void (*f)(int), int n){ for (int i=1; i<=n; i++) (*f)(i);}void print(int x){ cout << x << endl;}

1122334455

Page 54: 1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Functions as parameters – Functions as parameters – ExampleExample

5454

#include <iostream>using namespace std;int MinMax(bool (*f)(int&, int&), int A[], int n){ int val = A[0]; for (int i=1; i<n; i++) if ((*f)(A[i],val)) val = A[i]; return val;}bool Min(int &x, int &y) { return x < y;}bool Max(int &x, int &y) { return x > y;}int main(){ int values[] = {4,7,5,2,9,3}; cout << ”Smallest = ” << MinMax(Min,values,6) << endl; cout << ”Biggest = ” << MinMax(Max,values,6) << endl; return 0;}

Smallest = 2Smallest = 2Biggest = 9Biggest = 9