Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Final Review COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 Scope n The scope of an identifier does not apply if the same identifier.

Similar presentations


Presentation on theme: "Programming Final Review COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 Scope n The scope of an identifier does not apply if the same identifier."— Presentation transcript:

1

2 Programming Final Review

3 COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 Scope n The scope of an identifier does not apply if the same identifier is declared in an inner block. n A global declaration of an identifier is made outside the bodies of all functions, including the main function. It is normally grouped with the other global declarations and placed at the beginning of the program file. n A local declaration of an identifier is made inside a block of code which could be the body of a function. n Globally declared identifiers can be accessed anywhere in the program. n Locally declared identifiers cannot be accessed outside of the block they were declared in.

4 COMP102 Prog. Fundamentals I: Character I/O/ Slide 3 Scope: Example 3 Number in Increment () is the global variable. #include using namespace std; int Number; //global variable void Increment(int IncNum) { IncNum = IncNum + 3; cout << IncNum << endl; Number = Number + 1; } int main() { Number = 1; Increment(Number); cout << Number << endl; return 0; }

5 Programming Character I/O

6 COMP102 Prog. Fundamentals I: Character I/O/ Slide 5 More on char Type l Constant Declaration: const char star = '*'; l Variable Declaration: char letter; l Variable Assignment : letter = 'A'; l Input/Output: char t, x, y, z; cin >> t >> x >> y >> z; INPUT: 1X3Y t = '1'; x = 'X'; y = '3'; z = 'Y'; cout << t << x << y << z << endl; OUTPUT: 1X3Y

7 COMP102 Prog. Fundamentals I: Character I/O/ Slide 6 Example 1 int main() { char character; cout << "Please enter a character!\n"; cin >> character; cout << "As int " << (int)(character) << endl ; cout << "As char " << (char)(character) << endl; cout << "As bool "; if ((bool)(character)) cout << "true\n"; else cout << "false\n"; return 0; }

8 COMP102 Prog. Fundamentals I: Character I/O/ Slide 7 Classifications of the character type characters control printable space graphical alphanumeric punctuation alphabetic digit upper lower

9 COMP102 Prog. Fundamentals I: Character I/O/ Slide 8 Some Functions on char from ctype.h Classifying Functions: isupper(c) returns nonzero if c is an uppercase letter. islower(c) returns nonzero if c is a lowercase letter. isdigit(c) returns nonzero if c is a digit character.

10 COMP102 Prog. Fundamentals I: Character I/O/ Slide 9 More Functions on char from ctype.h Classifying Functions: isalpha(c) returns nonzero if either islower(c) or isupper(c) returns nonzero. isalnum(c): returns nonzero if either isalpha(c) or isdigit(c) returns nonzero. isspace(c): returns nonzero if c is a space, newline, formfeed, carriage return, tab or vertical tab character.

11 COMP102 Prog. Fundamentals I: Character I/O/ Slide 10 More Functions on char from ctype.h Conversion Functions: tolower(c): if c is uppercase, returns lowercase; otherwise, returns c. toupper(c): if c is lowercase, returns uppercase; otherwise, returns c.

12 COMP102 Prog. Fundamentals I: Character I/O/ Slide 11 Relational Operators and the Type char '0' through '9' have ASCII code values 48 through 57 '0' < '1' <... < '9' 'A' through 'Z' have ASCII code values 65 through 90 'A' < 'B' <...< 'Z' 'a' through 'z' have ASCII code values 97 through 122 'a' < 'b' <...< 'z'

13 COMP102 Prog. Fundamentals I: Character I/O/ Slide 12 Reading/Writing One Character at a Time get(char& character) reads a single character named character from the input stream. put(char character) writes a single character named character to the output stream.

14 COMP102 Prog. Fundamentals I: Character I/O/ Slide 13 Example 4: get(c) and put(c) #include using namespace std; int main() { char character; cout << "Please enter some names "; cout << "(0 to stop) \n"; do{ cin.get(character); cout.put(character); }while (character != '0'); return 0; }

15 Programming File I/O

