登金陵鳳凰臺 ~李白 鳳凰臺上鳳凰遊, 鳳去臺空江自流。 吳宮花草埋幽徑, 晉代衣冠成古丘。 三山半落青山外, 二水中分白鷺洲。

Slides:



Advertisements
Similar presentations
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Advertisements

Chapter 10.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Chapter 9: Arrays and Strings
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Chapter 8 Arrays and Strings
1 Chapter 8 Destructor & Operator Overloading. 2 Destructor  A destructor is a function that is called when an object is no longer required. A constructor.
Pointers OVERVIEW.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Elementary C++. Procedural Programming Split your problem into simpler parts then solve each part separately Recognize common parts and solve them only.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Bill Tucker Austin Community College COSC 1315
Secure Coding Rules for C++ Copyright © 2016 Curt Hill
Chapter # 2 Part 2 Programs And data
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Programming with ANSI C ++
User-Written Functions
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 7 - Pointers Outline 7.1 Introduction
Computer Programming BCT 1113
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
Basic Elements of C++.
Chapter 7 - Pointers Outline 7.1 Introduction
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
New Structure Recall “average.cpp” program
Subroutines in Computer Programming
CSC113: Computer Programming (Theory = 03, Lab = 01)
Arrays in C.
Lecture 6 C++ Programming
Basic Elements of C++ Chapter 2.
Arrays, For loop While loop Do while loop
Arrays and Strings Chapter 9.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Arrays Kingdom of Saudi Arabia
Pointers and Pointer-Based Strings
A First Book of ANSI C Fourth Edition
Review for Final Exam.
Engineering Problem Solving with C++, Etter
Review for Final Exam.
CS150 Introduction to Computer Science 1
C++ Pointers and Strings
CS150 Introduction to Computer Science 1
Arrays Arrays A few types Structures of related data items
CS250 Introduction to Computer Science II
Lecture 2 Arrays & Pointers May 17, 2004
C++ Programming Lecture 20 Strings
Just Enough Java 17-May-19.
Lecture 2 Arrays & Pointers September 7, 2004
CISC181 Introduction to Computer Science Dr
登金陵鳳凰臺 ~李白 鳳凰臺上鳳凰遊, 鳳去臺空江自流。 吳宮花草埋幽徑, 晉代衣冠成古丘。 三山半落青山外, 二水中分白鷺洲。
各題答對人數.
登金陵鳳凰臺 ~李白 鳳凰臺上鳳凰遊, 鳳去臺空江自流。 吳宮花草埋幽徑, 晉代衣冠成古丘。 三山半落青山外, 二水中分白鷺洲。
C++ Pointers and Strings
Chapter 8 (Part 2) Destructor & Operator Overloading (P.331)
送孟浩然之廣陵 ~李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧空盡, 惟見長江天際流。.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

登金陵鳳凰臺 ~李白 鳳凰臺上鳳凰遊, 鳳去臺空江自流。 吳宮花草埋幽徑, 晉代衣冠成古丘。 三山半落青山外, 二水中分白鷺洲。 登金陵鳳凰臺 ~李白 鳳凰臺上鳳凰遊, 鳳去臺空江自流。 吳宮花草埋幽徑, 晉代衣冠成古丘。 三山半落青山外, 二水中分白鷺洲。 總為浮雲能蔽日, 長安不見使人愁。

山居秋暝 ~ 王維 空山新雨後, 天氣晚來秋。 明月松間照, 清泉石上流。 竹喧歸浣女, 蓮動下漁舟。 隨意春芳歇, 王孫自可留。

答題分佈

Max 75 Min Average 32.22222 StdEv 16.60196 Failed 77 2016成績分佈

How to Improve? (1) One more mid-term exam in May. Three categories of questions Basic C++ syntax Subtle mistakes Sophisticated applications

How to Improve? (2) Exams are there to make you aware that there are some concepts which you still don’t understand. The brick wall is there for a reason. According to the result of each exam, probably you should adjust your time or method in studying this course. If your score is lower than 60, probably you should spend 3 more hours in each week. If your score is lower than the average, you are recommended to spend 6 more hours. If your score is lower than 20, probably you should suspend this course and try again in next year.

Chapter 6 More about Functions

