Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

49
Programming in Programming in C++ C++ Lecture Notes 6 Lecture Notes 6 Void Functions Void Functions (Procedures) (Procedures) Andreas Savva Andreas Savva

Transcript of Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

Page 1: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

Programming inProgramming in C++C++

Lecture Notes 6Lecture Notes 6Void Functions Void Functions (Procedures)(Procedures)

Andreas SavvaAndreas Savva

Page 2: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

22

The manager of a The manager of a companycompany

Does he pay the bills?Does he pay the bills? Does he answer the Does he answer the

phone?phone? Does he clean the office?Does he clean the office?

Page 3: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

33

CLEAN THE OFFICEPAY THE BILLS

ANSWER THE PHONE

Division of LaborDivision of Labor

Page 4: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

44

Our programs until now Our programs until now ……

Display messagesDisplay messages

Read values for the variablesRead values for the variables

Calculate expressionsCalculate expressions

Display resultsDisplay results

Page 5: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

55

It would be good It would be good ……

A part to read input values,A part to read input values,

another to calculate results, another to calculate results, andand

another to display the resultsanother to display the results

Page 6: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

66

FunctionsFunctions(Subprograms)(Subprograms)

Self-contained routines that are Self-contained routines that are identified by a identified by a namename and have the and have the same structure as same structure as main()main()..

They are executed when they are They are executed when they are calledcalled (calling their (calling their namesnames).).

main()main() is also a function but a special is also a function but a special one.one.

Page 7: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

77

Building my houseBuilding my house

I will call:the architectthe builderbuilderthe ironmongerthe builderbuilderthe plumberthe electricianthe builderbuilderthe painterthe carpenterthe designer

Page 8: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

88

ProceduresProcedures(void Functions)(void Functions)

Functions return a value (see later).Functions return a value (see later). If a function is declared a If a function is declared a voidvoid it does it does

not return a value, and is called a not return a value, and is called a procedureprocedure..

voidvoid is a special data-type. is a special data-type.

void main(){ ………

}

int main(){ ……… return 0;}

Page 9: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

99

Reasons for usingReasons for using Sub-Sub-programsprograms

Decrease the size of the programDecrease the size of the program Program becomes more readableProgram becomes more readable Decrease of errorsDecrease of errors

Page 10: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1010

Top-Down DesignTop-Down Design#include <iostream>using namespace std;// Global declaration section ………

void One(){ ………}

float Two(float x){ ……… return ??;}

void main(){ ………}

Declaration sectionand

function definition

Mainprogram

Includelibraries

Page 11: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1111

Procedure structureProcedure structure

void <function name>(<Formal parameters>){

. . .. . .

}

Page 12: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1212

Example:Example: #include#include <iostream> <iostream> using namespace std;using namespace std;

voidvoid Builder() Builder() {{ cout << ” * ” << endl;cout << ” * ” << endl; cout << ” * * ” << endl;cout << ” * * ” << endl; cout << ” * * ” << endl;cout << ” * * ” << endl; cout << ”*******” << endl;cout << ”*******” << endl; cout << ”* *” << endl;cout << ”* *” << endl; cout << ”* *” << endl;cout << ”* *” << endl; cout << ”* *” << endl;cout << ”* *” << endl; cout << ”*******” << endl;cout << ”*******” << endl; cout << endl;cout << endl; }}

voidvoid Gardener()Gardener() {{ cout << ” * ” << endl;cout << ” * ” << endl; cout << ” *** ” << endl;cout << ” *** ” << endl; cout << ” ***** ” << endl;cout << ” ***** ” << endl; cout << ”*******” << endl;cout << ”*******” << endl; cout << ” * ” << endl;cout << ” * ” << endl; cout << ” * ” << endl;cout << ” * ” << endl; cout << ” * ” << endl;cout << ” * ” << endl; cout << endl;cout << endl; }} voidvoid main( main()) {{ Builder()Builder();; Builder()Builder();; Gardener()Gardener();; Gardener()Gardener();; }}

** * * * * * ** **************** ** ** ** ** ** ***************

** * * * * * ** **************** ** ** ** ** ** ***************

** ****** ************************ ** ** **

** ****** ************************ ** ** **

