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

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

Embed Size (px)

Citation preview

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

CSE 103, Penn State University

Monday, November 4, 2002

prepared by Doug Hogan

Page 2: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Announcements & OverviewAnnouncements & 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

Page 3: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Function HeadersFunction 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)

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

Function CallsFunction 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

Page 5: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Function Calls ExampleFunction 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;

}

Page 6: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Functions – Memory and Functions – Memory and ScopingScoping

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.

Page 7: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Parameter PassageParameter 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

Page 8: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Parameters and Memory Parameters and Memory ProblemProblem

What is the value of all variables in scope at each What is the value of all variables in scope at each arrow?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 b c

3

d

30

5

3

This line causes a compiletime error because we can’t changec. We’ll move on anyhow for illustration…

Page 9: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Prototypes vs. HeadersPrototypes 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.)

Page 10: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Functions – Default Functions – Default ArgumentsArguments

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)

Page 11: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

RecursionRecursion Lots of detail at

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

Page 12: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Generic Recursive Function Generic Recursive Function CodeCode

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}

Page 13: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Recursion ProblemRecursion 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)*5rec(2,5) = rec(1,5)*5 = 5*5 = 25so rec(3,5) = 25*5 = 125

how many calls?3

precondition?a > 0 && Assigned(b)

Page 14: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Arrays – the basicsArrays – 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

Page 15: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

What’s wrong with this code to What’s wrong with this code to find the minimum element of find the minimum element of

x?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].

Page 16: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

What is the state of x after this What is the state of x after this code executes?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}

Page 17: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

2D arrays2D arrays

Declaration: type name[numberOfRows][numberOfColumns];

Accessing individual elements:name[row][column]

Keep in mind that we still count from 0.

Page 18: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

2D arrays - problem2D 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]? 2nd row, 3rd column 11

0 1 2 3

4 5 6 7

8 9 10 11

12 13 14 15

Page 19: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Passing arrays as Passing arrays as parametersparameters

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)

Page 20: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

VectorsVectors Resizeable arrays provided within vector.h Declaration:

vector <type> name(size, initValue); Problem: Declare a vector of 10 integers, all initially 0.

vector <int> vectorOfInts(10, 0); Finding Size:

vectorName.capacity() Resizing:

vectorName.resize(newSize); vectorName.resize(vectorName.capacity() +sizeIncrease);

Page 21: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Linear SearchLinear 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.

Page 22: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Linear Search CodeLinear Search Codeint 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)

}

Page 23: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Another Method: Another Method: The Binary SearchThe 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.

Page 24: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Binary Search Example, Search for Binary Search Example, Search for 55

-9 -2 -1 0 3 5 7 17 25

yellow == low

-9 -2 -1 0 3 5 7 17 25

Compare key to middle element…

-9 -2 -1 0 3 5 7 17 25

It can’t be in the first half; eliminate first half and compare to middle of what remains

-9 -2 -1 0 3 5 7 17 25

-9 -2 -1 0 3 5 7 17 -9

Can’t be 7 or anything greater; eliminate those elements and compare again

-9 -2 -1 0 3 5 7 17 -95 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 == highgreen == middle

0 1 2 3 4 5 6 7 8

Page 25: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Binary Search CodeBinary Search Codeint 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}

Page 26: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Running Time of SearchingRunning Time of Searching

For n elements, Linear search worst case running time is n Binary search worst case running time is lg n

Page 27: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Selection SortSelection 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

Page 28: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Selection Sort ExampleSelection Sort Exampletop element is top element is yellowyellow, min element is , min element is blueblue

0

1

2

3

4

5

6

7

8

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…

Page 29: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Bubble SortBubble 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

Page 30: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Bubble Sort ExampleBubble Sort Examplebottom element is bottom element is yellowyellow

4

8

1

6

9

12

3

7

2

bottom = 8

2

4

8

8

1

8

6

9

12

12

3

7

12

12

22

bottom = 7

4>1

1>4

6

8

9>3

3>9>7

7>9>2

9

12

next iteration?

0

1

2

3

4

5

6

7

8

Page 31: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Running Time of SortingRunning Time of Sorting

Worst case, for n elements, Selection sort

Comparisons: n2

Swaps: n Total: n2 + n, asymptotically n2

Bubble sort Comparisons: n2

Swaps: n2

Total: n2 + n2, asymptotically n2

Page 32: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

PointersPointers 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

Page 33: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Pointer Fun with Binky!Pointer Fun with Binky!

Binky, provided we have QuickTime: http://www.personal.psu.edu/djh300/cse103/binky.mov

Page 34: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Pointer ExercisePointer ExerciseDraw the state of memory, Give the Draw the state of memory, Give the

outputoutputint y = 7;

int * p1;

int * p2;

p1 = new int;

p2 = &y;

*p1 = y-1;

y++;

cout << p2 << endl

<< *p1 << endl

<< *p2 << endl;

Page 35: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Pointer ExercisePointer ExerciseDraw the state of memory, Give the Draw the state of memory, Give the

outputoutputint 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

0xffbef9bc68

Page 36: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Pointer Exercise, commentedPointer Exercise, commentedDraw the state of memory, Give the Draw the state of memory, Give the

outputoutputint y = 7; // creates integer yint * p1; // creates int pointer p1int * 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

Page 37: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Pointers and Arrays ExercisePointers 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

Page 38: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

Character operationsCharacter operationsThese functions require ctype.hThese 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

Page 39: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

String operationsString operationsThese functions require string.hThese 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”

Page 40: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

String operations, ctd.String operations, ctd.These functions require string.hThese 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

Page 41: CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan

RemindersReminders 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

This PowerPoint: http://www.personal.psu.edu/djh300/cse103/exam2rev.ppt