Outline Default Parameters for a Function Function Overloading Pointers to Functions Exception Handling☆☆☆ Function Templates Case Study: A Calculator

Initializing Function Parameters (P.228) You may declare the default value of some parameters: void showit(char msg[] = "I know the default!"); When you omit the argument in calling the function, the default value will be supplied automatically. showit("Today is Wednesday."); showit(); Ex6_03.cpp on P.228 Note that in P.229: Only the last argument(s) can be omitted. do_it(30, 30) is legal. do_it(30, , 30, 30) is illegal.

Exercise: TETRIS (3) Modify your TETRIS program so that when the function draw_block(i) and erase_block(i) are invoked without specifying the x and y coordinates, the default values would be x=0 and y=0. Add a segment of code in your main program (before the loop which shows the falling down blocks) to test it. for (i=1; i<=7; i++) { draw_block(i); refresh(); usleep(1000000); erase_block(i); }

Function Overloading (P.237) #include <iostream> using std::endl; using std::cout; void print(int i) { cout << " Here is int " << i << endl; } void print(double f) { cout << " Here is float " << f << endl; void print(const char* c) { // Use of the const Modifier cout << " Here is char* " << c << endl; int main() { print(10); print(10.10); print("ten");

Function Overloading (P.237) Normally, we need three distinct functions to handle three different data types: int max_int(int array[], int len); long max_long(long array[], int len); double max_double(double array[], int len); Function overloading allows you to use the same function name for defining several functions as long as they each have different parameter lists. When the function is called, the compiler chooses the correct version according to the list of arguments you supply.

Ex6_07.cpp on P.238 The following functions share a common name, but have a different parameter list: int max(int array[], int len); long max(long array[], int len); double max(double array[], int len); Three overloaded functions of max() In main(), C++ compiler inspect the argument list to choose different version of functions.

Signature Overloaded functions can be differentiated by having corresponding parameters of different types, or having a different number of parameters. The signature of a function is determined by its name and its parameter list. All functions in a program must have unique signatures. The following example is not valid overloading double max(long array[], int len); long max(long array[], int len); A different return type does not distinguish a function, if the signatures are the same.

If Signature Is Not Unique … #include <iostream> using std::cout; using std::endl; int sum(int a, float b) { return a+ static_cast<int>(b); } float sum(int a, float b) { return static_cast<float>(a) + b; } int main() { cout << sum(1, 2.5) << endl; return 0; } Which version does it invoke?

Exercise: Function Overloading Define two functions display(char []) and display(char [], char[]). The first function will display the argument with a newline character. The second function will display a horizontal separator composed of equal signs ('='), then display an argument in a line, and end with a horizontal separator again. Test your functions with the following main program: int main() { char first[] = "C programming"; char second[] = "is interesting"; display(first); display(first, second); return 0; } The output should be C programming ============== C programming is interesting ==============

Function Templates In Ex6_07.cpp, you still have to repeat the same code for each function (in P.312), with different variable and parameter types. You may define a function template to ask C compiler automatically generate functions with various parameter types.

Defining a Function Template template<typename T> T max(T x[], int len) { T max = x[0]; for (int i = 1; i < len; i++) if (max < x[i]) max = x[i]; return max; }

Using a Function Template Each time you use the function max() in your program, the compiler checks to see if a function corresponding to the type of arguments that you have used in the function call already exists. If the function does not exist, the compiler creates one by substituting the argument type in your function call to replace the parameter T. Compare Ex6_08.cpp and Ex6_07.cpp to see how the source code is reduced. Note that using a template doesn’t reduce the size of your compiled program. Q: Can we calculate the length of the array inside the function?

Example: Playing Cards Playing cards have four suits: Spade () Heart () Diamond () Club () There are 13 ranks in a suit: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A ex3_suit.cpp

Use 0..51 to Represent 52 Cards 2 3 4 5 6 7 8 9 T J Q K A ======================================  0 1 2 3 4 5 6 7 8 9 10 11 12  13 14 15 16 17 18 19 20 21 22 23 24 25  26 27 28 29 30 31 32 33 34 35 36 37 38  39 40 41 42 43 44 45 46 47 48 49 50 51 ex5_cards.cpp Suit     ASCII code 3 4 5 6