Executed Executed when we when we call call

themthem

Page 13: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1313

PrototypesPrototypes#include <iostream>using namespace std;// Global declaration sectionvoid one();float two(float x); ………

int main(){ ……… return 0;}

void one(){ ………}

float two(float x){ ……… return ??;}

PrototypePrototypess

Page 14: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1414

Exercise 1Exercise 1 Write the following proceduresWrite the following procedures::

LineLine – – to display 5to display 5 stars in one line, i.e.stars in one line, i.e.

********** ExEx – – to display an X of stars, i.e.to display an X of stars, i.e.

* ** ** ** **** ** ** ** *

Write the main program to display the Write the main program to display the following shape:following shape:

*********** ** ** ** **** ** ** ** ** ** ** ** **** ** ** ** ***********

Page 15: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1515

Exercise 2Exercise 2

Write a procedure called “Display”Write a procedure called “Display” that that will prompt the user to enter two integer will prompt the user to enter two integer numbers numbers nn andand mm, and will display all the , and will display all the numbers from numbers from nn until until mm. . i.ei.e..

If If nn = 4 = 4,, mm = 9 = 9 it will displayit will display: : 4 5 6 7 8 94 5 6 7 8 9

Also, write the main program to call the Also, write the main program to call the procedure “Display”procedure “Display”..

Draw the flowchart of the above program.Draw the flowchart of the above program.

Page 16: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1616

Exercise 3Exercise 3

Write a procedure called “Sum”Write a procedure called “Sum” that that will prompt the user to enter two will prompt the user to enter two integer numbers integer numbers nn andand mm, and will , and will display the sum of all the numbers display the sum of all the numbers from from nn until until mm. . i.ei.e..

IfIf n n = 2, = 2, mm = 6 = 6 it will displayit will display: : 2020

since since 2 + 3 + 4 + 5 + 6 = 202 + 3 + 4 + 5 + 6 = 20

Page 17: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

Programming inProgramming in C++C++

Lecture Notes 7Lecture Notes 7Value ParametersValue Parameters

Andreas SavvaAndreas Savva

Page 18: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1818

#include <iostream>using namespace std;

void Show (int a, int b, float c){ cout << a << ’ ’ << b << ’ ’ << c;}

void main(){ Show (5 , 2 , 6);}

Actual parametersActual parameters

Formal parametersFormal parameters

Parameters (Arguments)Parameters (Arguments) Formal parametersFormal parameters Actual parametersActual parameters

5 2 6

Page 19: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

1919

ExampleExample

void pets(int cats){ cout << ”I have ” << cats << ” kittens\n”;}

NameName Formal parameterFormal parameter

Functions are executed when we call themFunctions are executed when we call them::

• pets(6);pets(6);• pets(4+2*3);pets(4+2*3);

I have 6 kittensI have 10 kittens

Page 20: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2020

MemoryMemory

ExampleExample

#include <iostream>using namesapce std;

void Add (int x, int y){ int sum = x + y; cout << x << ” + ” << y << ” = ” << sum);}

void main() { Add(5, 2); Add(3*2, 16-2);}

OutputOutput

5 + 2 = 7

6 + 14 = 20

sumsumx yx y

Add

55 22 7766 1414 2020

Page 21: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2121

FlowchartFlowchart

#include <iostream>using namespace std;

void Add (int x, int y){ int sum = x + y; cout << x << ’ + ’ << y << ’ = ’ << sum;}

void main() { int n, m; cout << ”Enter two numbers: ”; cin >> n >> m; Add(n, m);}

Start

Add(n,m)

Read n,m

Finish

Main ProgramMain Program

Display sum

Entrance

sum = x + y

Exit

Add(x,y)Add(x,y)

Page 22: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2222

Exercise 1Exercise 1

Write a program to ask for the price of Write a program to ask for the price of a product and display the discount. The a product and display the discount. The discount which is 15% will be discount which is 15% will be calculated and displayed in the calculated and displayed in the procedure “Discount”, that will take procedure “Discount”, that will take the price as a value formal parameter.the price as a value formal parameter.

Draw the flowchart of the above Draw the flowchart of the above program.program.

Page 23: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2323

