programming principles ii lecture notes 3.1 void functions andreas savva

60
Programming Principles Programming Principles II II Lecture Notes 3.1 Lecture Notes 3.1 Void Functions Void Functions Andreas Savva Andreas Savva

Upload: claud-parks

Post on 19-Jan-2018

229 views

Category:

Documents


0 download

DESCRIPTION

3 Functions (Subprograms) Self-contained routines that are identified by a name and have the same structure as main(). Self-contained routines that are identified by a name and have the same structure as main(). They are executed when they are called (calling their names). They are executed when they are called (calling their names). main() is also a function but a special one. main() is also a function but a special one.

TRANSCRIPT

Page 1: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Programming Programming Principles IIPrinciples II

Lecture Notes 3.1Lecture Notes 3.1Void FunctionsVoid Functions

Andreas SavvaAndreas Savva

Page 2: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

22

Sub-programs – Division of Sub-programs – Division of LaborLabor

The manager of a companyThe manager of a company Does he pay the bills?Does he pay the bills? Does he answer the phone?Does he answer the phone? Does he clean the office?Does he clean the office?

Clean the office

Pay the billsAnswer the phone

Page 3: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

33

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 4: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

44

Building my houseBuilding my house

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

Page 5: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

55

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 6: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

66

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 7: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

77

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 8: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

88

Procedure structureProcedure structure

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

. . .. . .

}

Page 9: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

99

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 10: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1010

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() {{ 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; }} voidvoid main( main()) {{ Gardener()Gardener();; Gardener()Gardener();; }}

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

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

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

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

Page 11: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1111

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 12: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1212

Exercise 1Exercise 1 Write the following void functionsWrite the following void functions::

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 13: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1313

Exercise 2Exercise 2 Write a void function called “Display”Write a void function called “Display”

that will prompt the user to enter two that will prompt the user to enter two integer numbers integer numbers nn andand mm, and will , and will display all the numbers from display all the 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 4 5 6 7 8

9 9

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

Page 14: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1414

Exercise 3Exercise 3 Write a void function called “Sum”Write a void function 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 15: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Programming Programming Principles IIPrinciples II

Lecture Notes 3.2Lecture Notes 3.2Value ParametersValue Parameters

Andreas SavvaAndreas Savva

Page 16: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1616

#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 17: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1717

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 18: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1818

MemoryMemory

ExampleExample

#include <iostream>using namespace 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);}

OutputOutput5 + 2 = 76 + 14 = 20

sumsumx yx y Add

55 22 7766 1414 2020

Page 19: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

1919

Exercise 1Exercise 1 Write a program to ask for the price Write a program to ask for the price

of a product and display the discount. of a product and display the discount. The discount which is 15% will be The discount which is 15% will be calculated and displayed in the void calculated and displayed in the void function called “Discount”, that will function called “Discount”, that will take the price as a value formal take the price as a value formal parameter.parameter.

Page 20: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2020

Exercise 2Exercise 2 Write a program that will ask the user to Write a program that will ask the user to

enter the base and height of a right-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 void function “Area”, displayed in the void function “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 21: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2121

Exercise 3Exercise 3 Write a void function called “Times” that Write a void function 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 character and it will display the 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 function “Times”.will call the function “Times”.

Page 22: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2222

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 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 function “Display”call the function “Display”..

Page 23: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2323

Exercise 5Exercise 5 Write a void function called “Even”Write a void function 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 function “Even”call the function “Even”..

Page 24: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2424

Exercise 6Exercise 6 Write a void function called “Line”Write a void function called “Line” that that

will take a character will 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.e, i.e..LineLine((’?’’?’,,55)) will display will display::

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

??

Page 25: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2525

Exercise 7Exercise 7 Write a void function called “Position”Write a void function called “Position”

that will take a character that 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 26: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2626

Exercise 8Exercise 8 Write a void function called “Sum”Write a void function 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 27: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Programming Programming Principles IIPrinciples II

Lecture Notes 3.3Lecture Notes 3.3Reference ParametersReference Parameters

Andreas SavvaAndreas Savva

Page 28: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2828

#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 29: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

2929

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 30: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3030

MemoryMemory

GlobalGlobalx y zx y z