16 COMP102 Prog. Fundamentals I: Character I/O/ Slide 15 Input File-Related Functions #include ifstream fsIn; l fsIn.open("fname.txt") connects stream fsIn to the external file " fname.txt ". l fsIn.close() n disconnects the stream and associated file. fsIn >> c; //Behaves just like cin l fsIn.eof() n tests for the end-of-file condition.

17 COMP102 Prog. Fundamentals I: Character I/O/ Slide 16 Output File-Related Functions #include ofstream fsOut; l fsOut.open("fname.txt") connects stream fsOut to the external file " fname.txt ". l fsOut.close() n disconnects the stream and associated file. fsOut << c; //Behaves just like cout

18 COMP102 Prog. Fundamentals I: Character I/O/ Slide 17 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson Publishing Inc. File Open Result

19 COMP102 Prog. Fundamentals I: Character I/O/ Slide 18 File I/O: Example 2 // Reads three numbers from the file input_file.dat, // sums the numbers, and writes the sum to the file // output_file.dat. #include // for cin, cout #include // for ifstream, ostream using namespace std; int main(){ // declare the input and output streams ifstream input_stream; ofstream output_stream; // declare the input and output file names char input_file_name[16], output_file_name[16];

20 COMP102 Prog. Fundamentals I: Character I/O/ Slide 19 File I/O: Example 2 // user supplies the input and // output file names cout << "input_stream.open(input_file_name)”; cout << "Enter the input file name " << "(maximum 15 characters):\n"; cin >> input_file_name; cout << "Enter the output file name " << "(maximum 15 characters):\n"; cin >> output_file_name; // open the input file input_stream.open(input_file_name); // open the output file output_stream.open(output_file_name);

21 COMP102 Prog. Fundamentals I: Character I/O/ Slide 20 File I/O: Example 2 // declare variables and read in the data (3 numbers) int first, second, third; input_stream >> first >> second >> third; // write the data to the output file output_stream << "The sum of the first 3\n" << "numbers in input_file.dat\n" << "is " << (first + second + third) << endl; // close the input and output files input_stream.close(); output_stream.close(); return 0; }

22 Arrays Programming

23 COMP102 Prog. Fundamentals I: Character I/O/ Slide 22 Array Declaration l Syntax: [ ] Ex. int Ar[10]; The array elements are all values of the type. The size of the array is indicated by, the number of elements in the array. must be an int constant or a constant expression. Note that an array can have multiple dimensions.

24 COMP102 Prog. Fundamentals I: Character I/O/ Slide 23 Array Declaration // array of 10 uninitialized ints int Ar[10]; -- Ar -- 4 5 6 3 0 2 8 9 7 1 01 2 34 5

25 COMP102 Prog. Fundamentals I: Character I/O/ Slide 24 Subscripting l Declare an array of 10 integers: int Ar[10]; // array of 10 ints To access an individual element we must apply a subscript to array named Ar. n A subscript is a bracketed expression. –The expression in the brackets is known as the index. n First element of array has index 0. Ar[0] n Second element of array has index 1, and so on. Ar[1], Ar[2], Ar[3],… n Last element has an index one less than the size of the array. Ar[9] l Incorrect indexing is a common error.

26 COMP102 Prog. Fundamentals I: Character I/O/ Slide 25 Array Initialization Ex. 4 int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; Ar[3] = -1; 876 9 Ar 432510 4 5 6 3 0 2 8 9 7 1 87 9 Ar 432510 4 5 6 3 0 2 8 9 7 1 6

27 COMP102 Prog. Fundamentals I: Character I/O/ Slide 26 Ex. 1: 2-D Array Initialization It is highly recommended, however, that you nest the data in braces to show the exact nature of the array. For example, array table is better initialized as : // 2-D array of 18 initialized chars const int NUM_ROWS = 3, NUM_COLS = 6; Char table[NUM_ROWS][NUM_COLS]={ {’a’,’b’,’c’,’d’,’e’,’f’}, {’g’,’h’,’i’,’j’,’k’,’l’}, {’m’,’n’,’o’,’p’,’q’,’r’} }; nopm table 4 5 3 0 2 1 rq hijglk bcdafe 0 2 1

