CS 101
Computer Programming and utilization
IIT BOMBAY
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
Session 7, Functions
Overview
IIT
BOMBAY
• 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
Session 7, Functions
2
Need to come out of iteration
IIT
BOMBAY
• To abandon the iterative block completely, and to
jump (break) out of iteration
Dr. Deepak B Phatak
Session 7, Functions
3
To continue next iteration by skipping some code
IIT
BOMBAY
• Skip remaining statements within a iteration,
and directly jump to continue with the next
iteration
Dr. Deepak B Phatak
Session 7, Functions
4
break and continue statements
IIT
BOMBAY
• Break
When used inside a loop control structure,
break causes an immediate exit from the loop
• Continue
When 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
Session 7, Functions
5
Finding a real root of an equation
IIT
BOMBAY
• 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
Session 7, Functions
6
Finding real root, using a numerical method
IIT
BOMBAY
• 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
Session 7, Functions
7
Finding real root ...
IIT
BOMBAY
• 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
Session 7, Functions
8
How to find ‘xnew’
IIT
BOMBAY
• Newton-Raphson method uses the tangent
– Derivative of the function should be known
Dr. Deepak B Phatak
Session 7, Functions
9
Start with a point P (initial guess)
IIT
BOMBAY
point P on x-axis
Initial guess
Find some point Q
Closer to root
How to find Q?
y=f(x)
R
Q
root
Note that length PR
= f(xguess)
P
xguess
x
Dr. Deepak B Phatak
Session 7, Functions
10
Determine Q, using tangent at R
IIT
BOMBAY
Draw tangent to curve
at point R
Q is the intersection of
this tangent with x-axis
y=f(x)
R
Q
root
xnew
P
xguess
x
Dr. Deepak B Phatak
Session 7, Functions
11
Coordinates of Q can now be calculated
IIT
BOMBAY
Tangent determined by
derivative of function f’(x)
y=f(x)
R
f’(xguess) = PR/PQ
PQ = PR / f’(xguess)
= f(xguess) / f’(xguess)
xnew = xguess - PQ
Q
root
xnew
P
xguess
x
Dr. Deepak B Phatak
Session 7, Functions
12
For next iteration, move to the new point as initial guess
IIT
BOMBAY
y=f(x)
P
root
xguess
x
Dr. Deepak B Phatak
Session 7, Functions
13
Find square root of a given number
IIT
BOMBAY
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
• Consider that, for some x,
Dr. Deepak B Phatak
Session 7, Functions
14
xguess and xnew
IIT
BOMBAY
• Start with xguess = 1,
• Compute xnew = xguess - (xguess2 - k)/(2 *xguess)
= (xguess + k/xguess)/2
Dr. Deepak B Phatak
Session 7, Functions
15
Block of statement to be repeated iteratively
IIT
BOMBAY
• ‘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
Session 7, Functions
16
Termination criterion
IIT
BOMBAY
• 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
Session 7, Functions
17
Accuracy of the calculated value of the root
IIT
BOMBAY
Accuracy threshold
0.0001
| f(x) | <= 0.0001
Dr. Deepak B Phatak
Session 7, Functions
18
Termination criterion
IIT
BOMBAY
• 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
Session 7, Functions
19
The program
IIT
BOMBAY
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
Session 7, Functions
20
Finding root using a fixed number of iterations
IIT
BOMBAY
int main() {
// calculating square root of a number k
float 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
Session 7, Functions
21
Using ‘for’ in a ‘while’ like fashion
IIT
BOMBAY
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
Session 7, Functions
22
Using ‘for’ loop in a different way
IIT
BOMBAY
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
Session 7, Functions
23
‘Functions’ in c++
IIT
BOMBAY
• a facility to compute value of a mathematical
function for specified value(s) of some
parameter(s)
• Consider a quadratic
f(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
Session 7, Functions
24
‘Functions’ in c++ …
IIT
BOMBAY
• 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
Session 7, Functions
25
Functions in C++ …
IIT
BOMBAY
• 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
Session 7, Functions
26
C++ Function to evaluate a Quadratic
IIT
BOMBAY
• We need to evaluate the function
f(x) = ax2 + bx + c
Dr. Deepak B Phatak
Session 7, Functions
27
Our definition of ‘quad’ function
IIT
BOMBAY
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
Session 7, Functions
28
C++ rules
IIT
BOMBAY
• 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
Session 7, Functions
29
Function invocation
IIT
BOMBAY
• 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.6
We 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;
Dr. Deepak B Phatak
Session 7, Functions
30
C++ rules for function invocation
IIT
BOMBAY
• 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
Session 7, Functions
31
Some points to ponder ...
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;
Dr. Deepak B Phatak
Session 7, Functions
32
Example
IIT
BOMBAY
• 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 write
v = (sroot(m) + sroot(n)) / sroot(m+n);
Dr. Deepak B Phatak
Session 7, Functions
33
Our function named ‘sroot’
IIT
BOMBAY
#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
Session 7, Functions
34
Use of the function root within the main program
IIT
BOMBAY
int main() {
// calculating value of the given formula
float 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
Session 7, Functions
35
Slot-wise students’ performance
IIT
BOMBAY
#include<iostream>
using namespace std;
double average(int, int); // prototype definition
int 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
Session 7, Functions
36
Contd. ...
IIT
BOMBAY
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;
}
Dr. Deepak B Phatak
Session 7, Functions
37
IIT
BOMBAY
Dr. Deepak B Phatak
Session 7, Functions
38
Announcement
IIT
BOMBAY
• 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:30
Students who have missed the lectures, or would like to attend
for additional clarity, can attend with prior registration
Dr. Deepak B Phatak
Session 7, Functions
39
Announcements
IIT
BOMBAY
• 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
Dr. Deepak B Phatak
Session 7, Functions
40
© Copyright 2026 Paperzz