Displayx 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

OutputOutput7 9 49 5 4

77 99

22 55 3399 44

Page 31: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3131

MemoryMemory

GlobalGlobalx y zx y z

Displayx 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 32: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3232

MemoryMemory

NumNumGlobalGlobal

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

Displayx yx y

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

Page 33: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3333

MemoryMemory

NumNumGlobalGlobal

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 yDisplay

3030

10102020

Page 34: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3434

MemoryMemory

NumNumGlobalGlobal

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 yDisplay

1010303010102020

Page 35: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3535

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 36: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

3636

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 GlobalGlobalnum, n, m, c PI, x, yx, y, z PIp, y PI, x

Page 37: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Global VariablesGlobal Variables

3737

#include <iostream>using namespace std;int x = 0;void Display (){ x = x + 1; cout << x << endl;}

int main() { for (int i=0; i<5; i++) Display(); return 0;}

12345

Page 38: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Local VariablesLocal Variables

3838

#include <iostream>using namespace std;

void Display (){ int x = 0; x = x + 1; cout << x << endl;}

int main() { for (int i=0; i<5; i++) Display(); return 0;}

11111

Page 39: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

Static VariablesStatic Variables

3939

#include <iostream>using namespace std;

void Display (){ static int x = 0; x = x + 1; cout << x << endl;}

int main() { for (int i=0; i<5; i++) Display(); return 0;}

12345

This line is executed only the first time

and the variable stays

in memory

Page 40: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

PrototypesPrototypes

4040

#include <iostream>using namespace std;void Display (int x, int &&y);;int main() { int Num = 10; Display(Num, Num); cout << Num; return 0;}void Display (int x, int &&y){ x = x + y; y = x + y;}

#include <iostream>using namespace std;void Display (int, int&&);;int main() { int Num = 10; Display(Num, Num); cout << Num; return 0;}void Display (int x, int &&y){ x = x + y; y = x + y;}

Page 41: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

The return keywordThe return keyword The reserved word The reserved word returnreturn w when hen

executed, it causes the flow of control executed, it causes the flow of control to immediately exit the function.to immediately exit the function.

4141

void divide(int a, int b){ if (b==0) cout << ”Division by zero”;

else cout << b << ” goes to ” << a << ” ” << a / b << ”times”;}

void divide(int a, int b){ if (b==0) { cout << ”Division by zero”; return; } cout << b << ” goes to ” << a << ” ” << a / b << ”times”;}

samesame

Page 42: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4242

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 43: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4343

Exercise 2Exercise 2

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

Page 44: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4444

Exercise 3Exercise 3 Write a void function “Summation” that will Write a void function “Summation” that will

take two integer numbers take two integer numbers nn and and mm and and return through a reference formal parameter return through a reference formal parameter the 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 zero. should be 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 45: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4545

Exercise 4Exercise 4 Write a void function “Money” that will take Write a void function “Money” that will take

a an amount in pounds (real number), and a an amount in pounds (real number), and it would return through two integer it would return through two integer reference formal parameter the number of reference formal parameter the number of pounds and the number of cents.pounds 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 46: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4646

Exercise 5Exercise 5

Write a void function “Euro” that will Write a void function “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 47: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4747

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 void function to take three Write a void function to take three

marks, calculate and return their marks, calculate and return their average and the highest of the three.average and 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 48: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4848

Arrays as parametersArrays as parameters Arrays are pointersArrays are pointers Passed by referencePassed by reference

void init(int Y[10]){ for (int i=0; i<10; i++) Y[i] = i + 1;}void change(int X[]){ X[3] = 99; *(X+5) = 45;}void print(int *p){ for (int i=0; i<10; i++) cout << p[i] << endl;}void main(){ int A[10]; init(A); change(A); print(A);}

1239954578910

AA00 11 22 33 44 55 66 77 88 99

AA 11 22 33 44 55 66 77 88 99 101000 11 22 33 44 55 66 77 88 99

AA 11 22 33 9999 55 4545 77 88 99 101000 11 22 33 44 55 66 77 88 99

Page 49: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

4949