Exercise 2Exercise 2

Write a program that will ask the user Write a program that will ask the user to enter the base and height of a right-to enter the base and height of a right-angle triangle and will display its area. angle triangle and will display its area. The area will be calculated and The area will be calculated and displayed in the procedure “Area”, displayed in the procedure “Area”, that will take the base and height as that will take the base and height as value formal parameters.value formal parameters.

Area = (base x height) / 2Area = (base x height) / 2

Page 24: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2424

Exercise 3Exercise 3

Write a procedure called “Times” that Write a procedure called “Times” that will take an integer number will take an integer number nn and a and a character and it will display the character and it will display the character character nn times, i.e. times, i.e.

TimesTimes(5,’?’)(5,’?’) will displaywill display: : ??????????

TimesTimes(8,’Α’)(8,’Α’) will displaywill display: : ΑΑΑΑΑΑΑΑΑΑΑΑΑΑΑΑ

Also, write the program that will prompt Also, write the program that will prompt for the number and the character and for the number and the character and will call the procedure “Times”.will call the procedure “Times”.

Page 25: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2525

Exercise 4Exercise 4

Write a procedure called “Display”Write a procedure called “Display” that that will take two integer numbers will take two integer numbers nn andand mm, , and will display all the numbers from and will display all the numbers from nn until until mm. . i.ei.e..

DisplayDisplay((44,,99)) will display will display: : 4 5 6 7 8 94 5 6 7 8 9

Also, write the program that will ask the Also, write the program that will ask the user to enter the two numbers and call user to enter the two numbers and call the procedure “Display”the procedure “Display”..

Draw the flowchart of the above program.Draw the flowchart of the above program.

Page 26: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2626

Exercise 5Exercise 5

Write a procedure called “Even”Write a procedure called “Even” that that will take two integer numbers will take two integer numbers nn andand mm, , and will display all the even numbers and will display all the even numbers from from nn until until mm. . i.ei.e..

EvenEven((44,,1313)) will display will display: : 4 6 8 10 124 6 8 10 12

Also, write the program that will ask Also, write the program that will ask the user to enter the two numbers and the user to enter the two numbers and call the procedure “Even”call the procedure “Even”..

Page 27: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2727

Exercise 6Exercise 6

Write a procedure called “Line”Write a procedure called “Line” that will that will take a character take a character chch and an integer and an integer number number nn and will display and will display chch in line in line nn, , i.ei.e..

LineLine((’?’’?’,,55)) will display will display::

line 1line 1line 2line 2line 3line 3line 4line 4line 5line 5line 6line 6line 7line 7

??

Page 28: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2828

Exercise 7Exercise 7

Write a procedure called “Position”Write a procedure called “Position” that that will take a character will take a character chch and two and two integer numbers integer numbers nn and and mm and will and will display display chch in row in row nn, and column , and column mm, i.e, i.e..

PositionPosition((’A’’A’,,4,74,7)) will display will display::

123456789123456789112233445566

AA

Page 29: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

2929

Exercise 8Exercise 8

Write a procedure called “Sum”Write a procedure called “Sum” that that will take two integer numbers will take two integer numbers nn andand mm, , and will display the sum of all the and will display the sum of all the numbers from numbers from nn until until mm. . i.ei.e..

SumSum((22,,66)) will display will display: : 2020

since since 2 + 3 + 4 + 5 + 6 = 202 + 3 + 4 + 5 + 6 = 20

Page 30: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

Programming inProgramming in C++C++

Lecture Notes 8Lecture Notes 8Reference ParametersReference Parameters

Andreas SavvaAndreas Savva

Page 31: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3131

#include <iostream>using namespace std;

void First (int a, int b, float c){ . . .}

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

Formal parametersFormal parameters

Parameters (Arguments)Parameters (Arguments) FormalFormal ActualActual

Page 32: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3232

Formal parametersFormal parameters Value formal parametersValue formal parameters Reference (Variable) formal parametersReference (Variable) formal parameters

void Display (int x, int &y){ x = x + y; y = x + y;}

Display(3Display(3,, Num); Num);

ValueValue FormalFormal

parameterparameter

ReferenceReference formalformal

parameterparameter

