60
Programming Principles Programming Principles II II Lecture Notes 1 Lecture Notes 1 Data Structures Data Structures Andreas Savva Andreas Savva

Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

Embed Size (px)

Citation preview

Page 1: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

Programming Programming Principles IIPrinciples II

Lecture Notes 1Lecture Notes 1Data StructuresData Structures

Andreas SavvaAndreas Savva

Page 2: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

22

ArraysArrays

WagonWagon:: [[00]] [[11]] [[22]] [[33]] [[44]] [[55]]

2people

14people

6people

10people

8people

3people

WagonWagon[[00] = 2, ] = 2, WagonWagon[[11] = 14, ] = 14, WagonWagon[[44] = 8] = 8

Page 3: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

33

How will you send me a letter?What will you write on the envelop?

Great

Ale

xand

er A

venu

e

Eleftherias street

Andreas SavvaEleftherias 4Nicosia

My HouseMy House

11

22

33

44

55

66

7

88

Elef

ther

ias[

1]

Elef

ther

ias[

1]

Elef

ther

ias[

2]

Elef

ther

ias[

2]

Elef

ther

ias[

3]

Elef

ther

ias[

3]

Elef

ther

ias[

7]

Elef

ther

ias[

7]

Page 4: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

44In C++ there are

no basements

BuildingBuilding AKROPOLIAKROPOLI

AKROPOLIAKROPOLI

11stst Floor Floor

22ndnd Floor Floor

33rdrd Floor Floor

44thth Floor Floor

55thth Floor Floor

Ground FloorGround Floor00thth Floor Floor Akropoli[0]Akropoli[0]

Akropoli[1]Akropoli[1]

Akropoli[2]Akropoli[2]

Akropoli[3]Akropoli[3]

Akropoli[4]Akropoli[4]

Akropoli[5]Akropoli[5]

55

44

33

22

11

00

LiftLift

Page 5: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

55

What is an Array (Table)What is an Array (Table) It is a set of sequential memory positions, that It is a set of sequential memory positions, that

values of the same data-type are storedvalues of the same data-type are stored.. Every item in the table is called an element and it Every item in the table is called an element and it

is specified by its positionis specified by its position.. All the elements of the array have a common name All the elements of the array have a common name

(the name of the array) but have a different (the name of the array) but have a different position.position.

It is NOT possible in C/C++ to define arrays with It is NOT possible in C/C++ to define arrays with arbitrary starting and ending indexes.arbitrary starting and ending indexes.

NumbersNumbers 66 33 77 44 77Pos 00 11 22 33 44

Numbe

rs[

Numbe

rs[00]]

Numbe

rs[

Numbe

rs[11]]

Numbe

rs[

Numbe

rs[22]]

Numbe

rs[3]

Numbe

rs[3]

Numbe

rs[4]

Numbe

rs[4]

Page 6: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

66

Example of a Table (Array)Example of a Table (Array)

NumberNumberss

66 77 99 00 77

Position [[00]] [[11]] [[22]] [[33]] [[44]]

Table Name Values

Numbers[0]Numbers[0] 66Numbers[1]Numbers[1] 77Numbers[2]Numbers[2] 9 9 Numbers[3]Numbers[3] 00Numbers[4]Numbers[4] 77

Page 7: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

77

ArraysArrays

ExampleExample:: int Numbers[10];int Numbers[10];

NumbersNumbers 66 33 88 44 77--

3232 44 1212 9999 66

Pos 00 11 22 33 44 55 66 77 88 99

<<DataTypeDataType>> < <IdentifierIdentifier>> [<DimensionDimension>>];

Positions: 0 to 9

Array positions: 0 to Dimension –

1

Page 8: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

88

ExampleExample

DaysInMonth[4] DaysInMonth[4] 31 31 SemesterGrade[2] SemesterGrade[2] ’A ’A’’

int DaysInMonth[12];int DaysInMonth[12];char SemesterGrade[5];char SemesterGrade[5];

DaysInMonthDaysInMonth 3131 2828 3131 3030 3131 3030 3131 3131 3030 3131 3030 3131

Pos 00 11 22 33 44 55 66 77 88 99 1010 1111

SemesterGradSemesterGradee

’’AA’’ ’’BB’’ ’’AA’’ ’’CC’’ ’’BB’’

Pos 00 11 22 33 44

Page 9: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

99

Accessing the ArrayAccessing the Array

