1 / 60

Programming Principles II

Andreas Savva. Programming Principles II. Lecture Notes 1 Data Structures. 2 people. 14 people. 6 people. 10 people. 8 people. 3 people. Wagon :. [ 0 ]. [ 1 ]. [ 2 ]. [ 3 ]. [ 4 ]. [ 5 ]. Arrays. Wagon [ 0 ] = 2, Wagon [ 1 ] = 14, Wagon [ 4 ] = 8.

helene
Download Presentation

Programming Principles II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 2 people 14 people 6 people 10 people 8 people 3 people Wagon: [0] [1] [2] [3] [4] [5] Arrays Wagon[0] = 2, Wagon[1] = 14, Wagon[4] = 8

  3. How will you send me a letter? What will you write on the envelop? Eleftherias[1] Eleftherias[2] Eleftherias[3] 1 2 Eleftherias[7] 3 4 5 My House 6 7 8 Great Alexander Avenue Andreas Savva Eleftherias 4 Nicosia Eleftherias street

  4. 5th Floor Akropoli[5] Lift 5 4th Floor Akropoli[4] 4 3rd Floor Akropoli[3] 3 2 2nd Floor Akropoli[2] 1 0 1st Floor Akropoli[1] Ground Floor 0th Floor Akropoli[0] AKROPOLI BuildingAKROPOLI In C++ there are no basements

  5. Numbers[0] Numbers[1] Numbers[2] Numbers[3] Numbers[4] What is an Array (Table) • It is a set of sequential memory positions, that values of the same data-type are stored. • Every item in the table is called an element and it is specified by its position. • All the elements of the array have a common name (the name of the array) but have a different position. • It is NOT possible in C/C++ to define arrays with arbitrary starting and ending indexes.

  6. Table Name Values Example of a Table (Array) Numbers[0]  6 Numbers[1]  7 Numbers[2]  9 Numbers[3]  0 Numbers[4]  7

  7. Arrays <DataType> <Identifier>[<Dimension>]; Array positions: 0 to Dimension – 1 Example: int Numbers[10]; Positions: 0 to 9

  8. Example int DaysInMonth[12]; char SemesterGrade[5]; • DaysInMonth[4]  31 • SemesterGrade[2]  ’A’

  9. Example: #include <iostream> using namespace std; void main() { intΝ1[5], N2[5]; N1[2] = 4; N1[0] = N1[2]; N2[4] = N1[0]; } Accessing the Array 4 4 4

  10. VAR boolA[100]; intB[9]; intC[1000]; doubleD[6]; char E[10]; Array Declaration Examples

  11. Output: 27 29 31 33 35 16 17 18 19 20 Arrays and For-loops #include <iostream> using namespace std; constint 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; }

  12. Array Bounds • What happens if we try and access an element beyond the bounds of the array? max = A[370]; • or, even worse, write to it? A[-10] = 32; • Answer: • Nothing! • The program will compile • It may cause runtime errors • It may cause serious problems (during testing if lucky)

  13. Some Important Array Operations for (i = 0; i < MAX; i++) A[i] = B[i]; or copying in reverse for (i = 0; i < MAX; i++) A[MAX-1-i] = B[i]; Copying an array: for ( i = 0; i < MAX; i++) A[i] = 0; or for (i = 0; i < MAX; i++) Symbol[i] = ’ ’; Initializing: for (i = 0; i < MAX; i++) cin >> A[i]; Reading: for (i = 0; i < MAX; i++) cout << A[i]; Writing:

  14. Some Important Array Operations Sum = 0; for (i = 0; i < MAX; i++) Sum += A[i]; cout << ”The sum is ” << Sum; Summing: i = 0; Found = false; while (!Found && (i < MAX)) Found = A[i++] == SearchingKey; if (Found) cout << SearchingKey << ” is found”; else cout <<SearchingKey << ” is not found”; Searching:

  15. Two-Dimensional ArraysTables Sales per month for three types of cars for the year 2005

  16. Referencing a Flat: Akropoli[Floor][FlatNo] Akropoli[4][03] Akropoli[2][02] Akropoli[2][01] Akropoli[0][02] 401 301 101 201 402 102 202 302 203 103 303 403 001 002 003 BuildingAKROPOLI

  17. Two-Dimensional Arrays • Declaring the Array (12 rows, 3 columns) int sales[12][3]; • Referencing the Array (Make the sales of Renault for March be 11) sales[2][1] = 11; • Remember: indexes start at 0

  18. 2D Arrays Example 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; } }

  19. x, y, z double picture[MAX][MAX][3]; z y x Multi-Dimensional Arrays picture

  20. Array Initialization • Arrays can be initialized at definition like normal variables. • Single-dimensional arrays • Array of 5, all elements initialized float prices[5]={1.25, 3.50, 1.20, 2.99, 0.75}; • Array of 5, the first two elements initialized float prices[5]={1.25, 3.50}; • Array whose length is determined by initialization int months[ ]={1,2,3,4,5,6,7,8,9,10,11,12}; • Multi-dimensional arrays • Matrices 3x2, all elements initialized int x[2][3]={1,2,3,3,2,1}; // either like this... int y[2][3]={{1,2,3},{3,2,1}}; // ...or like this

  21. Constant Arrays const int Fibonacci[] = {1, 1, 2, 3, 5, 8, 13, 21}; Fibonacci cannot be changed. Thus the following will give a syntax error. Fibonacci[2] = 5; 

  22. Declaring Arrays const int MAX_GRADES = 100; … int grades[MAX_GRADES]; const int MAX_ROWS = 8; const int MAX_COLS = 4; … int table[MAX_ROWS][MAX_COLS];

  23. Strings • C++ has two ways of storing and manipulating strings: • Using the string class • C-Strings – array of characters • Reasons for using a stringclass object: • 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 index can result in system crash. • It expands and constructs storage as needed. C-strings are fixed in length and are subject to overrunning the allocation storage space. • It provides a rich set of methods for operating on a string. C-strings almost always require a subsidiary set of functions. • When necessary, it is easy to convert to C-strings using the method c_str(). Also a C-string can be assigned to a string object. • Reasons for using a C-string: • The programmer has ultimate control over how the string is stored and manipulated. • A large number of useful functions exist to input, examine and process C-strings. • They are an excellent way to explore advance programming techniques using pointers. • You will encounter them throughout your programming career, as they are embedded in almost all existing C++ code. • They are fun to program.

  24. String – Array of Characters • The last character in the string is the NULL character, ’\0’. • ’\0’must be present for the string to be valid! Example: char message[6]={’H’,’e’,’l’,’l’,’o’,’\0’}; • You must remember to leave extra space to store the NULL character, otherwise results could be unpredictable.

  25. CY Strings • C/C++ provide a shorthand for initializing and defining strings, using double quotes (”...”) to enclose the string. In this case the NULL is added automatically. char message[6]=”Hello”; • Strings start at position zero and terminated at the first NULL character. cout << Word;

  26. Hello World Yellow Example #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; } ’w’ ’Y’ ’\0’

  27. message ”What” message ”What a nice day!” Reading a String The command cin >> message; will read a string until the first control character. Thus if the input is: What a nice day! then message will have the value ”What”. We can use the function gets(message) to read the whole line into message (Library: <stdio.h>).

  28. Reading a Character The command cin >> c; will read only non-control characters. Thus if the input is: What a nice day! the statement while(cin >> c, c!=’!’) cout << c; will display Whataniceday. We can use the function cin.get() that reads any character (including control characters). Therefore the statement while(c=cin.get(), c!=’!’) cout << c; will display What a nice day

  29. Reading a String 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; }

  30. Type a line of text and press <enter> I am a student tneduts a ma I Example // 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 }

  31. String Functions • There are a number of ready to use string-related operations (functions). • These are accessible by including the definitions from the header file <cstring> in your program. • Among them you get: strlen(s) returns the length of string s strcpy(s2,s1) copies a string s1 to another string s2 strcat(s2,s1) concatenates s1 at the end of s2 strcmp(s2,s1) compares s1 and s2, returns 0 if equal

  32. strlen(s) Function Length – Returns the size of the string strlen(String)  integer i.e. strlen(”I like school”)  13 strlen(”123456789:?@”)  12 Counting how many times character ’A’ is in the string Name: 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”;

  33. s1 s2 ”one” ”one” strcpy(s1,s2) strcpy(<StringVariable>, <StringValue>); char s1[20] = ”Thirty ”, s2[20] = ”one”; strcpy(s1,s2); char s1[20] = ”Thirty ”; s2[20] = ”one”; strcpy(s1,”one”); Errors: strcpy(”one”,s1); s1 = s2;

  34. s2 s1 ”Thirty one” ”one” strcat(s1,s2) strcat(<StringVariable>, <StringValue>); char s1[20] = ”Thirty ”, s2[20] = ”one”; strcat(s1,s2); char s1[20] = ”Thirty ”; s2[20] = ”one”; strcat(s1,”one”); Error: strcat(”one”,s1);

  35. C++ strcmp(<String1>, <String2>)  integer; If String1 > String2 it will return an integer > 0 If String1 == String2 it will return 0 If String1 < String2 it will return an integer < 0 strcmp(s1,s2) = true = false = false Comparing Strings? (This is not C++) • ”George” < ”Mark” • ”George” = ”george” • ”Plant” < ”Planet” ’t’ > ’e’

  36. Converting String to Integer • Library: <stdlib.h> • Example: int x = atoi(”342”); // x = 342 int x = atoi(”342Hello856”); // x = 342 atoi(String)  Integer

  37. 13 - 13 1110101011 1110101011 1b – 1b Converting Integer to String • Library: <stdlib.h> • Example: char s[10]; cout << itoa(13, s, 10) << ” – ” << s; cout << itoa(0x3Ab, s, 2) << endl << s; cout << itoa(27, s, 16) << ” – ” << s; itoa(int, char *, int)  String Number to convert Base Returning string

  38. h ? B clint eastwood Character Functions • Library: <stdlib.h> • Example: cout << tolower(’H’) << ’\n’; cout << tolower(’?’) << ’\n’; cout << toupper(’b’) >> ’\n’; char s[] = ”Clint Eastwood”; for (inti=0; i < strlen(s); i++) cout << tolower(s[i]); tolower(char)  char toupper(char)  char

  39. Character Functions islower(char)  bool • Examples: islower(’H’) = false islower(’h’) = true islower(’?’) = false isupper(’H’) = true isupper(char)  bool

  40. Syntax: enum <type name> {<value1>,<value2>, … ,<valueΝ>}; Examples: enum Day{Mon, Tue, Wed, Thu, Fri, Sat, Sun}; enum Season {Winter, Spring, Summer, Autumn}; enumColour {Red, Green, Blue}; enumGrade {A, B, C, D, F}; enumMyBoolean {MyFalse, MyTrue}; Enumerated Types • The user can declare a new data-type in which he can also define its values.

  41. 0 1 2 3 4 5 6 Example: enum Day{Mon, Tue, Wed, Thu, Fri, Sat, Sun}; Day d; Enumerated Data Types  d = Fri; d = ”Fri”; d = Friday; d = 4; d = d++; Mon < Tue Tue < Wed int(Mon) = 0 int(Fri) = 4 (Day)(Thu+1) = Fri (Day)(Tue-1) = Mon    

  42. Enumerated Data Types • Can be used as any other data type, e.g. if (d <= Fri) cout << ”Weekday”; else cout << ”Weekend”; for (d=Mon; d<=Sun; d=(Day)(d+1)) ...

  43. Enumerated Data Types  • Cannot read enumerated type values. • cin >> d; // will give a syntax error • cout << d; // will display its ordinal position 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; } Outputtingthe day

  44. Why the following declaration is wrong? enum Grade {1,2,3,4,5,6,7,8,9,10}; Exercise #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; } } • What is the output of the following program?

  45. 1 2 3 1 2 3 4 5 6 7 0 1 2 1 2 Enumeration 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};

  46. Enumerated Types in Arrays enum Season {Winter, Spring, Summer, Autumn}; enum Day{Mon, Tue, Wed, Thu, Fri, Sat, Sun}; enum Color {Red, Green, Blue}; Day A[5]; Color B[8]; Season C[4];

  47. Programming 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; }

  48. Arrays vs Records • Array • Sequence of elements (data types) • Position association among the elements • Record • Collection of data into a single structure • No association

  49. Records • Records in C++ are called structures (struct) or classes (class). Date struct date { char strDay[4]; int day; int month; int year; }; class date { public: char strDay[4]; int day; int month; int year; };

  50. today ”Mon” 28 3 2006 Structures class date { public: char strDay[4]; int day; int month; int year; }; date today; • Data members are accessed as: • today.strDay • today.day • today.month • today.year strcpy(today.strDay,”Mon”); today.day = 28; today.month = 3; today.year = 2006;

More Related