2D-Arrays as parameters2D-Arrays as parametersvoid init(int Y[10][2]){ for (int i=0; i<10; i++){ Y[i][0] = i + 10; Y[i][1] = i + 20; }}void print(int A[][2]){ for (int i=0; i<10; i++) cout << A[i][0] << ’-’ << A[i][1] << endl;}void change(int *p){ p[0] = 0; *(p+1) = 1;}void main(){ int A[10][2]; init(A); change(A[4]); change(A[8]); print(A);}

10-2011-2112-2213-230-115-2516-2617-270-119-29

A A 001

00 11 22 33 44 55 66 77 88 99

1010 1111 1212 1313 1414 1515 1616 1717 1818 19192020 2121 2222 2323 2424 2525 2626 2727 2828 292911

001100

Page 50: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5050

ArraysArrays AA 11 22 33 44 55 66 77 88 99 101000 11 22 33 44 55 66 77 88 99

BB 00 1111 1212 1313 1414 1515 1616 1717 1818 1919 2020

1 4141 4242 4343 4444 4545 4646 4747 4848 4949 505000 11 22 33 44 55 66 77 88 99

int *p = A;p++;cout << *p << endl;p = &A[5];cout << *p << endl;p += 3;cout << *p << endl;p = *B;cout << *(p+5) << endl;p = *(B+5);cout << *p << endl;p = B[7];cout << *(p+2) << endl;p = &B[8][1];cout << *p << endl;p++;cout << p[0] << endl;

pp

2694316194920

Page 51: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5151

StringsStringschar s[] = ”I come from Cyprus”;char *p = &s[10];cout << *p << endl;cout << p[2] << endl;cout << p << endl;

char *q = new char[5];for (int i=2; i<6; i++) q[i-2] = p[i];q[4] = ’\0’;cout << q << endl;

mCm CyprusCypr

Page 52: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5252

Multidimensional Arrays as Multidimensional Arrays as parametersparameters

void print3D(int A[][6][3], int n) { for (int i=0; i<n; i++) { for (int j=0; j<6; j++) { for (int k=0; k<3; k++) cout << A[i][j][k] << ’\t’; cout << endl; } cout << endl << endl; }}void print2D(int A[][3], int n) { for (int i=0; i<n; i++) { for (int j=0; j<6; j++) cout << A[i][j][k] << ’\t’; cout << endl; }}void print1D(int A[], int n) { for (int i=0; i<n; i++) cout << A[i][j][k] << ’\t’; }void main() { int A[10][6][3]; . . . print3D(A,10); print2D(A[3],6); print1D(A[7][4],3);}

Page 53: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5353

MemoryMemory

Classes as Value ParametersClasses as Value Parametersclass Fraction {public: int numerator; int denominator;};

void change(Fraction f){ f.numerator = 1; f.denominator = 5; }

void main(){ Fraction y = {6,12}; change(y); cout << y.numerator << ’/’ << y.denominator;}

mainmain

yy121266

ff121266

changechange

1155

6/12

Page 54: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5454

MemoryMemory

Classes as Reference ParametersClasses as Reference Parametersclass Fraction {public: int numerator; int denominator;};

void change(Fraction &f){ f.numerator = 1; f.denominator = 5; }

void main(){ Fraction y = {6,12}; change(y); cout << y.numerator << ’/’ << y.denominator;}

mainmain

yy1212661155

1/5

changechange

ff

Page 55: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5555

Stack MemoryStack Memory

mainmain

yy 66

Classes with Pointers as Classes with Pointers as ParametersParameters

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

void change(Fraction f){ f.numerator = 1; *f.denominator = 5; }

void main(){ Fraction y = {6}; y.denominator = new int(12); change(y); cout << y.numerator << ’/’ << *y.denominator;} 6/5

????

1212

ff 66

changechange

55

11

Page 56: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5656

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

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

6 81 103 10

Page 57: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5757

Default Parameters are defined only Default Parameters are defined only ONCEONCE

#include <iostream>using namespace std;

void print(int, int = 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, int);

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 58: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5858

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 59: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

5959

The void parameterThe void parameter

void display(void){ cout << ”Welcome to C++” << endl;}

void display(){ cout << ”Welcome to C++” << endl;}

samesame

Page 60: Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva

6060

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

(the return value will be lost).(the return value will be 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