ExampleExample::

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

voidvoid main() main(){{ intint ΝΝ1[5]1[5], , N2[5]N2[5];; N1[2] = 4;N1[2] = 4; N1[0] = N1[2];N1[0] = N1[2]; N2[4] = N1[0];N2[4] = N1[0];}}

N1N1

00 11 22 33 44

N2N2

00 11 22 33 44

4444

44

Page 10: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1010

Array Declaration Array Declaration ExamplesExamples

AA truetrue truetrue falsefalse truetrue falsefalse …… falsefalse00 11 22 33 44 …… 9999

BB -5-5 -5-5 8787 22 -12-12 123123 00 77 9900 11 22 33 44 55 66 77 88

DD 1.21.2 0.020.02 231.0231.0 66.1266.12 78.0178.01 -2.4-2.4

00 11 22 33 44 55

VAR bool AA[100]; int BB[9]; int CC[1000]; double DD[6]; char E E[10];

CC -2-2 77 -1-1 77 -3-3 22 …… 2200 11 22 33 44 55 …… 999999

EE ’’c’c’ ’’r’r’ ’’a’a’ ’’v’v’ ’’a’a’ ’’a’a’ ’’d’d’ ’’f’f’ ’’p’p’ ’’f’f’

00 11 22 33 44 55 66 77 88 99

Page 11: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1111

Arrays and For-loopsArrays and For-loops#include <iostream>using namespace std;const int MAX = 10;

void main(){ int A[MAX], i;

for (i = 0; i < MAX; i++) A[i] = i + 11;

for (i = 0; i < MAX / 2; i++) A[i] += A[i+5];

for (i = 0; i < MAX; i++) cout << A[i] << endl;}

27293133351617181920

OutputOutput::

AA00 11 22 33 44 55 66 77 88 99

AA 1111 1212 1313 1414 1515 1616 1717 1818 1919 202000 11 22 33 44 55 66 77 88 99

AA 2727 2929 3131 3333 3535 1616 1717 1818 1919 202000 11 22 33 44 55 66 77 88 99

Page 12: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1212

Array BoundsArray Bounds What happens if we try and access an What happens if we try and access an

element beyond the bounds of the array?element beyond the bounds of the array?max = A[370];

or, even worse, write to it?or, even worse, write to it?A[-10] = 32;

Answer:Answer: Nothing!Nothing! The program will compile The program will compile It may cause runtime errorsIt may cause runtime errors It may cause serious problems (during testing if It may cause serious problems (during testing if

lucky)lucky)

Page 13: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1313

Some Important Array OperationsSome Important Array Operations

for (i = 0; i < MAX; i++) cin >> A[i];

for ( i = 0; i < MAX; i++) A[i] = 0;oror for (i = 0; i < MAX; i++) Symbol[i] = ’ ’;

for (i = 0; i < MAX; i++) cout << A[i];

for (i = 0; i < MAX; i++) A[i] = B[i];or copying in reverseor copying in reverse for (i = 0; i < MAX; i++) A[MAX-1-i] = B[i];

Copying an array:Copying an array:

Initializing:Initializing:

Reading:Reading:

Writing:Writing:

Page 14: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1414

Some Important Array OperationsSome Important Array Operations

i = 0;Found = false;while (!Found && (i < MAX)) Found = A[i++] == SearchingKey;

if (Found) cout << SearchingKey << ” is found”;else cout << SearchingKey << ” is not found”;

Sum = 0;for (i = 0; i < MAX; i++) Sum += A[i];cout << ”The sum is ” << Sum;

Summing:Summing:

Searching:Searching:

Page 15: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1515

Two-Dimensional ArraysTwo-Dimensional ArraysTablesTables

Sales per month for three typesSales per month for three typesof cars for the year 2005of cars for the year 2005

HondaHonda[0][0]

RenaultRenault[1][1]

ToyotaToyota[2][2]

Jan Jan [0][0] 1212 1313 88

Feb Feb [1][1] 1313 55 77

Mar Mar [2][2] 66 88 44

Apr Apr [3][3] 88 44 55

May May [4][4] 99 66 77

Jun Jun [5][5] 22 44 33

Jul Jul [6][6] 55 77 88

Aug Aug [7][7] 22 77 1414

Sep Sep [8][8] 88 55 44

Oct Oct [9][9] 99 77 1212

Nov Nov [10][10]