Randomly Get 5 Cards An intuitive method is to randomly choose a number between 0..51, and repeat this action for 5 times for (int i = 0; i < 5; i++ ) cout << rand() % 52 << endl; print_card.cpp print_card_with_seed.cpp Sooner or later, you will see duplicate cards!

Shuffle (1) START i=0; i<52; i++ Randomly choose a card j Swap card i with card j Print all cards END The correct way is to “shuffle” your cards and get the first 5 of them.

Shuffle (2) 1 2 3 4 5 6 7 8 9 ^ + 7 2 3 4 5 6 1 8 9 @ ^ + 7 2 4 3 5 6 1 8 9 + ^ 7 2 4 3 6 5 1 8 9 + ^ 7 1 4 3 6 5 2 8 9 7 1 4 3 6 5 2 9 8 The correct way is to “shuffle” your cards and get the first 5 of them. for (i=0; i<52; i++) { j = rand() % 52; temp=card[i]; card[i]=card[j]; card[j]=temp; } Let’s see a shorter example: rand_swap.cpp card[i] temp card[j]

card_shuffle.cpp int main() { int cards[52]; initialize(cards, 52); shuffle(cards, 52); get_five(cards); return 0; } The following exercise will get you familiar with how to pass arrays to a function.

Exercise print_a_card() print_a_card_in_chinese() print_cards() sort_card()

Homework: Riffle Shuffle See these professional ways to shuffle a deck of cards: The Riffle Shuffle for Playing Card Shuffling The Riffle Shuffle Slow Motion of Riffle Shuffle 1 2 3 4 5 6 7 8 5 1 6 2 7 3 8 4 5 1 6 2 7 3 8 4 1 5 2 6 3 7 4 8

riffle_shuffle() 1 5 2 3 6 4 7 8 Implement the Riffle Shuffle as a function, whose input is an array (length may be shorter than 52) of integers. The function will shuffle the sequence of array elements according to Riffle Shuffle. Write a simple main() function to call the function, and display a deck of cards before and after the shuffle. 1 4 2 3 5 6 7

Pointers (Chapter 4) A pointer stores an address which points to a variable of some type A single pointer can point to different variables at different times a p b p = &a; *p = a p = &b; *p = b c p = &c; *p = c

Pointers to Functions (P.221) A pointer to functions also provide you the flexibility. It will call the function whose address was last assigned to the pointer. A pointer to a function must contain The memory address of the function The parameter list The return type

Declaring Pointers to Functions (P.222) double (*pfun) (char*, int); The parentheses around the pointer name, pfun, and the asterisk are necessary. Otherwise, double *pfun (char*, int) would be a function returning a pointer to a double value. long sum(long num1, long num2); long (*pfun)(long, long) = sum; long product(long, long); pfun = product;

Ex6_01.cpp on P.223 P.225

A Simpler Example As a matter of fact, I think Ex6_01.cpp is too complicated. I prefer the following example: pdo_it = product; cout << pdo_it(3,5) << endl; pdo_it = sum;

