+ All Categories
Home > Documents > Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular....

Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular....

Date post: 28-Jul-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
18
Lesson 11 (functions) Ricardo Salazar, PIC 10A
Transcript
Page 1: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

Lesson 11(functions)

Ricardo Salazar, PIC 10A

Page 2: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● C++ is modular. I.e., programs can be built from smaller pieces called components.

● A function is set of instructions, separated from the main routine, that can perform tasks on its own and can be called at any time. We have already used some of them:

main(), Circle.move(), sqrt(a),getline(c,s), cwin.coord(w,x,y,z), setw(width)

● Functions can receive values called parameters.● They often return a value as well.● Our goal is to learn how to write our own functions.

(4.1) Functions

Page 3: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● When writing a function we need to ○ specify the types of values it will receive as parameters; and○ specify the type of value it will return.

● Syntax:r_type someFun(type1 par1, type2 par2, ... ){ --CODE_OF_THE_FUNCTION-- return object/variable of type r_type;}

● A simple example:bool sumEqualsZero( float a , double b ){ double sum = a + b; return (sum == 0);}// This is a bad example. The use of 'float' is OK // for didactic purposes.

Writing functions

Page 4: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● When calling a function it is not necessary to write the type of value it returns…

● but make sure it receives the appropriate parameters.int main(){double x=2.3; y=1.0; cout << "The sum is :"; /* cout << double addTwoNumbers(x,y); // Don't! */ cout << addTwoNumbers(x,y); /* cout << addTwoNumbers(a); // Error! */ /* cout << addTwoNumbers('C','o'); // Error??? */}

● addTwoNumbers is not defined on <iostream> nor <string> nor "ccc_win.h". It is defined in the same program. But…

● how does the compiler know it is OK to use?● Place the body of the function before main.

Calling functions

Page 5: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

#include <iostream>using namespace std;

double addTwoNumbers(double a, double b){ double sum = a + b ; return sum;}

int main(){ /* double a = 2.3, b = 1.0; // Trouble? */ double x = 2.3, y = 1.0;

cout << "The sum is "; cout << addTwoNumbers(x,y) << endl; return 0;}

Example

Page 6: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Functions should have a brief description of what they do. They should also describe the parameters and the return value.

● Think of it as a summary. You get the main details without having to worry about understanding all the code.

/* ************************************* addTwoNumbers: Adds two numbers. Parameters a: First number b: Second number Returns the sum of two numbers ************************************* */

double addTwoNumbers( double a, double b){ return a + b;}

Comments

The comment section is longer than the actual function.

Are you sure we are doing things right???

Page 7: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Sure, adding numbers does not require a full function… but think about other places where it could have come in handy.○ Homework 1: convertToSeconds(hours);○ Homework 2: singularOf(wordInPlural);○ Homework 3: drawShape(turn);

● Use functions when:○ there is a procedure that needs to be repeated. ○ a piece of the code is particularly complex.

■ This way you can focus on the finding the errors.○ you anticipate re-using your code for a different program.

Why functions?

Page 8: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Write a function that draws an O or an X (depending on whether the turn is odd or even).

void drawShape(int turn){ const double SIZE = 0.4; if ( turn % 2 == 0 ){ Point p = cwin.get_mouse("Click for X."); cwin << Line( Point( p.get_x()-SIZE , p.get_y()+SIZE ) , Point( p.get_x()+SIZE , p.get_y()-SIZE ) ); cwin << Line( Point( p.get_x()-SIZE , p.get_y()-SIZE ) , Point( p.get_x()+SIZE , p.get_y()+SIZE ) ); } else{ p = cwin.get_mouse("Click for O."); cwin << Circle(p, SIZE); }

return;}

Example (from Hw 3)

When a function doesn't return a value is called a procedure.

- The function type is void, and- return is followed by a semi-colon ( ; ) - The return statement is optional.

Page 9: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Compute the value of a savings account after 5 and 10 years if the initial balance is 2018.The formula is b = P ⨉ (1+p/100)t

where:○ b is the value after t years,○ p is the interest rate,○ P is the initial balance,○ t is the time in years.

Assume p is 2 percent. - The function pow in <cmath> can be usedto compute powers.

Example (savings account)

#include<iostream>#include<cmath>using namespace std;

int main(){ double value; value = 2018*pow(1.02,5); cout << value << endl;

value = 2018*pow(1.02,10); cout << value << endl; return 0;}

Not good!

- Not reusable. - What if r changes?

Page 10: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Let's try again...

Savings account (cont)

#include <iostream>using namespace std;

double futureValue(int t){ return 2018*pow(1.02,t);}

int main(){ double value;

value = futureValue(5); cout << value << endl; value = futureValue(10); cout << value << endl;

return 0;}

#include <iostream>using namespace std;

double futureValue(double P, double r, int t){ return P*pow(1+r/100,t);}

int main(){ // added bonus: request info // from user!!! double rate, years, ini, value; cout << "Principal, rate, time? "; cin >> ini >> rate >> years;

value=futureValue(ini,rate,years); cout << value << endl;

return 0;}

Better! but...

- If r changes?- If P is not 2015?

Much better!!!