Page 33: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3333

MemoryMemory

GlobalGlobal

x y zx y z

Display

x yx y

Example:Example:#include <iostream>using namespace std;

int x, y, z;

void Display (int x, int &&y){ x = x + y; y = x + y; z = z + 1; cout << x << ” ” << y << ” ” << z << ’\n’;}

void main() { x = 2; y = 5; z = 3; Display(y, x); cout << x << ” ” << y << ” ” << z; }

55 22

OutputOutput

7 9 4

9 5 4

77 99

22 55 3399 44

Page 34: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3434

MemoryMemory

GlobalGlobal

x y zx y z

Display

x yx y

THE CORRECT WAYTHE CORRECT WAY – – Same exampleSame example

#include <iostream>using namespace std;

int x, y, z;

void Display (int x, int &&y){ x = x + y; y = x + y; z = z + 1; cout << x << ” ” << y << ” ” << z << ’\n’;}

void main() { x = 2; y = 5; z = 3; Display(y, x); cout << x << ” ” << y << ” ” << z; }

55

OutputOutput

7 9 4

9 5 4

77

22 55 3399 44

The reference formal parameter is a The reference formal parameter is a pointer to the address in memory of the pointer to the address in memory of the actual parameter.actual parameter.

Page 35: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3535

MemoryMemory

NumNum

GlobalGlobal

Reference formal Reference formal parameter:parameter:

#include <iostream>using namespace std;

int Num;

void Display (int &&x, int &&y){ x = x + y; y = x + y;}

void main() { Num = 10; Display(Num, Num); cout << Num; }

OutputOutput

40

101020204040

Display

x yx y

This example will help you to understandThis example will help you to understand..

Page 36: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3636

MemoryMemory

NumNum

GlobalGlobal

Exercise:Exercise:

#include <iostream>using namespace std;

int Num;

void Display (int x, int &&y){ x = x + y; y = x + y;}

void main() { Num = 10; Display(Num, Num); cout << Num; }

OutputOutput

30

1010

x yx y

Display

3030

10102020

Page 37: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3737

MemoryMemory

NumNum

GlobalGlobal

Exercise:Exercise:

#include <iostream>using namespace std;

int Num;

void Display (int x, int y){ x = x + y; y = x + y;}

void main() { Num = 10; Display(Num, Num); cout << Num; }

OutputOutput

10

1010

x yx y

Display

1010303010102020

Page 38: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3838

Only in C++Only in C++

In C and C+In C and C+++

void add(int a, int b, int &c){ c = a + b;}

void main(){ int x=3, y=5, z; add(x, y, z); cout << z;}

void add(int a, int b, int *c){ *c = a + b;}

void main(){ int x=3, y=5, z; add(x, y, &z); cout << z;}

Passing Parameters by Passing Parameters by ReferenceReference

Page 39: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

3939

Sub-Sub-programsprograms

#include <iostream> using namespace std; const int PI = 3.14159; float x, y;

void one(int num) { int n, m; char c; ……… }

void two(float &x) { int z; char y; ……… }

void main() { int p, y; ……… }

VariablesVariables LocalLocal GlobalGlobal

OneTwomain

LocalLocal GlobalGlobal

num, n, m, c PI, x, yx, y, z PIp, y PI, x

Page 40: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4040

ExerciseExercise 11 Write a void function “Calculate”Write a void function “Calculate” that will that will

take two numberstake two numbers αα andand ββ and a character and a character chch, and it will return through a reference , and it will return through a reference formal parameter called “formal parameter called “resultresult” the ” the following which depends on the value of following which depends on the value of chch: :

chch resultresult’’+’+’ α + βα + β’’–’–’ α – β α – β ’’*’*’ α * βα * β’’/’/’ α / βα / βotherwiseotherwise 00

Page 41: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4141

Exercise 2Exercise 2

Write a procedure “Swap” that will Write a procedure “Swap” that will accept two integer numbers, swap accept two integer numbers, swap and and returnreturn their values. their values.

Page 42: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4242

Exercise 3Exercise 3 Write a procedure “Summation” that will Write a procedure “Summation” that will

