40
CS 101 Computer Programming and utilization Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Session 7, Functions in C++ Tuesday, August 16, 2011 And Wednesday, August 17, 2011 IIT BOMBAY Session 7, Functions

Dr Deepak B Phatak - Kanwal Rekhi€¦ · Dr. Deepak B Phatak 7. IIT BOMBAY. Finding real root, using a numerical method. Session 7, Functions • Make an initial guess, say ‘xguess’

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

CS 101Computer Programming and utilization

Dr Deepak B PhatakSubrao Nilekani Chair Professor

Department of CSE, Kanwal Rekhi BuildingIIT Bombay

Session 7, Functions in C++Tuesday, August 16, 2011

And Wednesday, August 17, 2011

IIT BOMBAY

Session 7, Functions

Dr. Deepak B Phatak 2

IIT BOMBAY

Session 7, Functions

Overview

• More about iterations– Break and continue statements– Another example of iterative solution

• Newton-Raphson method• ‘sub’ programs which can be invoked from anywhere

– ‘Functions’ in C++– Parameter passing– Function declaration

• Take home quiz

Dr. Deepak B Phatak 3

IIT BOMBAY

Need to come out of iteration

Session 7, Functions

• To abandon the iterative block completely, and to jump (break) out of iteration

Dr. Deepak B Phatak 4

IIT BOMBAY

To continue next iteration by skipping some code

Session 7, Functions

• Skip remaining statements within a iteration, and directly jump to continue with the next iteration

Dr. Deepak B Phatak 5

IIT BOMBAY

break and continue statements

Session 7, Functions

• BreakWhen used inside a loop control structure, break causes an immediate exit from the loop

• ContinueWhen executed inside a loop control structure, continue statement skips any remaining statements within the block, and goes for the next iteration

Dr. Deepak B Phatak 6

IIT BOMBAY

Finding a real root of an equation

Session 7, Functions

• ax2 + bx + c = 0– This equation could have real roots

• In general, for any function f(x), – a root is that value of x, for which f(x) =0

Dr. Deepak B Phatak 7

IIT BOMBAY

Finding real root, using a numerical method

Session 7, Functions

• Make an initial guess, say ‘xguess’• Use the properties of the function, to compute a new value, say,

‘xnew’, which should be closer to the root– ‘xnew’ is a better approximation to the root

Dr. Deepak B Phatak 8

IIT BOMBAY

Finding real root ...

Session 7, Functions

• An iteration can now be carried out– take ‘xnew’ as the initial guess,

xguess = xnew;– repeat the steps to find another approximation

Dr. Deepak B Phatak 9

IIT BOMBAY

How to find ‘xnew’

Session 7, Functions

• Newton-Raphson method uses the tangent– Derivative of the function should be known

Dr. Deepak B Phatak 10

IIT BOMBAY

Start with a point P (initial guess)

Session 7, Functions

xguessrootQ

y=f(x)

P

R

x

point P on x-axis Initial guess

Find some point Q Closer to root

How to find Q?

Note that length PR= f(xguess)

Dr. Deepak B Phatak 11

IIT BOMBAY

Determine Q, using tangent at R

Session 7, Functions

xguessrootQ

y=f(x)

xnewP

R

x

Draw tangent to curve at point R Q is the intersection of this tangent with x-axis

Dr. Deepak B Phatak 12

IIT BOMBAY

Coordinates of Q can now be calculated

Session 7, Functions

xguessrootQ

y=f(x)

xnewP

R

x

Tangent determined by derivative of function f’(x)

f’(xguess) = PR/PQ

PQ = PR / f’(xguess) = f(xguess) / f’(xguess)

xnew = xguess - PQ

Dr. Deepak B Phatak 13

IIT BOMBAY

For next iteration, move to the new point as initial guess

Session 7, Functions

rootP

y=f(x)

xguessx

Dr. Deepak B Phatak 14

IIT BOMBAY

Session 7, Functions

Find square root of a given number

• Consider that, for some x, k = x2; or x2 - k = 0

• We need to find a real root for the function f(x) = x2 - k, Note that f ’(x) = 2x

Dr. Deepak B Phatak 15

IIT BOMBAY

xguess and xnew

Session 7, Functions

• Start with xguess = 1, • Compute xnew = xguess - (xguess2 - k)/(2 *xguess)

= (xguess + k/xguess)/2

Dr. Deepak B Phatak 16

IIT BOMBAY

Block of statement to be repeated iteratively

Session 7, Functions