28 COMP102 Prog. Fundamentals I: Character I/O/ Slide 27 Ex. 1: 2-D Array Inputting Values aln table 4 5 3 0 2 1 ra Another way to fill up the values is to read them from the keyboard. For a two-dimensional array this usually requires nested for loops. If the array is an n by m array, the first loop varies the row from 0 to n-1. The second loop varies the column from 0 to m -1. const int NUM_ROWS = 3, NUM_COLS = 6; for (int row=0; row < NUM_ROWS; row++) for (int column = 0; column < NUM_COLS; column++) cin.get(table[row][column]); //input “ two-dimensional array” ensmoi wo-tid 0 2 1

29 COMP102 Prog. Fundamentals I: Character I/O/ Slide 28 Passing Arrays as Parameters l Arrays are always passed by reference. l The “[ ]” in the formal parameter specification indicates that the variable is an array. l It is a good practice to pass the dimension of the array as another parameter. l If the function must not change any element of the array then const should be used in the formal parameter specification of that array.

30 COMP102 Prog. Fundamentals I: Character I/O/ Slide 29 int ListMinimum(const int Ar[], int asize) { int SmallestValueSoFar = Ar[0]; for (int i = 1; i < asize; ++i) { if (Ar[i] < SmallestValueSoFar ) { SmallestValueSoFar = Ar[i]; } return SmallestValueSoFar ; } Passing An Array Example 3 Notice empty brackets Could we just assign a 0 and have it work?

31 COMP102 Prog. Fundamentals I: Character I/O/ Slide 30 Example 5 // Add a[i] and b[i] and store the sum in c[i] void add_array(int size, // in: array size double a[], // in: first array double b[], // in: second array double c[] ) // out: result array // array elements with subscripts ranging from // 0 to size-1 are added element by element // Pre: a[i] and b[i] (0<=i<=size-1) are defined // Post: c[i] = a[i] + b[i] (0<=i<=size-1) { int i; // Add a[i] and b[i] and store result in c[i] for (i=0; i < size; i++) c[i] = a[i] + b[i]; }

32 Programming Strings

33 COMP102 Prog. Fundamentals I: Character I/O/ Slide 32 Character Strings l A sequence of characters is often referred to as a character “string”. A string is stored in an array of type char ending with the null character '\0 '.

34 COMP102 Prog. Fundamentals I: Character I/O/ Slide 33 l A string containing a single character takes up 2 bytes of storage. Character Strings

35 COMP102 Prog. Fundamentals I: Character I/O/ Slide 34 getline The function getline can be used to read an entire line of input into a string variable. The getline function has three parameters: n The first specifies the area into which the string is to be read. n The second specifies the maximum number of characters, including the string delimiter. n The third specifies an optional terminating character. If not included, getline stops at ‘\n’.

36 COMP102 Prog. Fundamentals I: Character I/O/ Slide 35

37 COMP102 Prog. Fundamentals I: Character I/O/ Slide 36 Ex. 6: String Copy Function void strcpy(char dest[], const char src[]); // copies string src into string dest example: char name1[16], name2[16]; strcpy(name1,"Chan Tai Man"); name1: name2: strcpy(name2,"999999999999999"); strcpy(name2,name1); ChanTaiMan\0??? ChanTaiMan 99 999999999999999

38 COMP102 Prog. Fundamentals I: Character I/O/ Slide 37 String Comparison int strcmp(char s1[], char s2[]); /*compares strings s1 and s2, returns < 0 if s1 < s2 = 0 if s1 == s2 (i.e. strcmp returns false) > 0 if s1 > s2 */ int strncmp(char s1[], char s2[], int limit); /* Same as strcmp except that at most limit characters are compared. */

39 COMP102 Prog. Fundamentals I: Character I/O/ Slide 38

40 Programming Structures

41 COMP102 Prog. Fundamentals I: Character I/O/ Slide 40 Structures l A Structure is a collection of related data items, possibly of different types. l A structure type in C++ is called struct. l A struct is heterogeneous in that it can be composed of data of different types. l In contrast, array is homogeneous since it can contain only data of the same type.

42 COMP102 Prog. Fundamentals I: Character I/O/ Slide 41 Structures l Individual components of a struct type are called members (or fields). l Members can be of different types (simple, array or struct). l A struct is named as a whole while individual members are named using field identifiers. l Complex data structures can be formed by defining arrays of structs.

43 COMP102 Prog. Fundamentals I: Character I/O/ Slide 42 struct basics l Definition of a structure: struct { ;... } ; l Example: struct Date { int day; int month; int year; } ; The “Date” structure has 3 members, day, month & year. Each identifier defines a member of the structure.

44 COMP102 Prog. Fundamentals I: Character I/O/ Slide 43 struct examples l Example: struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; l Example: struct StudentRecord{ char Name[15]; int Id; char Dept[5]; char Gender; }; The “StudentRecord” structure has 4 members. The “BankAcount” structure has simple, array and structure types as members.

45 COMP102 Prog. Fundamentals I: Character I/O/ Slide 44 struct basics l Declaration of a variable of struct type: ; l Example: StudentRecord Student1, Student2; Student1 and Student2 are variables of StudentRecord type. Student1Student2 Name IdGender Dept Name IdGender Dept

46 COMP102 Prog. Fundamentals I: Character I/O/ Slide 45 Chan Tai Man 12345 M COMP Ex. 2: struct-to-struct assignment The values contained in one struct type variable can be assigned to another variable of the same struct type. l Example: strcpy(Student1.Name, "Chan Tai Man"); Student1.Id = 12345; strcpy(Student1.Dept, "COMP"); Student1.gender = 'M'; Student2 = Student1; Student1 Chan Tai Man 12345 M COMP Student2

47 COMP102 Prog. Fundamentals I: Character I/O/ Slide 46 Ex. 3-5: Nested structures We can nest structures inside structures. l Examples: struct point{ double x, y; }; point P; struct line{ point p1, p2; }; line L; struct triangle{ point p1, p2, p3; }; triangle T; (P.x, P.y) (L.p1.x, L.p1.y) (L.p2.x, L.p2.y) (T.p2.x, T.p2.y) (T.p1.x, T.p1.y) (T.p3.x, T.p3.y)

48 COMP102 Prog. Fundamentals I: Character I/O/ Slide 47 Arrays of structures l An ordinary array: One type of data l An array of structs: Multiple types of data in each array element. 0 1 2 … 98 99

49 COMP102 Prog. Fundamentals I: Character I/O/ Slide 48 Arrays of structures l We often use arrays of structures. Example: StudentRecord Class[100]; strcpy(Class[98].Name, "Chan Tai Man"); Class[98].Id = 12345; strcpy(Class[98].Dept, "COMP"); Class[98].gender = 'M'; Class[0] = Class[98];... 0 1 2 … 98 99 Chan Tai Man 12345 M COMP

50 COMP102 Prog. Fundamentals I: Character I/O/ Slide 49 Ex. 10: Initialize Data of struct Type l By assignment during declaration; example : struct StudentRecord { // student record double totalgrade; char name[name_size], id[id_size]; int grade[no_grades]; }; StudentRecord student1 = { 0.0, "CHAN Tai Man", "12345678", {80, 67, 34, 67} };

51 COMP102 Prog. Fundamentals I: Character I/O/ Slide 50 Initialization of a “ nested ” structure: struct Point { int x, y; }; //defines the coordinates of a point struct Triangle { Point vertex[3]; double area; }; //defines a triangle Triangle tlist[2] = { {{{0, 0}, {1, 0}, {0, 1}}, 0.5}, // 1st Triangle {{{2, 0}, {3, 0}, {3, 1}}, 0.5} // 2nd Triangle }; Ex. 11: Initialize Data of struct Type

52 COMP102 Prog. Fundamentals I: Character I/O/ Slide 51 Ex. 12: Using struct Type in Functions l As parameters: both pass-by-value and pass-by-reference are supported. l As type of function: assembly of return value needed. Example: StudentRecord shrink_wrap( // a function with const char sname[], // name shrink_wrap of const char sid[], // type StudentRecord const int sgrade[]) { StudentRecord temp; strcpy (temp.name, sname); strcpy (temp.id, sid); for (int index=0; index<no_grades; index++) temp.grade[index] = sgrade[index]; return temp; } // Defines an initialization function

53 Programming Searching Arrays

54 COMP102 Prog. Fundamentals I: Character I/O/ Slide 53 Unordered Linear Search l Search an unordered array of integers for a value and return its index if the value is found. Otherwise, return -1. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] l Algorithm: Start with the first array element (index 0) while(more elements in array){ if value found at current index, return index; Try next element (increment index); } Value not found, return -1; 14 2 10 5 1 3 17 2

55 COMP102 Prog. Fundamentals I: Character I/O/ Slide 54 Unordered Linear Search // Searches an unordered array of integers int search(int data[], //input: array int size, //input: array size int value){ //input: search value // output: if found, return index; // otherwise, return –1. for(int index = 0; index < size; index++){ if(data[index] == value) return index; } return -1; }

56 COMP102 Prog. Fundamentals I: Character I/O/ Slide 55 Ordered Linear Search l Search an ordered array of integers for a value and return its index if the value is found; Otherwise, return -1. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] l Linear search can stop immediately when it has passed the possible position of the search value. 1 2 3 5 7 10 14 17

57 COMP102 Prog. Fundamentals I: Character I/O/ Slide 56 Ordered Linear Search // Searches an ordered array of integers int lsearch(int data[],// input: array int size, // input: array size int value // input: value to find ) { // output: index if found for(int index=0; index<size; index++){ if(data[index] > value) return -1; else if(data[index] == value) return index; } return -1; }

58 COMP102 Prog. Fundamentals I: Character I/O/ Slide 57 Binary Search l Search an ordered array of integers for a value and return its index if the value is found. Otherwise, return -1. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] l Binary search skips over parts of the array if the search value cannot possibly be there. 1 2 3 5 7 10 14 17