Page 11: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Write a function that determines the sign of a given number. Should return 1 if the number is positive and -1 if it is negative.

int signOf( double number ){ if ( number > 0 ){ return 1; } else if ( number < 0 ){ return -1; }

}

What is the value of the following statements?- int a = signOf( 3.14 );- int b = signOf( cos(3.14) );- int c = signOf( -3/14 );

Example: two or more return's

// a = 1// b = -1// c = -1 ???// my computer sets c = 0// which is considered garbage!

What went wrong?

- Always consider all possible cases.

- Here we are missing the case where the number is 0.

else return 0;

Page 12: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Write a program that decomposes a number into its prime factors. ○ They should be sorted in ascending order. ○ Repetitions are OK.

● Let us look at some examples:

Factorization example

36 is divisible by 2, list 2 and divide18 is divisible by 2, list 2 and divide 9 is not divisible by 2, use the next prime 9 is divisible by 3, list 3 and divide 3 is divisible by 3, list 3 and divide 1 stop.

Factors of 36: 2, 2, 3, 3.

60 | 2 OK, list and divide30 | 2 OK, list and divide15 | 2 no, next prime15 | 3 OK, list and divide 5 | 3 no, next prime 5 | 5 OK, list and divide 1 STOP

Factors of 60: 2, 2, 3, 5.

It would be helpful if we had:- A way to tell primes apart from other numbers; and- A way to find the smallest prime that divides a number.

BINGO!

← These are our functions

You know what they say:

"It it looks like a loop and talks like a loop… "

Page 13: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Ok, we have our functions. But what if we do not know how to implement them?○ Use stubs

/* Stub for isPrime(int n) returns true */

bool isPrime(int number){ return true; }

- We are assuming all numbers are prime.- We'll fix this later.

Factorization (cont)

The steps:

read N

i=2while ( i <= N )|| while( isPrime(i) && i divides N )| | list i| | update N = N / i| end while|| i = i + 1|end while

Page 14: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Now let's do the actual translation

Factorization (cont)

read N

i=2while i <= N| | while ( isPrime(i) && i divides N)| | list i| | update N = N / i| end while|| i = i + 1end while

#include <iostream>using namespace std;

bool isPrime(int n){ //stub return true; }

int main(){ int N; cin >> N;

for (int i=2 ; i<=N ; i++){ while( isPrime(i) && N%i == 0 ){ cout << i << " "; N /= i; } }

return 0;}

Page 15: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Now let's tackle the isPrime function.○ Prime numbers are positive○ 1 is not prime○ 2 is the only even prime○ If n >= 3 is odd

check for odd divisors■ if n%3 is zero, not prime■ if n%5 is zero, not prime■ if n%7 is zero, not prime■ …■ When do we stop?

● When we reach n, or ● Use the following...

Theorem: If n is not prime, it has a divisor less or equal to √n.

Factorization (cont)

bool isPrime(int n){ if ( n <= 0) return false; if ( n == 1) return false; if ( n == 2) return true; if ( n%2 == 0 ) return false;

int k = 3; while ( k*k <= n){ if( n%k == 0) return false; k = k + 2; } return true;}

Page 16: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● What changes are neededif we do not want repeatedfactors?○ Check for repetitions

in the inner loop!

Factorization (cont)

read N

i=2while i <= N| | while ( isPrime(i) && i divides N)| | if ( i is not repeated ) | | | list i| | end if| | update N = N / i| end while|| i = i + 1end while

#include <iostream>using namespace std;

bool isPrime(int n){ //stub return true; }

int main(){ int N; cin >> N;

for (int i=2 ; i<=N ; i++) { int repetition=1; while( isPrime(i) && N%i == 0 ){ if (repetition==1) cout << i << " "; N /= i; repetition++; } } return 0;}

A function is not needed in this case…but the pseudo-code certainly helped!

Page 17: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Write a program that computes the least common multiple of a pair of integers. ○ Here is how the process works:

Factorization (cont)

36, 60 | 2 Both of them are divisible. Divide both.18, 30 | 2 Both of them are divisible. Divide both. 9, 15 | 2 None of them are divisible. Use next prime. 9, 15 | 3 Both of them are divisible. Divide both. 3, 5 | 3 Only one is divisible. Divide it. Other remains unchanged. 1, 5 | 3 None of them are divisible. Use next prime. 1, 5 | 5 Only one is divisible. Divide it. Other remains unchanged. 1, 1 | Stop.

The least common multiple of 36 and 60 is: 2⨉2⨉3⨉3⨉5 = 180.

Next steps:- Pseudo-code- Implementation

We get to: - reuse our function isPrime(i)- adapt our loops.

Page 18: Lesson 11 - UCLA Program in ComputingLesson 11 (functions) Ricardo Salazar, PIC 10A C++ is modular. I.e., programs can be built from smaller pieces called components. A function is

● Your turn. Here is the basic pseudo-code with some extra blank lines. Make some changes and translate.○ I'll help you with the first couple of changes.

Factorization (cont)

read Nread M

i=2while ( i <= N or i<=M )| | while ( isPrime(i) && i divides N)| || | list i <-- Do not list. Multiply. (use an accumulator)| | update N = N / i| || end while|| i = i + 1|end while


Recommended