88 1212 66

Dec Dec [11][11]

99 1010 1212

Page 16: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1616

BuildingBuilding AKROPOLIAKROPOLI

001001 002002 003003

101101 102102 103103

201201 202202 203203

301301 302302 303303

401401 402402 403403

Akropoli[Akropoli[00][][0202]]

Akropoli[Akropoli[22][][0101]]

Akropoli[Akropoli[22][][0202]]

Akropoli[Akropoli[44][][0303]]

Akropoli[Akropoli[FloorFloor][][FlatNoFlatNo]]

Referencing a Flat:Referencing a Flat:

Page 17: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1717

Two-Dimensional ArraysTwo-Dimensional Arrays

Declaring the Array (12 Declaring the Array (12 rows, 3 columns)rows, 3 columns)

int sales[12][3];int sales[12][3];

Referencing the Array Referencing the Array (Make the sales of Renault (Make the sales of Renault for March be 11)for March be 11)

sales[2][1] = 11;sales[2][1] = 11;

Remember: indexes start Remember: indexes start at at 00

HondaHonda[0][0]

RenaultRenault[1][1]

ToyotaToyota[2][2]

Jan Jan [0][0] 1212 1313 88

Feb Feb [1][1] 1313 55 77

Mar Mar [2][2] 66 88 44

Apr Apr [3][3] 88 44 55

May May [4][4] 99 66 77

Jun Jun [5][5] 22 44 33

Jul Jul [6][6] 55 77 88

Aug Aug [7][7] 22 77 1414

Sep Sep [8][8] 88 55 44

Oct Oct [9][9] 99 77 1212

Nov Nov [10][10]

88 1212 66

Dec Dec [11][11]

99 1010 1212

Page 18: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1818

2D Arrays Example2D Arrays Example1 5 3 3 2 4 4 3 7

2 1 3 2 3 7 0 4 4

Addition of Matrices:

#include <iostream>using namespace std;void main(){ float M1[2][3],M2[2][3],Result[2][3]; int row, col;

for (row=0; row<2; row++) // Read matrix 1 for (col=0; col<3; col++) cin >> M1[row][col];

for (row=0; row<2; row++) // Read matrix 2 for (col=0; col<3; col++) cin >> M2[row][col];

for (row=0; row<2; row++) // Add the two matrices for (col=0; col<3; col++) Result[row][col]= M1[row][col] + M2[row][col];