59 COMP102 Prog. Fundamentals I: Character I/O/ Slide 58 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson Publishing Inc. 6

60 COMP102 Prog. Fundamentals I: Character I/O/ Slide 59

61 COMP102 Prog. Fundamentals I: Character I/O/ Slide 60 Binary Search l Binary search is based on the “divide-and- conquer” strategy which works as follows: n Start by looking at the middle element of the array –1. If the value it holds is lower than the search element, eliminate the first half of the array from further consideration. –2. If the value it holds is higher than the search element, eliminate the second half of the array from further consideration. n Repeat this process until the element is found, or until the entire array has been eliminated.

62 COMP102 Prog. Fundamentals I: Character I/O/ Slide 61 Binary Search // Searches an ordered array of integers int bsearch(int data[], // input: array int size, // input: array size int value // input: value to find ) // output: if found,return index { // otherwise, return -1 int first, middle, last; first = 0; last = size - 1; while (true) { middle = (first + last) / 2; if (data[middle] == value) return middle; else if (first >= last) return -1; else if (value < data[middle]) last = middle - 1; else first = middle + 1; }

63 Programming Sorting Arrays

64 COMP102 Prog. Fundamentals I: Character I/O/ Slide 63 Ex. 1A: Selection Sort l Selection sort performs sorting by repeatedly putting the largest element in the unsorted portion of the array to the end of this unsorted portion until the whole array is sorted. l It is similar to the way that many people do their sorting.

