Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan.

Similar presentations


Presentation on theme: "CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan."— Presentation transcript:

1 CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

2 Announcements & Overview The exam… Wednesday night, 8:15 p.m. (be on time), 100 Thomas Bring a #2 pencil, your ID card, and an eraser if you want it No notes, books, calculators Homework 4 due by 4:30 p.m. today Lab 9 in progress, due during lab 10 Study guide: http://www.personal.psu.edu/djh300/cse103/ exam2studyguide.htm http://www.personal.psu.edu/djh300/cse103/ exam2studyguide.htm

3 Function Headers returnType name(/*parameters*/) The return type is the value the function sends back to the function that calls it if nothing is returned, use void Parameters (placeholders for inputs to the function) are specified with their type and name no parameters  leave parentheses empty Ex: int sum(int a, int b)

4 Function Calls When the function is called, the parameters are replaced with arguments. Arguments can be constants the names of variables that are known to the calling method other function calls If the return type of the function is void, the function is called by itself on a line. If the return type is non-void, something needs to be done with what is returned Assign it to a variable Output it Use it as an argument to another function call

5 Function Calls Example Call foo with x as its input. foo(x); foo(int x); is WRONG!! void foo(x); is WRONG!! Valid calls of goo from main: cout << goo(x); y = goo(x); y = goo(goo(x)); goo(x); isn’t very useful because we ingore the return value. void foo(int a) { cout << a; } int goo(int a) { return a*3; } int main() { int x = 3; int y; … }

6 Functions – Memory and Scoping Memory is divided up such that each function essentially has its own memory space. A function can access the variables declared within its braces (local variables), its parameters, and any global variables. Functions cannot access variables declared in other functions. It’s possible to declare a variable with the same name local to two different functions.

7 Parameter Passage Pass by value – int a memory for a is allocated separately changes may be made to a, but they won’t affect the arguments Pass by reference – int & a no new memory is allocated, a is essentially a pointer back to the argument changing a changes the argument at the same time Pass by constant reference – const int & a again, a is like a pointer, but this time, it cannot even be changed locally preferred for large objects and arrays

8 Parameters and Memory Problem What is the value of all variables in scope at each arrow? int foo(int a, int & b, const int & c) { int d = 3; a += d; b = b*d; c = b; return a*b*c; } int main() { int d = 2; int e = 1; int f = 2; f = foo(d, e, f); } memory visible to foo memory visible to main 2 d 1 e 2 f 2 a bc 3 d 30 5 3 This line causes a compiletime error because we can’t change c. We’ll move on anyhow for illustration…

9 Prototypes vs. Headers Prototypes are placed above main and allow you to call a function before you implement it. To go from a function header to a function prototype, simply add a semicolon to the end. header: void foo(int a, int & b) prototype: void foo(int a, int & b); Names could be omitted and prototypes are still valid. (Not really recommended.)

10 Functions – Default Arguments In the function header (or prototype if one is used), the parameters can be given default values. These values are used when the function is called without enough arguments. Examples: void displayStars(int cols = 10, int rows = 1) void displayStars(int cols = 10, int rows)

11 Recursion Lots of detail at http://www.personal.psu.edu/djh300/cse103/recursion.htm http://www.personal.psu.edu/djh300/cse103/recursion.htm Parts of a recursive definition: Base case: where the function is defined simply, usually for 0 and/or 1. where recursive calls stop, infinite recursion happens w/o it ex: 0! = 1 and 1! = 1 Recursive case: where the function is defined in terms of itself recursive calls need to change the values of the arguments so they work toward a base case ex: for n > 1, n! = (n-1)! * n

12 Generic Recursive Function Code int recursiveFunc(int n) // PRE: (something about what values of n are legal) // POST: what it does, e.g. returns value of the factorial of n { if(n == valueOfFirstBaseCase) // Base case { return someConstantValue; } // other base cases if necessary if(n /*some condition usu. involving >, >=, <, <=*/) { // Recursive case return (recursiveFunc(/*changed n*/) + something) * somethingElse + somethingElse2; } // other recursive cases, similarly }

13 Recursion Problem int rec(int a, int b) { if(a == 1) return b; if(a > 1) return rec(a-1,b)*b; } value of rec(3,5)? how many calls? precondition? value of rec(3,5)? rec(3,5) = rec(2,5)*5 rec(2,5) = rec(1,5)*5 = 5*5 = 25 so rec(3,5) = 25*5 = 125 how many calls? 3 precondition? a > 0 && Assigned(b)

14 Arrays – the basics Declare an array to hold 15 floats. float x[15]; Print the first element of x cout << x[0]; Print the last element of x cout << x[14]; What is the value of x[3]? unknown