“A Pointer to a Function” as an Argument Ex6_02.cpp on P.226 int main(void) { double array[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; int len(sizeof array/sizeof array[0]); cout << endl << "Sum of squares = " << sumarray(array, len, squared); cout << endl << "Sum of cubes = " << sumarray(array, len, cubed); cout << endl; return 0; }

sumarray() double sumarry(double array[], int len, double (*pfun) (double)) { double total(0.0); for (int i=0; i<len; i++) total += pfun(array[i]); return total; }

Arrays of Pointers to Functions double sum(double, double); double product(double, double); double difference(double, double); double (*pfun[3]) (double, double) = { sum, product, difference } ; pfun[1](2.5, 3.5); product(2.5, 3.5) (*pfun)(2.5, 3.5); sum(2.5, 3.5); (*(pfun+2)) (2.5, 3.5); difference(2.5, 3.5)

Callback Functions

qsort() #include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); The contents of the array base are sorted in ascending order according to a comparison function pointed to by compar, which requires two arguments pointing to the objects being compared. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is the “callback function” which you must supply in your program.

main() /* * Sort an array of 'int' values and print it to standard output. */ int main() { int int_array[] = { 4, 5, 9, 3, 0, 1, 7, 2, 8, 6 }; const int array_size = sizeof(int_array) / sizeof(int_array[0]); int k; qsort(&int_array, array_size, sizeof(int_array[0]), cmpFunction); for (k = 0; k < array_size; k++) cout << ' ' << int_array[k]; cout << endl; return 0; }

cmpFunction() /* * Custom comparison function that can * compare 'int' values through pointers * passed by qsort(3). */ int cmpFunction(const void *p1, const void *p2) { int left = *(const int *)p1; int right = *(const int *)p2; return ((left > right) - (left < right)); }

Case Study: Implementing a Calculator Goal Design a program which acts as a calculator. It will take an arithmetic expression, evaluate it, and print out the result. For example, taking the input string “2 * 3.14159 * 12.6 * 12.6 /2 + 25.2 * 25.2” will obtain the result “1133.0”. To make it simple at the first stage, The whole computation must be entered in a single line. Spaces are allowed to be placed anywhere. Parentheses are not allowed in the expression. Only unsigned numbers are recognized.

Step 1: Eliminating Blanks from a String

An Intuitive Code for Eliminating Blanks #include <iostream> using std::cout; using std::endl; int main() { const int MAX = 80; char str1[MAX] = "NCNU is a good university."; char str2[MAX]; int i=0, j=0; do { if (str1[i] != ' ') str2[j++] = str1[i]; } while (str1[i++] != '\0'); cout << str2 << endl; return 0; }

P.322 Now, we obtain an expression with no embedding spaces. // Function to eliminate spaces from a string void eatspaces(char* str) { int i = 0; // ‘Copy to’ index to string int j = 0; // ‘Copy from’ index to string while ((*(str + i) = *(str + j++)) != ‘\0’) if (*(str + i) != ‘ ‘) i++; return; } Now, we obtain an expression with no embedding spaces.

Step 2: Evaluating an Expression expression: term addop term addop … term

Breaking Down an Expression into Terms and Numbers

Handling addop T F T F T F Get value of the first term Set expression value to value of first term Next character is ‘\0’ T F T Next character is ‘-’ Subtract value of next term from expression value F T Next character is ‘+’ Add value of next term from expression value F ERROR Return expression value

double expr(char* str) { double value = 0.0; int index = 0; value = term(str, index); for (;;) switch (*(str + index++)) case ‘\0’: return value; case ‘-’: value -= term(str, index); case ‘+’: value += term(str, index); default: cout << endl << “Arrrgh!*#!! There’s an error” << endl; exit(1); }

Getting the value of a Term (P.325) // Function to get the value of a term double term(char* str, int& index) { double value(0.0); // Somewhere to accumulate the result value = number(str, index); // Get the first number in the term // Loop as long as we have a good operator while (true) if (*(str + index) == '*') // If it's multiply, value *= number(str, ++index); // multiply by next number else if (*(str + index) == '/') // If it's divide, value /= number(str, ++index); // divide by next number else break; } return value;

Analyzing a Number

double number(char* str, int& index) { double value = 0.0; while (isdigit(*(str + index))) value = 10 * value + ( *(str + index++) – ‘0’); if (*(str + index) != ‘.’) return value; double factor = 1.0; while (isdigit(*(str + (++index)))) factor *= 0.1; value = value + ( *(str + index) – ‘0’) * factor; }

Handling the fractional part after the decimal point

Putting the Program Together P.330 Ex6_10.cpp #include <iostream> // For stream input/output #include <cstdlib> // For exit() function #include <cctype> // For isdigit() function Use cin.getline() so that the input string can contain spaces. See P.175

Extending the Program Let us try to extend it so that it can handle parentheses: 2* (3 + 4) / 6 – (5 + 6) / (7+ 8) Idea: treat an expression in parentheses as just another number. P.332 expr() recursively calls itself expr()  term()  number()  expr() The string pointed by psubstr is allocated in extract(), and must be freed as an array. Dynamic memory allocation is postponed until Chapter 7.

extract() Extract a substring between parentheses P.334 Utilize strcpy_s() which is defined in <cstring> header file

Exercise: Modify number() Implement the simple calculator defined in P.318—336. Modify the number() function defined in P.327 so that it will take hexadecimal strings as input. The return type will thus become an integer. You may test the modified program by providing an input string “A + B”, which should result in “15”. Another expression “B – A” will result in “1”.