65 COMP102 Prog. Fundamentals I: Character I/O/ Slide 64 Before sorting14210513177 After pass 114210513717 After pass 272105131417 After pass 372351101417 After pass 412357101417

66 // Sort array of integers in ascending order void select(int data[], // in/output: array int size){ // input: array size int temp; // for swap int max_index; // index of max value for (int rightmost=size-1; rightmost>0; rightmost--){ //find the largest item in the unsorted portion //rightmost is the end point of the unsorted part of array max_index = 0; //points the largest element for ( int current=1; current<=rightmost; current++) if (data[current] > data[max_index]) max_index = current; //swap the largest item with last item if necessary if (data[max_index] > data[rightmost]){ temp = data[max_index]; // swap data[max_index] = data[rightmost]; data[rightmost] = temp; } }}

67 COMP102 Prog. Fundamentals I: Character I/O/ Slide 66 Ex. 1B: Bubble Sort l Bubble sort examines the array from start to finish, comparing elements as it goes. l Any time it finds a larger element before a smaller element, it swaps the two. l In this way, the larger elements are passed towards the end. l The largest element of the array therefore "bubbles" to the end of the array. l Then it repeats the process for the unsorted portion of the array until the whole array is sorted.

68 COMP102 Prog. Fundamentals I: Character I/O/ Slide 67 Ex. 1B: Bubble Sort l Algorithm n Define the entire array as the unsorted portion of the array. n While the unsorted portion of the array has more than one element: 1. For every element in the unsorted portion, swap with the next neighbor if it is larger than the neighbor. 2. Reduce the size of the unsorted portion of the array by 1.