• ‘xnew’ is the modified value of ‘xguess’– to be used as ‘xguess’ for next iteration

• Instruction which we may repeatedly execute is identified as

x = (x + k/x)/2• In any iteration cycle

• Using the current value of x, compute its new value• to be used in the next iteration

Dr. Deepak B Phatak 17

IIT BOMBAY

Session 7, Functions

Termination criterion

• When do we stop iterating?– Perform a fixed number of iterations– Iterate while we are not close ‘enough’

• How to define ‘closeness’ or accuracy of the result?– We can get as close to the root (which is √ k ), as required.

Dr. Deepak B Phatak 18

IIT BOMBAY

Session 7, Functions

Accuracy of the calculated value of the root

0.0001Accuracy threshold

| f(x) | <= 0.0001

Dr. Deepak B Phatak 19

IIT BOMBAY

Termination criterion

Session 7, Functions

• Let the ‘closeness’ be defined as f(x) being within 0.0001• At the root value, f(x) will be exactly 0

– We wish to stop when f(x) is within ± 0.0001• This helps us define the termination criterion

– Keep repeating while | f(x) | > 0.0001 – otherwise, terminate the iterative loop

Dr. Deepak B Phatak 20

IIT BOMBAY

Session 7, Functions

The program

int main() {float k; float x=1;cout << “Give number whose square root is to be found ”;cin >> k;while (x*x – k > 0.0001 || k - x*x > 0.0001){

x = (x + k/x)/2 ;}cout << endl<< “Value of the root is ” << x << endl;return 0;

}

Dr. Deepak B Phatak 21

IIT BOMBAY

Finding root using a fixed number of iterations

Session 7, Functions

int main() {// calculating square root of a number kfloat k; float x=1; int i; cout << “Give number whose square root is to be found ”;cin >> k;for (i=1; i <= 10; i++){ // 10 iterations

x = (x + k/x)/2;}cout << x;return 0;

}

Dr. Deepak B Phatak 22

IIT BOMBAY

Using ‘for’ in a ‘while’ like fashion

Session 7, Functions

int main() {float x, k; cout << “Give value of k ”; cin >> k;for(x=1; (x*x – k > 0.0001) ||( k - x*x > 0.0001); x= (x+k/x)/2){}cout << x;return 0;

}

Dr. Deepak B Phatak 23

IIT BOMBAY

Using ‘for’ loop in a different way

Session 7, Functions

for(x=1; x*x – k > 0.0001 || k - x*x > 0.0001; x= (x+k/x)/2){}– Here x is ‘initialized’ to 1 before the loop– The ‘condition’ repeats the loop, while it is true– x is ‘incremented’ to reflect the new value calculated

• The use of for without a body is possible• Iterations will be executed as defined by the specifications• Since there is no body, all meaningful computations should

happen within the actions given in the 3 specifications

Dr. Deepak B Phatak 24

IIT BOMBAY

‘Functions’ in c++

Session 7, Functions

• a facility to compute value of a mathematical function for specified value(s) of some parameter(s)

• Consider a quadraticf(x) = ax2 + bx + c

• If we have to evaluate it for x=4 at one place in our program, and for x = 2.3 at another place, assigning the results to say, y1 and y2

• We will have to write two separate statements– Each statement will have to specify the

complete formula

Dr. Deepak B Phatak 25

IIT BOMBAY

‘Functions’ in c++ …

Session 7, Functions

• It would be useful if we could write the instructions to evaluate the formula separately, at some other place– And make the computer go to that place

whenever needed• In our main program, we would like to write:

y1 = quad(a, b, c, 4.0);--------y2 = quad(a, b, c, 2.3)

Dr. Deepak B Phatak 26

IIT BOMBAY

Functions in C++ …

Session 7, Functions

• Such a facility is provided by c++• Write instructions to compute value of a function

only once– Such a function accepts ‘parameters’– Calculates and returns the function value

• A function can be invoked from within a program– as many times as needed

Dr. Deepak B Phatak 27

IIT BOMBAY

Session 7, Functions

C++ Function to evaluate a Quadratic

• We need to evaluate the functionf(x) = ax2 + bx + c

Dr. Deepak B Phatak 28

IIT BOMBAY

Session 7, Functions

Our definition of ‘quad’ function

float quad (float a, float b, float c, float x){float value;value = a *x*x + b*x + c;return (value);

}

Dr. Deepak B Phatak 29

IIT BOMBAY

C++ rules

Session 7, Functions

• First word tells the type of the value which will be returned.