for (row=0; row<2; row++) { // Display the result for (col=0; col<3; col++) cout << Result[row][col] << ’\t’; cout << endl; }}

Page 19: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

1919

Multi-Dimensional ArraysMulti-Dimensional Arrays

zzyy

xx

picturepicture

double picture[MAX][MAX][3];

x, y, zx, y, z

Page 20: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2020

Array InitializationArray Initialization Arrays can be initialized at definition like normal Arrays can be initialized at definition like normal

variables.variables.

Single-dimensional arraysSingle-dimensional arrays Array of 5, all elements initializedArray of 5, all elements initialized

float prices[5]={1.25, 3.50, 1.20, 2.99, 0.75};float prices[5]={1.25, 3.50, 1.20, 2.99, 0.75}; Array of 5, the first two elements initializedArray of 5, the first two elements initialized

float prices[5]={1.25, 3.50};float prices[5]={1.25, 3.50}; Array whose length is determined by initializationArray whose length is determined by initialization

int months[ ]={1,2,3,4,5,6,7,8,9,10,11,12};int months[ ]={1,2,3,4,5,6,7,8,9,10,11,12};

Multi-dimensional arraysMulti-dimensional arrays Matrices 3x2, all elements initializedMatrices 3x2, all elements initialized

int x[2][3]={1,2,3,3,2,1};int x[2][3]={1,2,3,3,2,1}; // either like this...int y[2][3]={{1,2,3},{3,2,1}}; int y[2][3]={{1,2,3},{3,2,1}}; // ...or like this

Page 21: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2121

Constant ArraysConstant Arrays

const int Fibonacci[] = {1, 1, 2, 3, 5, 8, 13, 21};const int Fibonacci[] = {1, 1, 2, 3, 5, 8, 13, 21};

FibonacciFibonacci cannot be changed. Thus the cannot be changed. Thus the following will give a syntax error.following will give a syntax error.

Fibonacci[2] = 5; Fibonacci[2] = 5;

Page 22: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2222

Declaring ArraysDeclaring Arrays

const int MAX_GRADES = 100;const int MAX_GRADES = 100;……int grades[MAX_GRADES];int grades[MAX_GRADES];

const int MAX_ROWS = 8;const int MAX_ROWS = 8;const int MAX_COLS = 4;const int MAX_COLS = 4;……int table[MAX_ROWS][MAX_COLS];int table[MAX_ROWS][MAX_COLS];

Page 23: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2323

StringsStrings C++ has two ways of storing and manipulating strings:C++ has two ways of storing and manipulating strings:

Using the Using the string classstring class C-StringsC-Strings – array of characters – array of characters

Reasons for using a Reasons for using a stringstring class object: class object: It does a bounds check on every index used to access string It does a bounds check on every index used to access string

elements. This is not true for C-strings, and using an invalid C-string elements. This is not true for C-strings, and using an invalid C-string index can result in system crash.index can result in system crash.

It expands and constructs storage as needed. C-strings are fixed in It expands and constructs storage as needed. C-strings are fixed in length and are subject to overrunning the allocation storage space.length and are subject to overrunning the allocation storage space.

It provides a rich set of methods for operating on a string. C-strings It provides a rich set of methods for operating on a string. C-strings almost always require a subsidiary set of functions.almost always require a subsidiary set of functions.

When necessary, it is easy to convert to C-strings using the method When necessary, it is easy to convert to C-strings using the method c_str()c_str(). Also a C-string can be assigned to a . Also a C-string can be assigned to a stringstring object. object.

Reasons for using a Reasons for using a C-stringC-string:: The programmer has ultimate control over how the string is stored The programmer has ultimate control over how the string is stored

and manipulated.and manipulated. A large number of useful functions exist to input, examine and A large number of useful functions exist to input, examine and

process C-strings.process C-strings. They are an excellent way to explore advance programming They are an excellent way to explore advance programming

techniques using pointers.techniques using pointers. You will encounter them throughout your programming career, as You will encounter them throughout your programming career, as

they are embedded in almost all existing C++ code.they are embedded in almost all existing C++ code. They are fun to program.They are fun to program.

Page 24: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2424

String – Array of CharactersString – Array of Characters

The last character in the string is the The last character in the string is the NULLNULL character, character, ’\0’’\0’ ..

’’\0’\0’ must be present for the string to be valid!must be present for the string to be valid!

ExampleExample::

char message[6]={’H’,’e’,’l’,’l’,’o’,’\0’};

You must remember to leave extra space to store You must remember to leave extra space to store the NULL character, otherwise results could be the NULL character, otherwise results could be unpredictable.unpredictable.

messagemessage ’’H’H’ ’’e’e’ ’’l’l’ ’’l’l’ ’’o’o’ ’’\0’\0’00 11 22 33 44 55

Page 25: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2525

StringsStrings C/C++ provide a shorthand for initializing and C/C++ provide a shorthand for initializing and

defining strings, using double quotes (defining strings, using double quotes (”...””...”) to ) to enclose the string. In this case the NULL is added enclose the string. In this case the NULL is added automatically.automatically.

char message[6]=”Hello”;

Strings start at position zero and terminated at the Strings start at position zero and terminated at the first NULL character. first NULL character.

messagemessage ’’H’H’ ’’e’e’ ’’l’l’ ’’l’l’ ’’o’o’ ’’\0’\0’00 11 22 33 44 55

WordWord ’’C’C’ ’’Y’Y’ ’’\0’\0’ ’’P’P’ ’’R’R’ ’’U’U’ ’’S’S’ ’’\0’\0’ ’’?’?’00 11 22 33 44 55 66 77 88

cout << Word;CY

Page 26: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2626

ExampleExample#include <iostream>using namespace std;void main(){ char message[20] = ”Hello World”; cout << message << endl; message[0] = ’Y’; message[5] = ’w’; message[6] = ’\0’; cout << message << endl;}

Hello WorldYellow

WordWord ’’H’H’ ’’e’e’ ’’l’l’ ’’l’l’ ’’o’o’ ’ ’’ ’ ’’W’W’ ’’o’o’ ’’r’r’ ’’l’l’ ’’d’d’ ’’\0\0’’

00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313

’Y’ ’w’ ’\0’

Page 27: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2727

Reading a StringReading a StringThe commandThe command

cin >> message;cin >> message;will read a string until the first control character. Thus will read a string until the first control character. Thus if the input is:if the input is:

What a nice day!

then message will have the value then message will have the value ”What””What”..

We can use the functionWe can use the function

gets(message)gets(message)

to read the whole line into message (Library: to read the whole line into message (Library: <stdio.h><stdio.h>).).

”What”messagemessage

”What a nice day!”messagemessage

Page 28: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2828

Reading a CharacterReading a CharacterThe commandThe command

cin >> c;cin >> c;will read only non-control characters. Thus if the input will read only non-control characters. Thus if the input is:is:

What a nice day!the statementthe statement

while(while(cin >> ccin >> c, c!=’!’) cout << c;, c!=’!’) cout << c;

will display will display WhatanicedayWhataniceday..

We can use the function We can use the function cin.get()cin.get() that reads any that reads any character (including control characters). Therefore the character (including control characters). Therefore the statementstatement

while(while(c=cin.get()c=cin.get(), c!=’!’) cout << c;, c!=’!’) cout << c;

will display will display What a nice dayWhat a nice day

Page 29: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

2929

Reading a StringReading a String

We can also read a line of string with the following code:We can also read a line of string with the following code:

#include <iostream>using namespace std;

void main(){ char c, message[255]; int i=0; while (c=cin.get(), i<254 && c!=’\n’) message[i++] = c; message[i] = ’\0’; cout << message << endl;}

Page 30: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3030

ExampleExample// Reads in a line of text and prints it in reverse order#include <iostream.h>#include <stdio.h>#define MAXLEN 256 // max length of strings used

void main() { char inline[MAXLEN], outline[MAXLEN]; int i,j;

cout << ”Type a line of text and press <enter>\n”; gets(inline);

for (i=0;inline[i]!=’\0’;i++) ; // find end of string

for (j=0,i--;i>=0;j++,i--) outline[j]=inline[i]; outline[j]=’\0’; //terminate string cout << outline << ’\n’; // print text in reverse}

Type a line of text and press <enter>I am a studenttneduts a ma I

Page 31: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3131

String FunctionsString Functions There are a number of ready to use string-There are a number of ready to use string-

related operations (functions).related operations (functions). These are accessible by including the definitions These are accessible by including the definitions

from the header file from the header file <cstring><cstring> in your program. in your program.

Among them you get:Among them you get:strlen(s)strlen(s) returns the length of string s returns the length of string s

strcpy(s2,s1) strcpy(s2,s1) copies a string s1 to another string s2 copies a string s1 to another string s2

strcat(s2,s1) strcat(s2,s1) concatenates s1 at the end of s2concatenates s1 at the end of s2

strcmp(s2,s1) strcmp(s2,s1) compares s1 and s2, returns 0 if equalcompares s1 and s2, returns 0 if equal

Page 32: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3232

strlen(s)strlen(s)

int i, Count = 0;char Name[100];. . . for (i = 0; i < strlen(Name); i++) if (Name[i] == ’A’) Count++;

cout << ”Character -A- found ” << Count << ” times”;

strlen(String) strlen(String) integerinteger

Function Length – Returns the size of the stringFunction Length – Returns the size of the string

Counting how many times character ’A’ is in the string Name:Counting how many times character ’A’ is in the string Name:

i.e.i.e. strlen(”I like school”) 13 strlen(”123456789:?@”) 12

Page 33: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3333

strcpy(s1,s2)strcpy(s1,s2)

strcpy(<StringVariable>, strcpy(<StringVariable>, <StringValue>);<StringValue>);

char s1[20] = ”Thirty ”, s2[20] = ”one”;strcpy(s1,s2); ”one”

s1s1

”one”s2s2

char s1[20] = ”Thirty ”; s2[20] = ”one”;strcpy(s1,”one”);

strcpy(”one”,s1);

Errors:Errors:

s1 = s2;

Page 34: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3434

strcat(s1,s2)strcat(s1,s2)

strcat(<StringVariable>, strcat(<StringVariable>, <StringValue>);<StringValue>);

char s1[20] = ”Thirty ”, s2[20] = ”one”;strcat(s1,s2); ”Thirty one”

s1s1

”one”s2s2

char s1[20] = ”Thirty ”; s2[20] = ”one”;strcat(s1,”one”);

strcat(”one”,s1);

Error:Error:

Page 35: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3535

strcmp(s1,s2)strcmp(s1,s2)Comparing Strings? (This is not C++)Comparing Strings? (This is not C++)

””George” < ”Mark”George” < ”Mark” ””George” = ”george”George” = ”george” ””Plant” < ”Planet”Plant” < ”Planet”

= true= true

= false= false

= false= false

’t’ > ’e’

strcmp(<String1>, <String2>) strcmp(<String1>, <String2>) integer;integer;

C++C++

If String1 > String2 it will return an integer > 0If String1 == String2 it will return 0If String1 < String2 it will return an integer < 0

Page 36: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3636

Converting String to Converting String to IntegerInteger

Library: Library: <stdlib.h><stdlib.h>

Example:Example:int x = atoi(”342”); // x = 342int x = atoi(”342”); // x = 342

int x = atoi(”342Hello856”); // x = 342int x = atoi(”342Hello856”); // x = 342

atoi(String) atoi(String) IntegerInteger

Page 37: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3737

Converting Integer to Converting Integer to StringString

Library: Library: <stdlib.h><stdlib.h>

Example:Example:char s[10];char s[10];cout << itoa(13, s, 10) << ” – ” << s;cout << itoa(13, s, 10) << ” – ” << s;cout << itoa(0x3Ab, s, 2) << endl << s;cout << itoa(0x3Ab, s, 2) << endl << s;cout << itoa(27, s, 16) << ” – ” << s;cout << itoa(27, s, 16) << ” – ” << s;

itoa(int, char *, int) itoa(int, char *, int) StringString

BaseNumber to

convertReturning

string

13 - 13111010101111101010111b – 1b

Page 38: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3838

Character FunctionsCharacter Functions Library: Library: <stdlib.h><stdlib.h>

Example:Example:cout << tolower(’H’) << ’\n’;cout << tolower(’H’) << ’\n’;cout << tolower(’?’) << ’\n’;cout << tolower(’?’) << ’\n’;cout << toupper(’b’) >> ’\n’;cout << toupper(’b’) >> ’\n’;char s[] = ”Clint Eastwood”;char s[] = ”Clint Eastwood”;for (int i=0; i < strlen(s); i+for (int i=0; i < strlen(s); i+

+)+) cout << tolower(s[i]);cout << tolower(s[i]);

tolower(char) tolower(char) charchartoupper(char) toupper(char) charchar

h?Bclint eastwood

Page 39: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

3939

Character FunctionsCharacter Functions

Examples:Examples:islower(’H’) = falseislower(’H’) = false

islower(’h’) = trueislower(’h’) = true

islower(’?’) = falseislower(’?’) = false

isupper(’H’) = trueisupper(’H’) = true

islower(char) islower(char) bool bool

isupper(char) isupper(char) bool bool

Page 40: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4040

Enumerated TypesEnumerated Types The user can declare a new data-type in which The user can declare a new data-type in which

he can also define its values.he can also define its values.

enumenum <type name <type name> > {{<<valuevalue1>1>,,<<valuevalue2>2>,, … … ,,<<valuevalueΝ>Ν>}};;

SyntaxSyntax::

ExamplesExamples::enum Dayenum Day {Mon, Tue, Wed, Thu, Fri, Sat, Sun};{Mon, Tue, Wed, Thu, Fri, Sat, Sun};enum Season {Winter, Spring, Summer, Autumn};enum Season {Winter, Spring, Summer, Autumn};enum Colour {Red, Green, Blue};enum Colour {Red, Green, Blue};enumenum Grade {A, B, C, D, F};Grade {A, B, C, D, F};enum MyBoolean {MyFalse, MyTrue};enum MyBoolean {MyFalse, MyTrue};

Page 41: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4141

Enumerated Data TypesEnumerated Data Types

ExampleExample::enum Day {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

Day d;

d = Fri;d = Fri;

d = ”Fri”;d = ”Fri”;

d = Friday;d = Friday;

d = 4;d = 4;

d = d++;d = d++;

Mon < TueMon < TueTue < WedTue < Wedint(Mon) = 0int(Mon) = 0int(Fri) = 4int(Fri) = 4(Day)(Thu+1) = (Day)(Thu+1) = FriFri(Day)(Tue-1) = (Day)(Tue-1) = MonMon

1 20 3 4 5 6

Page 42: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4242

Can be used as any other data type, Can be used as any other data type, e.g.e.g.

Enumerated Data TypesEnumerated Data Types

for (d=Mon; d<=Sun; d=(Day)(d+1)) ...

if (d <= Fri) cout << ”Weekday”;else cout << ”Weekend”;

Page 43: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4343

Cannot read enumerated type values.Cannot read enumerated type values. cin >> d;cin >> d; // will give a syntax error // will give a syntax error cout << d;cout << d; // will display its ordinal position // will display its ordinal position

Enumerated Data TypesEnumerated Data Types

switch (d) { case Mon : cout << ”Monday”; break; case Tue : cout << ”Tuesday”; break; case Wed : cout << ”Wednesday”; break; case Thu : cout << ”Thursday”; break; case Fri : cout << ”Friday”; break; case Sat : cout << ”Saturday”; break; case Sun : cout << ”Sunday”; break; default : break;} Outputting

the day

Page 44: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4444

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

#include <iostream>using namespace std;

void main() { enum Grade {A,B,C,D,F};

Grade exam;

for (exam=A; exam<=F; exam=(Grade)(exam+1)) switch (exam) { case A : cout << ”Excellent\n”; break; case B : cout << ”Very Good\n”; break; case C : cout << ”Good\n”; break; case D : cout << ”Pass\n”; break; default: break; } }

Why the following declaration is Why the following declaration is wrong?wrong? enum Grade {1,2,3,4,5,6,7,8,9,10};

Page 45: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4545

EnumerationEnumeration

enum Color {Red=1, Green=2, Blue=3};

enum Day {Mon=1, Tue, Wed, Thu, Fri, Sat, Sun};

enum Month {Jan=1, Feb=1, Mar=2, Apr=2, May=2, Jun=3, Jul=3, Aug=3, Sep=4, Oct=4, Nov=4, Dec=1};

enum Rainbow {Red, Orange, Yellow, Green=1, Blue};

1 2 3

1 2 3 4 5 6 7

0 1 2 1 2

Page 46: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4646

Enumerated Types in ArraysEnumerated Types in Arrays

enum Season {Winter, Spring, Summer, Autumn};enum Day {Mon, Tue, Wed, Thu, Fri, Sat, Sun};enum Color {Red, Green, Blue};

Day AA[5];Color BB[8];Season CC[4];

AA FriFri MonMon FriFri TueTue WedWed00 11 22 33 44

BB RedRed GreeGreenn

RedRed BlueBlue RedRed BlueBlue GreeGreenn

GreeGreenn

00 11 22 33 44 55 66 77CC SummerSummer WinterWinter SummerSummer SpringSpring

00 11 22 33

Page 47: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4747

Programming ExampleProgramming Example

#include <iostream>using namespace std;

void main() { enum Day {Mon,Tue,Wed,Thu,Fri,Sat,Sun};

float hours[7], salary=0.0;

cout << ”Enter working hours from Monday to Sunday\n”;

for (Day d=Mon; d<=Sun; d=(Day)(d+1)) cin >> hours[d];

for (d=Mon; d<=Sun; d=(Day)(d+1)) if (d==Sat || d==Sun) salary += hours[d] * 2.0; else salary += hours[d] * 1.5;

cout << ”Your salary is ” << salary;}

Page 48: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4848

Arrays vs RecordsArrays vs Records ArrayArray

Sequence of elements (data types) Sequence of elements (data types) Position association among the elementsPosition association among the elements

RecordRecord Collection of data into a single structureCollection of data into a single structure No associationNo association

44 88 1212 2020 3232 4747 6060

pos pos 00 11 22 33 44 55 66

Surname:Surname: EastwoodEastwood

Name:Name: ClintClint

Nationality:Nationality: USAUSA

Telephone:Telephone: +15678900+15678900

Age:Age: 7575

Page 49: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

4949

RecordsRecords Records in C++ are called structures Records in C++ are called structures

((structstruct) or classes () or classes (classclass).).

strDaystrDay ””Mon”Mon”

dayday 2828

monthmonth 33

yearyear 20062006

DateDate

struct date {

char strDay[4]; int day; int month; int year;};

class date {public: char strDay[4]; int day; int month; int year;};

Page 50: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5050

StructuresStructures Data members are Data members are

accessed as:accessed as: today.strDaytoday.strDay today.daytoday.day today.monthtoday.month today.yeartoday.year

class date {public: char strDay[4]; int day; int month; int year;};

date today;

strcpy(today.strDay,”Mon”);today.day = 28;today.month = 3;today.year = 2006; 20062006

33

2828

””Mon”Mon”todaytoday

Page 51: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5151

Programming ExampleProgramming Example#include <iostream>using namespace std;

class date {public: char strDay[4]; int day, month, year;};

void main() { date today;

strcpy(today.strDay,”Mon”); today.day = 28; today.month = 3; today.year = 2006;

cout << ”Today is ” << today.strDay << ” ” << today.day << ”/” << today.month << ”/” << today.year;}

Today is Mon 28/3/2006

20062006

33

2828

””Mon”Mon”todaytoday

Page 52: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5252

Initializing ValuesInitializing Valuesclass date {public: char strDay[4]; int day; int month; int year;};

date today = {”Mon”,28,3,2006};

20062006

33

2828

””Mon”Mon”todaytoday

date today;today = {”Mon”,28,3,2006};

Error:Error:

Page 53: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5353

Initializing Initializing SomeSome Values Values

class date {public: char strDay[4]; int day; int month; int year;};

date today = {”Mon”,28};

????

????

2828

””Mon”Mon”todaytoday

We can initialize only a number of the fields in a structure but only We can initialize only a number of the fields in a structure but only from left-to-right.from left-to-right.

date today = { , ,3,2006};Error:Error:

Page 54: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5454

Classes of ClassesClasses of Classes#include <iostream>using namespace std;class date {public: char strDay[4]; int day, month, year;};

class event {public: char description[30]; date when;};

void main() { event twins;

strcpy(twins.description, ”NY Twin Towers attack”); strcpy(twins.when.strDay,”Tue”); twins.when.day = 11; twins.when.month = 9; twins.when.year = 2001;

. . .}

twinstwins

20012001

99

1111

””Tue”Tue”

””NY Twin Towers attack”NY Twin Towers attack”

whenwhen

Page 55: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5555

Arrays of ClassesArrays of Classesvoid main() { event history[100];

strcpy(history[0].description, ”NY Twin Towers attack”); strcpy(history[0].when.strDay,”Tue”); history[0].when.day = 11; history[0].when.month = 9; history[0].when.year = 2001;

strcpy(history[1].description, ”Great Alexander birth”); strcpy(history[1].when.strDay,”Sun”); history[1].when.day = 2; history[1].when.month = 1; history[1].when.year = -354;

for (int i=0; i<2; i++) cout << history[i].description << ” (” << history[i].when.strDay << ’ ’ << history[i].when.day << ’/’ << history[i].when.month << ’/’ << history[i].when.year << ”)\n”;}

NY Twin Towers attack (Tue 11/9/2001)Great Alexander birth (Sun 2/1/-354)

Page 56: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5656

The Data Structure of the The Data Structure of the ProgramProgram

-354-354

11

22

””SunSun””

””Great Alexander birth”Great Alexander birth”

20012001

99

1111

””Tue”Tue”

””NY Twin Towers attack”NY Twin Towers attack”

. . .

[0] [1] [99]

??

??

??

””??????””

””????

history[1].when.strDay[0] = ’W’;history[1].when.strDay[1] = ’e’;history[1].when.strDay[2] = ’d’;

”Wed”

Page 57: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5757

StructuresStructuresstruct date { char strDay[4]; int day, month, year;};

struct event { char description[30]; date when;};

struct ImportantEvents { int size; int which[100];};

event history[100];ImportantEvents important;

. . .

cout << history[important.which[0]].description;

Page 58: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5858

Structure DeclarationsStructure Declarations

class date {public: char strDay[4]; int day, month, year;} today; // object

. . .

cout << today.strDay << ” ” << today.day << ’/’ << today.month << ’/’ << today.year;

Page 59: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

5959

User-Defined Data TypesUser-Defined Data Typestypedef int MyInteger;typedef struct {double x;double y;

} Point; // data type

void main(){MyInteger x = 5;cout << x << endl;Point P;P.x = 12.0;P.y = 123.0;cout << P.x << ’-’ << P.y;

}

512 - 123

Page 60: Programming Principles II Lecture Notes 1 Data Structures Andreas Savva

6060

Type DefinitionsType Definitions

typedef class date { // data typepublic: char strDay[4]; int day, month, year;} today; // data type. . .

today t;date d;

typedef class {public: char strDay[4]; int day, month, year;} today; // data type. . . . .

today t;