69 Before sorting14210513177 outer=7, inner=021410513177 outer=7, inner=121014513177 outer=7, inner=221051413177 outer=7, inner=321051143177 outer=7, inner=421051314177 outer=7, inner=621051314717 outer=6, inner=125101314717 outer=6, inner=225110314717 outer=6, inner=325131014717 outer=6, inner=525131071417 outer=5, inner=121531071417 outer=5, inner=221351071417 outer=5, inner=421357101417 outer=4, inner=012357101417 --- outer=1, inner=012357101417

70 //Example1b: Bobble sort // Sort an array of integers in ascending order void bubble(int data[], // in/output: array int size){ // input: array size int temp; // for swap for(int outer=size-1; outer > 0; outer--){ for (int inner=0; inner < outer; inner++) { // traverse the nested loops if ( data[inner] > data[inner+1] ) { // swap current element with next // if the current element is greater temp = data[inner]; data[inner] = data[inner+1]; data[inner+1] = temp; } } // inner for loop } // outer for loop }

71 Programming Recursion

72 COMP102 Prog. Fundamentals I: Character I/O/ Slide 71 Ex. 2: Recursion In general, we can express the factorial function as follows: n! = n * (n-1)! Is this correct? Well… almost. The factorial function is only defined for positive integers. So we should be a little bit more precise: n! = 1(if n is equal to 1) n! = n * (n-1)! (if n is larger than 1)

73 COMP102 Prog. Fundamentals I: Character I/O/ Slide 72 Ex. 2: Recursion The C++ equivalent of this definition: int fac(int numb){ if(numb<=1) return 1; else return numb * fac(numb-1); } recursion means that a function calls itself

74 COMP102 Prog. Fundamentals I: Character I/O/ Slide 73 Recursion We must always make sure that the recursion bottoms out: l A recursive function must contain at least one non-recursive branch. l The recursive calls must eventually lead to a non-recursive branch.

75 COMP102 Prog. Fundamentals I: Character I/O/ Slide 74 Recursion General Form l How to write recursively? int recur_fn(parameters){ if(stopping condition) return stopping value; // other stopping conditions if needed return function of recur_fn(revised parameters) }

76 COMP102 Prog. Fundamentals I: Character I/O/ Slide 75 Direct Computation Method l Fibonacci numbers: Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... where each number is the sum of the preceding two. l Recursive definition: n F(0) = 0; n F(1) = 1; n F(number) = F(number-1)+ F(number-2);

77 COMP102 Prog. Fundamentals I: Character I/O/ Slide 76 Example 3: Fibonacci numbers //Calculate Fibonacci numbers using recursive function. int fib(int number) { if (number == 0) return 0; if (number == 1) return 1; return (fib(number-1) + fib(number-2)); } int main(){// driver function int inp_number; cout << "Please enter an integer: "; cin >> inp_number; cout << "The Fibonacci number for "<< inp_number << " is "<< fib(inp_number)<<endl; return 0; }


Download ppt "Programming Final Review COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 Scope n The scope of an identifier does not apply if the same identifier."

Similar presentations


Ads by Google