15 What’s wrong with this code to find the minimum element of x? int x[15] = {…}; int minIndex = 0; for(int i = 0; i < 14; i++) { if(i < minIndex) minIndex = i; } cout << “Min is “ << x[minIndex]; Here we compare the subscripts, not the elements at those subscripts. We want to do the comparison x[i] < x[minIndex].

16 What is the state of x after this code executes? int x[4] = {10, 20, 30, 40}; for(int i = 1; i < 4; i++) { x[i] += x[i-1]/10; } i==1: {10, 20+1=21, 30, 40} i==2: {10, 21, 30+2=32, 40} i==3: {10, 21, 32, 40+3=43} final: {10, 21, 32, 43}

17 2D arrays Declaration: type name[numberOfRows][numberOfColumns]; Accessing individual elements: name[row][column] Keep in mind that we still count from 0.

18 2D arrays - problem Given the array y at right, What is y[0][0]? 0 y[3][2]? row 3, column 2 14 y[2][3]? 2 nd row, 3 rd column 11 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

19 Passing arrays as parameters In the function header, give the array type, name, and empty brackets. ex: void foo(int array[], int size) In the function call, just use the array name. No brackets ex: foo(my_array, 10); For 2D arrays, you need to specify the number of columns. ex: void foo(int arr2d[][10], int numRows)

20 Vectors Resizeable arrays provided within vector.h Declaration: vector name(size, initValue); Problem: Declare a vector of 10 integers, all initially 0. vector vectorOfInts(10, 0); Finding Size: vectorName.capacity() Resizing: vectorName.resize(newSize); vectorName.resize(vectorName.capacity() +sizeIncrease);

21 Linear Search General idea: Compare search key to every element of the array. When key is found, save location and quit successfully. If key isn’t found after checking all elements, report failure.

22 Linear Search Code int Search(const double array[], int size, double key) // PRE: Assigned(array[0..size-1]) && Assigned(key) // POST: If key is found in array, function returns index // such that array[FCTVAL] == key // Otherwise, function returns -1 { for(int i = 0; i < size; i++) // go through array { // looking for key if(array[i] == key) // when it’s found { // return its index return i; // and leave function } return -1; // if the loop completes, the key // isn’t found, so report error // condition (-1) }

23 Another Method: The Binary Search If we have a sorted array, we can take a different approach to searching called the binary search. The binary search allows us to narrow our search field by half at each iteration. We compare the key to the middle element. We could find the key there  success. We otherwise eliminate half of the array and search the other half.

24 Binary Search Example, Search for 5 -9-203571725 yellow == low -9-203571725 Compare key to middle element… -9-203571725 It can’t be in the first half; eliminate first half and compare to middle of what remains -9-203571725 -9-2035717-9 Can’t be 7 or anything greater; eliminate those elements and compare again -9-2035717-9 5 is now the only thing remaining in the array. It is thus also the middle. Since the middle equals the key, we’ve successfully found our key. blue == high green == middle 0 1 2 3 4 5 6 7 8