• Next is the name of the function, which we choose appropriately

• This is followed by one or more parameters whose values will come from the calling instruction

• The return statement sends back the value• In general, ‘value’ can be any expression

– It is evaluated when return statement is executed, the result value is sent back

Dr. Deepak B Phatak 30

IIT BOMBAYFunction invocation

• C++ compiler translates instructions written by us in a function definition separately– keeps these as an independent block

identified by our chosen name for the function• Function code is executed only when called

Let f (x) = 23.5 x 2 + 9.7 x + 12.6We want to calculate y = 574.6 * f(x) + 1.0/x

float x, y; - - -cin >> x;y = 574.6 * quad (23.5, 9.7, 12.6, x) + 1.0/x;

Session 7, Functions

Dr. Deepak B Phatak 31

IIT BOMBAY

C++ rules for function invocation

Session 7, Functions

• Within a program, a function is invoked simply by using the function name within any expression with appropriate parameters

• given parameters are copied to the respective locations in the function block

• Function code is now executed• value is returned to the calling program• returned value used in the expression

Dr. Deepak B Phatak 32

IIT BOMBAY

• Can we use programming code for functions written by others• Yes, of course, that is the very idea• We can even compile those functions

separately and link them with our program,• C++ has many rich ‘libraries’ of functions

• Each function is predefined • Our main program is actually treated as a

function by the operating system• We can now understand why we say

int main() { return 0;

Some points to ponder ...

Session 7, Functions

Dr. Deepak B Phatak 33

IIT BOMBAY

Example

Session 7, Functions

• We wish to evaluate the following v = (√m + √n) / √(m+n)

for some given values of m and n• Can we use our earlier program,

– Rewrite as a function sroot

• In our main program, we can writev = (sroot(m) + sroot(n)) / sroot(m+n);

Dr. Deepak B Phatak 34

IIT BOMBAY

Our function named ‘sroot’

Session 7, Functions

#include<iostream>using namespace std;float sroot( float k) {

float x=1;while ((x*x – k > 0.0001) || (k - x*x > 0.0001)){

x = (x + k/x)/2 ;}return x;

}

Dr. Deepak B Phatak 35

IIT BOMBAY

Use of the function root within the main program

Session 7, Functions

int main() {// calculating value of the given formulafloat m, n, v;cout << “Give values of m and n: ”; cin >> m >>n;v = (sroot(m) + sroot(n)) / sroot(m+n);cout << “Value of the formula is: ” << v;return 0;

}

Dr. Deepak B Phatak 36

IIT BOMBAY

Slot-wise students’ performance

Session 7, Functions

#include<iostream> using namespace std; double average(int, int); // prototype definitionint main(){int N5, N11; double slot5avg, slot11avg; cout << "No. of students in slot 5: "; cin >> N5; cout << "No. of students in slot 11: "; cin >> N11;slot5avg = average (5, N5); slot11avg = average(11, N11);if (slot5avg > slot11avg) cout << "slot 5 has performed better" <<

endl;else cout << "slot 11 has performed better" << endl;return 0;

}

Dr. Deepak B Phatak 37

IIT BOMBAY

Contd. ...

double average (int slot, int N){ //function definition int i; double marks, sum=0.0; for(i = 1; i <= N; i++){

cout <<" Give Marks for student no. " << i <<" in slot "; cout << slot << ": "; cin >> marks; sum += marks;

} return sum/N;

}

Session 7, Functions

Dr. Deepak B Phatak 38

IIT BOMBAY

Session 7, Functions

Dr. Deepak B Phatak 39

IIT BOMBAY

Session 7, Functions

Announcement

• From next week, M Sc Chemistry students will have their labs on Wednesday morning in OSL. The exact timing will be announced soon.

• Video recordings of previous lectures are kept on a server• These will be screened on Sunday mornings in room SIC 301,

Kanwal Rekhi Building, CSE dept. A Schedule will be announced each week. The Schedule for Sunday, 21 August 2011 is:– Session 5, Iterative algorithms 09:30 to 11:00– Session 6, Iterative solutions 11:00 to 12:30Students who have missed the lectures, or would like to attend for additional clarity, can attend with prior registration

Dr. Deepak B Phatak 40

IIT BOMBAY

Announcements

Session 7, Functions

• Discussion and consulting session as also the Make up lab will now be held on Sundays– Consulting session and Make up lab:

Sunday 14:00 to 18:00[OSL, ground floor, Maths department building]

• The seating arrangement in the regular lab will be announced on the moodle. Please follow these