take two integer numbers take two integer numbers nn and and mm and and return through a reference formal return through a reference formal parameter the parameter the sumsum of all the numbers from of all the numbers from nn until until mm. If . If nn > > mm then the then the sumsum should be should be zero.zero.

i.e.i.e. If If nn = 1 and = 1 and mm = 4 then = 4 then SumSum = 1 + 2 + 3 + 4 = 10 = 1 + 2 + 3 + 4 = 10 If If nn = 4 and = 4 and mm = 9 then = 9 then SumSum = 4 + 5 + 6 + 7 + 8 + 9 = 39 = 4 + 5 + 6 + 7 + 8 + 9 = 39 If If nn = 7 and = 7 and mm = 7 then = 7 then SumSum = 7 = 7 If If nn = 7 and = 7 and mm = 2 then = 2 then SumSum = 0 = 0

Page 43: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4343

Exercise 4Exercise 4

Write a procedure “Money” that will take a Write a procedure “Money” that will take a an amount in pounds (real number), and it an amount in pounds (real number), and it would return through two integer reference would return through two integer reference formal parameters the number of pounds formal parameters the number of pounds and the number of cents.and the number of cents.

i.e.i.e.if if amountamount = 36.78 = 36.78then then poundspounds = 36 = 36and and centscents = 78 = 78

Page 44: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4444

Exercise 5Exercise 5

Write a procedure “Euro” that will Write a procedure “Euro” that will accept an amount in Cyprus pounds accept an amount in Cyprus pounds and return the respective amount in and return the respective amount in EURO. The rate should also be passed EURO. The rate should also be passed to the procedure as a value formal to the procedure as a value formal parameter. parameter.

Page 45: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4545

Exercise 6Exercise 6

Given the names of four students and three Given the names of four students and three exam-marks for each one:exam-marks for each one:1.1. Write a procedure to take three marks, Write a procedure to take three marks,

calculate and return their average and calculate and return their average and the highest of the three.the highest of the three.

2.2. Write the main program to read the four Write the main program to read the four students names and marks and display a students names and marks and display a list with their names, their average mark, list with their names, their average mark, and the highest mark for each student.and the highest mark for each student.

Page 46: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4646

Default ParametersDefault Parameters#include <iostream>using namespace std;void print(int n = 1, int m = 10){ cout << n << ’\t’ << m;}

void main(){ print(6,8); print(); print(3);}

6 81 103 10

Page 47: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4747

Default Parameters are defined only Default Parameters are defined only ONCEONCE

#include <iostream>using namespace std;

void print(int n, int m = 10);

void main(){ print(6,8); print(3);}

void print(int n, int m){ cout << n << ’\t’ << m;}

#include <iostream>using namespace std;

void print(int n, int m);

void main(){ print(6,8); print(3);}

void print(int n, int m = 10){ cout << n << ’\t’ << m;}

ERROR HERE:print takes

two parameters

Right-to-LeftRight-to-Leftvoid print(int n = 10, int m); //ERROR

void print(int x = 1, int y = 2, int z = 3);. . .print(7,5); //CORRECTprint( , , 6); //ERROR

Page 48: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4848

Overloading FunctionsOverloading Functions

#include <iostream>using namespace std;

void display(int n) { cout << n << endl;}

void display(char c) { cout << c << endl;}

void display(int x, int y) { cout << x << ’\t’ << y << endl;}

void display(int n, float m){ cout << n << ’\t’ << m << endl;}

void main() { display(6); display(’?’); display(3,8); display(2,(float)4.2);}

6?3 82 4.2

A function can be defined more than ones but with different A function can be defined more than ones but with different numbernumber or/and or/and typetype of parameters. of parameters.

Page 49: Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

4949

More about FunctionsMore about Functions Functions can also be called as Functions can also be called as

procedures (the return value will be procedures (the return value will be lost).lost).

int max (int a, int b)int max (int a, int b){{ cout << a+b << endl;cout << a+b << endl; if (a>b) return a;if (a>b) return a; else return b;else return b;}}

int main()int main(){{ cout << max(5,9) << endl;cout << max(5,9) << endl; max(3,1); max(3,1); // Return value is lost// Return value is lost}} C++ will give a

warning (not an error): main() does not return a value