25 Binary Search Code int Search(const double array[], int size, double key) { int high = size-1; // high index – one less than size int low = 0; // low index – 0 for any array int mid; // middle index while(low <= high) // search until low and high cross { mid = (high+low)/2; // find middle index if(key == array[mid]) // compare to middle { return mid; // successful case } else if(key < array[mid]) // key is in first half { // eliminate second half high = mid-1; } else if(key > array[mid]) // key is in second half { // eliminate first half low = mid+1; } } return -1; // if loop completes, search failed }

26 Running Time of Searching For n elements, Linear search worst case running time is n Binary search worst case running time is lg n

27 Selection Sort For ascending order, Go through the array, looking for the location of the smallest element Swap the smallest element with the top of the array Move the top down Repeat the above until the top is at the bottom For descending order, we look for the largest element and move it to the bottom

28 Selection Sort Example top element is yellow, min element is blue 012345678012345678 4 8 1 6 9 12 3 7 2 top = 0 minIndex = 2 1 1 8 4 6 9 12 3 7 2 4 8 top = 1 minIndex = 8 2 1 2 4 6 9 12 3 7 8 top = 2 minIndex = 6 4 3 1 2 3 6 9 12 4 7 8 top = 3 6 etc…

29 Bubble Sort While the bottom isn’t at the top For every element of the array (except the last) Compare it with the one after it. If they’re not sorted, swap them. Move bottom up (or top down if ascending) Largest element bubbles to the bottom (top if descending) with each iteration of the outer loop

30 Bubble Sort Example bottom element is yellow 4 8 1 6 9 12 3 7 2 bottom = 8 2 4 8 8 1 8 6 9 12 3 7 22 bottom = 7 4>1 1>4 6 8 9>3 3>9>73>9>7 7>9>27>9>2 9 12 next iteration? 012345678012345678

31 Running Time of Sorting Worst case, for n elements, Selection sort Comparisons: n 2 Swaps: n Total: n 2 + n, asymptotically n 2 Bubble sort Comparisons: n 2 Swaps: n 2 Total: n 2 + n 2, asymptotically n 2

32 Pointers Store the addresses of locations in memory New operators and keywords to know: * is used to declare a pointer, e.g. int * p; & is used to find the address of an existing variable, e.g. &y * is also used to dereference a pointer, i.e. tell the value of the pointee, e.g. *p1; new is used with a data type to allocate unnamed space in memory so that a pointer may point to it, e.g. new int The assignment operator, =, is used with these ideas. Make sure you’re assigning like things – pointer = pointer or pointee = pointee

33 Pointer Fun with Binky! Binky, provided we have QuickTime: http://www.personal.psu.edu/djh300/cse103/binky.mov http://www.personal.psu.edu/djh300/cse103/binky.mov

34 Pointer Exercise Draw the state of memory, Give the output int y = 7; int * p1; int * p2; p1 = new int; p2 = &y; *p1 = y-1; y++; cout << p2 << endl << *p1 << endl << *p2 << endl;

35 Pointer Exercise Draw the state of memory, Give the output int y = 7; int * p1; int * p2; p1 = new int; p2 = &y; *p1 = y-1; y++; cout << p2 << endl << *p1 << endl << *p2 << endl; 7 y p1 p2 6 8 0xffbef9bc 6 8

36 Pointer Exercise, commented Draw the state of memory, Give the output int y = 7; // creates integer y int * p1;// creates int pointer p1 int * p2; // creates int pointer p2 p1 = new int;// allocates memory space // that p1 points to; it // holds an integer p2 = &y;// gets the address of y // makes p2 point to y *p1 = y-1;// dereferences p1, making // its pointee get the // value y-1 y++;// increments y (and p2’s pointee) cout << p2 << endl // prints address p2 points to << *p1 << endl// prints value of p1’s pointee << *p2 << endl;// prints value of p2’s pointee

37 Pointers and Arrays Exercise Given: float x[ ] = {3.14, 2.71}; The size of a float in memory is 4 bytes. What is the output of cout << x[0]; 3.14 cout << x; 0xffbef9b8 cout << *x; 3.14 cout << *x +1; 3.14 + 1 4.14 cout << x[0]+1; 3.14+1 4.14 cout << x+1; 0xffbef9b8 + 1(4 bytes) 8 + 4 = 12 = c 0xffbef9bc cout << x[2]; Error! meaningless value

38 Character operations These functions require ctype.h tolower – converts argument to lowercase cout << tolower(‘A’); prints a toupper – converts argument to uppercase cout << toupper(‘d’); prints D isalpha – returns true when argument is a letter isalpha(‘A’); returns true isdigit – returns true when argument is a digit isdigit(‘A’); returns false islower – returns true when argument is lowercase islower(‘A’); returns false

39 String operations These functions require string.h strlen(char str[]) returns length of str (up to ‘\0’) strlen(“Hello”) returns 5 strcat(char toStr[], char fromStr[]) puts fromStr at the end of toStr, if there’s room char a[20] = “the ”; char b[9] = “string”; strcat(a, b) sets a to “the string” strncat(char toStr[], char fromStr[], int n) puts the first n chars of fromStr at the end of toStr, if room char a[20] = “the ”; char b[9] = “string” strcat(a, b, 3) sets a to s “the str”

40 String operations, ctd. These functions require string.h strcpy(char toStr[], const char fromStr[]) makes a copy of fromStr into toStr, if there’s room char a[20] = “the ”; char b[9] = “string”; strcpy(a, b) sets a to “string” strcmp(const char str1[], const char str2[]) str1 < str2 lexicographically  FCTVAL < 0 str1 == str2 lexicographically  FCTVAL == 0 str1 > str2 lexicographically  FCTVAL > 0 char a[20] = “the ”; char b[9] = “string”; strcmp(a, b) returns some positive value

41 Reminders The exam… Wednesday night, 8:15 p.m. (be on time), 100 Thomas Bring a #2 pencil, your ID card, and an eraser if you want it No notes, books, calculators Homework 4 due by 4:30 p.m. today It makes sense to finish lab 9 before the exam. Study guide: http://www.personal.psu.edu/djh300/cse103/ exam2studyguide.htm http://www.personal.psu.edu/djh300/cse103/ exam2studyguide.htm This PowerPoint: http://www.personal.psu.edu/djh300/cse103/ exam2rev.ppt http://www.personal.psu.edu/djh300/cse103/ exam2rev.ppt


Download ppt "CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan."

Similar presentations


Ads by Google