Chapter 1

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 65

Computer Programming II

Chapter One
Function in C++
Why Function?

 You can simplify programming tasks by breaking programs into


smaller logical components.
 Function are used for dividing a large code into module, due to this
we can easily debug and maintain the code.
E.g. if we write a calculator programs at that time we can write every
logic in a separate function [For addition sum(), for subtraction
sub()].
 Any function can be called many times.
 Code Re-usability
 Develop an application in module format.
 Easy to debug the program.
 Code optimization: No need to write lot of code.
Function

is like building blocks designed to tackle a specific


problem.
Every C++ program has atleast one function, main().
When your program starts, main() is called
automatically. main () might call other functions, some
of which might call still others.
Often, your program needs to interrupt what it is doing
to temporarily do something else. You do this in real life
all the time. For example, you might be reading a book
when you remember you need to make a phone call.
Cont’d

 You put a bookmark in your book, make the phone call, and
when you are done with the phone call, you return to your book
where you left off.
 Each function has its own name, and when that name is
encountered, the execution of the program branches to the body
of that function. When the function returns, execution resumes on
the next line of the calling function.
Cont’d

Function let you divide complicated programs into manageable


pieces. They have other advantages, too:
 While working on one function, you can focus on just that part
of the program and construct it, debug it, and perfect it.
 Different people can work on different functions simultaneously.
 If a function is needed in more than one place in a
program(s),you can write it once & use it many times.
 Using functions greatly enhances the program’s readability
because it reduces function complexity.
Function basics

 One of the best ways to tackle a problem is to start with


the overall goal(Top-down approach), then divide this
goal into several smaller tasks. You should never lose
sight of the overall goal, but think also of how individual
pieces can fit together to accomplish such a goal.
 If your program does a lot, break it into several functions.
Each function should do only one primary task.
Varieties of function

Built-in(predefined) function
are part of your compiler package in which they are
supplied by the manufacturer for your use.
Some of the predefined functions are pow(x, y), sqrt(x),
and floor(x) which calculates the largest whole number that
is less than or equal to x. For Ex:- pow(2, 3)= 8.0, sqrt(2.25)
is 1.5, floor(48.79) is 48.0.
N.B To use predefined function in a program, you must
include the header file (cmath and cctype) that contains the
function specification.
Other predefined functions and their purpose
Example
Varieties Of Function Cont’d

User-defined functions are functions which are defined by you


(the programmers). User-defined functions in C++ are
classified into two categories:
A)Value-returning functions:-functions that have a return type.
These functions return a value of a specific data type using the
return statement, which we will explain shortly.
• The value returned by a value-returning function is unique.
value-returning function is used:
-In an assignment statement. E.g x = add(3, 2.5);
-As a parameter in a function call y=PI*per(l+w);
- In an output statement. cout << abs(-5) << endl
Cont’d

For Example:- int abs(int number){ double larger(double x,


if (number < 0) double y) {
double max;
number = -number; if (x >= y)max = x;
else
return number;} max = y;
return max;
}
Void functions:-functions that do not have a return type. These
functions do not use a return statement to return a value.
For Example:- void abs(int number) { Void larger(double x, double y)
{
if (number < 0)
double max;
number = -number; if (x >= y)
cout<<number; max = x;
else
} max = y;
Cout<<max;
}
Cont’d

1. Every function must have a name.


2. Function names are made up and assigned by the
programmer following the same rules that apply to
naming variables. They can contain up to 32 characters,
3. All function names have one set of parenthesis(). This
helps you (and C++ compiler) differentiate them from
variables.
4. The body of each function, starting immediately after
parenthesis of the function name, must be enclosed by
braces{}.
Declaring and Defining Functions

Function Declaration( prototypes)?


 In C++ all functions must be declared before they are used. This
is accomplished using function prototype.
 Function prototype is a function declaration that specify the
return type and the argument types
 In c++ function prototype is a model of actual function.
 Prototypes enable complier to provide stronger type checking.
 When prototype is used, the compiler can find and report any
illegal type conversions between the type of arguments used to
call a function and the type definition of its parameters.
Declaring the Function

It can also find the difference between the no of


arguments used to call a function and the number of
parameters in the function.
Thus function prototypes help us trap bugs before they
occur. In addition, they help verify that your program is
working correctly by not allowing functions to be called
with mismatched arguments.
The interface of a function (prototype) specifies how
it may be used.
Function Prototype

 Function Prototype Syntax:


return_type function_name ( [type [parameterName1], type
[parameterName2]]...);
e.g int add(int a,int b);
 A prototype always ends with a semicolon (;).
1. The function return type. This specifies the type of value the
function returns. A function which returns nothing should have a
return type void.
2. The function name. this is simply a unique identifier
3. The function parameters (also called its signature). This is a set
of zero or more typed identifiers used for passing values to and
from the function.
Cont’d

 The function prototype and the function definition must

agree exactly about the return type, the name, and the
parameter list. If they do not agree, you will get a
compile-time error.
 The function prototype does not need to contain the

names of the parameters. Simply listing their types is


enough.

long Area(int, int);


Cont’d

 Although this is legal, it is not a good idea. Adding parameter


names makes your prototype clearer.
long Area(int length, int width);
 Note that all functions have a return type. If none is explicitly
stated, the return type defaults to int.
Function Prototype Examples
 long FindArea(long length, long width); //returns long, has two
parameters
 void PrintMessage(int messageNumber);// returns void, has one
parameter
 int GetChoice(); // returns int, has no parameters
Definition of Function

 The function definition is a listing of the actual instructions that


should be executed in the function
 There are three ways to definition function:
1. Write your prototype into a file, and then use the #include
directive to include it in your program.
2. Write the prototype into the file in which your function is
used.
3. Define the function before it is called by any other function.
When you do this, the definition acts as its own declaration.
 The third way looks easy because you don’t need to
declare, but it is not good programming practice.
Cont’d

 The definition of a function consists of the function header and


its body. The body of the function is a set of statements enclosed
in braces{}.
Function Definition Syntax
return_type function_name ( [type parameterName1], [type
parameterName2]...)
{
statements;
}
N.B If function definition is done before the main function, then
there is no need to put the prototype, otherwise the prototype
should be scripted/written before the main.
Cont’d

Function definition (for a void function)


General Form:
void FunctionName( FormalParameterList )
{
statement body of
function
--------
--------
}
Cont’d

N.B
 All functions have a return type. If none is explicitly stated,
the return type defaults to int.
 Function prototype - a function declaration that does not include
the body of the function and ends with ;.
 Function definition – a function declaration that includes the
body of the function with in { }.
Exercise

1. Write a value returning function that receives three integers and returns
the largest of the three. Assume the integers are not equal to one
another.
2. Write a value returning function that receives two floating point
numbers and returns true if the first formal parameter is smaller than
the second.
3. Write a value returning function that receives a character and returns
true if the character is a vowel and false otherwise. For this example,
vowels include the characters ‘A/a', ‘E/e', ‘I/i', ‘O/o', and ‘U/u‘.
4. Do the above exercise(1-3) in a void function.
5. Write a void function that receives an integer values and outputs
the message palindrome if a number is palindrome number,
unless it displays a message as number is not palindrome.
Calling the function

 Calling a function means making the instruction of the function


to be executed.
 A function call consists of the function name followed by the call
operator brackets ‘()’, inside which zero or more comma-
separated arguments appear depending up on number of formal
parameters. The number and type of arguments should match the
number of function parameters.
 When a function call is executed, the arguments are first
evaluated and their resulting values are assigned to the
corresponding parameters. The function body is then executed.
Finally the return value (if any) is passed to the caller.
General format

# include<iostream>
using namespace std;
void func1(); //prototype of function definition
int main()
{
……
func1();//function call (notice the semicolon)
……
}
void func1() // notice no semicolon
{ function
function body definition

} // notice no semicolon
Example

# include<iostream>
using namespace std;
void Greeting(); //prototype of function definition
int main()
{
Greeting();//function call (notice the semicolon)
Cout<<“hello again”;
cout<<“I wanna say ”;
return 0;
}
void Greeting() // notice no semicolon in function definition .
{
cout<<“Well come to Interesting class!”;// function body
example

# include<iostream>
Using namespace std;
int Sum(int, int);
Int main() {
int x, y, result ;
cout<<“Enter two integers to get their sum ”;
cin>>x>>y;
result = Sum(x,y); //function call (notice the semicolon)
cout<<“\n The sum is : ”<<result;
return 0;
}
int Sum(int a, int b) { Or you can simply put this in
int c; the body
c = a+b; return (a+b);
return c;
}
Example (without prototype)

# include<iostream>
using namespace std;
int Sum(int a, int b){
int c;
c = a+b;
return c;
}
int main(){
int x, y, result ;
cout<<“Enter two integers to get their sum ”;
cin>>x>>y;
result = Sum(x,y); //function call (notice the semicolon)
cout<<“\n The sum is : ”<<result;
return 0;
Scope of variables

 Scope can be defined as a range of lines in a program in which


any variables that are defined remain valid.
 A variable scope determines how long it is available to your
program and where it can be accessed.
 Scope delimiters are the curly braces { and }
 There are two scopes Local and Global.
A Local variables - exist only locally within the function itself.
When the function returns, the local variables are no longer
available. So Variables declared within the function are said to
have "local scope." That means that they are visible and usable
only within the function in which they are defined.
Cont’d

B Global variables - Variables defined outside of any


function have global scope and thus are available for any
function in the program, including main().
Local variables with the same name as global variables
do not change the global variables.
A local variable with the same name as a global variable
hides the global variable.
If a function has a variable with the same name as a
global variable, the name refers to the local variable--not
the global--when used within the function.
Cont’d

//Example on global and local variables


#include <iostream>
using namespace std;
void myFunction(); // prototype
int x = 5, y = 7; // global variables
int main() { Output:
cout << "x from main: " << x << "\n";//5 x from main: 5
cout << "y from main: " << y << “\n“;//7 y from main: 7
myFunction();//calling x from myFunction: 5
return 0; } y from myFunction: 10
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "\n“;//5
cout << "y from myFunction: " << y << "\n“;//10
}
Scope resolution operator

 When a local variable has the same name as a global variable, all
references to the variable name made with in the scope of the
local variable access the local variable
# include<iostream>
using namespace std;
float num = 42.8; //global variable
int main()
{
float num = 26.4; //local variable
cout<<”the value of num is:”<<num<<endl;
return 0; The output :the value of num is: 26.4
}
Cont’d

 As shown by the above output, the local variable


name takes precedence over the global variable.
 In such cases, we can still access the global variable
by using C++’s scope resolution operator (::).
 This operator must be placed immediately before the
variable name, as in ::num. When used in this
manner, the :: tells the compiler to use global
variable.
 The scope resolution operator causes the global,
rather the local variable to be accessed.
Cont’d

# include<iostream>
using namespace std;
float num = 42.8; //global variable
int main()
{
float num = 26.4; //local variable
cout<<”the value of num is:”<< ::num<<endl;
return 0;
} The output is: the value of the number is 42.8
Function arguments

 Any valid C++ expression can be a function


argument, including constants, mathematical and
logical expressions, and other functions that return a
value.
 You can also use Functions as Parameters to
Functions.
 Although it is legal for one function to take as a
parameter a second function that returns a value, it
can make your code hard to read and debug.
 Let’s see an example.
Cont’d

 Say you have the functions double(), triple(), square(),


and cube(), each of which returns a value.
 You could write
Answer = (double(triple(square(cube(myValue))))); This
statement takes a variable, myValue, and passes it as an
argument to the function cube(), whose return value is
passed as an argument to the function square(), whose
return value is in turn passed to triple(), and that return
value is passed to double().
 The return value of this doubled, tripled, squared, and
cubed number is now passed to Answer.
Cont’d

If the answer is wrong it will be hard to figure out


which function failed. An alternative is to assign each
step to its own intermediate variable:
unsigned long myValue = 2;
unsigned long cubed = cube(myValue); // cubed = 8
unsigned long squared = square(cubed); // squared=64
unsigned long tripled = triple(squared);// tripled = 192
unsigned long Answer = double(tripled);
// Answer=384
Passing arguments

There are two ways of passing arguments to functions,


i.e. Pass by Value & Pass by Reference
1) Pass by Value
The arguments passed in to the function are local to the
function. Changes made to the arguments do not affect
the values in the calling function. This is known as
passing by value, which means a local copy of each
argument is made in the function. These local copies are
treated just like any other local variables.
Cont’d

when calling a function with parameters, what we have


passed to the function were copies of their values but
never the variables themselves. For example, suppose
that we called our first function addition using the
following code:
int x=5, y=3, z;
z = addition ( x , y );
What we did in this case was to call to function
addition passing the values of x and y,
i.e. 5 and 3 respectively, but not the
variables x and y themselves.
Cont’d

This way, when the function addition is called, the


value of its local
variables a and b become 5 and 3 respectively, but any
modification to either a or b within the function addition
will not have any effect in the values of x and y outside
it, because variables x and y were not themselves passed
to the function, but only copies of their values at the
moment the function was called.
Cont’d

#include <iostream>
using namespace std;
void swap(int x, int y);
int main(){
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n“;
swap(x,y); Output:
cout << "Main. After swap, x: " << x << " y: " <<y << "\n“; Main. Before swap, x: 5 y:
return 0; 10
} Swap. Before swap, x: 5 y:
void swap (int x, int y) 10
{ Swap. After swap, x: 10 y: 5
int temp; Main. After swap, x: 5 y: 10
cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n“;
temp=x;
x=y;
y=temp;
cout << "Swap. After swap, x: " << x << " y: " << y << "\n“;
}
Cont’d

2) Pass by Reference
 In C++, passing by reference is accomplished in two ways: using
pointers and using references. The syntax is different, but the
net effect is the same. Rather than a copy being created within the
scope of the function, the actual original object is passed into the
function. Passing an object by reference allows the function to
change the object being referred to.
 When a variable is passed by reference we are not passing a copy
of its value, but we are somehow passing the variable itself to the
function and any modification that we do to the local variables
will have an effect in their counterpart variables passed as
arguments in the call to the function.
Cont’d

// passing parameters by reference using Reference(&)


#include <iostream>
using namespace std;
void duplicate (int &a, int &b, int &c)
{
a*=2;
b*=2;
This ampersand(&) is what specifies
c*=2; that their corresponding arguments
} are to be passed by
int main () reference instead of by value.
{
int x=1, y=3, z=7;
Output:
duplicate (x, y, z);
x=2, y=6, z=14
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
Cont’d

//Example on Pass By Reference using Reference(&)


Output:
#include <iostream> Main. Before swap, x: 5 y: 10
using namespace std; Swap. Before swap, x: 5 y: 10
void swap(int &x, int &y); Swap. After swap, x: 10 y: 5
int main(){ Main. After swap, x: 10 y: 5
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n“;
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n“;
return 0; }
void swap (int &x, int &y) {
int temp;
cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n“;
temp = x;
x = y;
y = temp;
cout << "Swap. After swap, x: " << x << " y: " << y << "\n“; }
Cont’d

#include <iostream>
using namespace std;
void prevnext (int x, int &prev, int &next)
{
prev = x-1; The output is:
next = x+1; Previous=99, Next=101
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
Cont’d

// passing parameters by reference using Pointers(*)


#include <iostream>
using namespace std;
void duplicate (int *a, int *b, int *c) {
The output is:
*a*=2;
x=2, y=6, z=14
*b*=2;
*c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (&x, &y,&z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0; }
Cont’d

#include <iostream>
using namespace std;
void prevnext (int x, int *prev, int *next)
{
*prev = x-1; The output is:
*next = x+1; Previous=99, Next=101
}
int main (){
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0; }
Cont’d

//Example on Pass By Reference using Pointer(*)


Output:
#include <iostream>
Main. Before swap, x: 5 y: 10
using namespace std;
Swap. Before swap, x: 5 y: 10
void swap(int *x, int *y);
Swap. After swap, x: 10 y: 5
int main(){ Main. After swap, x: 10 y: 5
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n“;
swap(&x,&y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n“;
return 0; }
void swap (int *x, int *y) {
int temp;
cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n“;
temp = *x;
*x = *y;
*y = temp;
cout << "Swap. After swap, x: " << x << " y: " << y << "\n“; }
Return values

 Functions return a value or return void. Void is a signal to


the compiler that no value will be returned.
 To return a value from a function, write the keyword
return followed by the value you want to return. The value
might itself be an expression that returns a value. For
example:
return 5;
return (MyFunction());
return (a+b)
Cont’d

#include<iostream>
using namespace std;
float AreaOfCircle(int r){
float pie = 3.14;
return (pie*r*r);}
float AreaOfCylinder(int Area, int h) {
return(Area*h);}
void main(){
float radius = 4.0, h= 2.0, CylinderArea ;
CylinderArea = AreaOfCylinder(AreaOfCircle(radius), h);
cout<<“The area of the cylinder is : ” << CylinderArea ;
}
Default parameters

 In C++, you can give a parameter default value that is automatically


used when no argument corresponding to that parameter is specified in
a call to a function.
 Default arguments can be used to simplify calls to complex functions.
Also, they can sometimes be used as a "shorthand" form of function
overloading.
 Default argument is a programming convenience which removes the
burden of having to specify argument values for all function
parameters.
 The use of default arguments is defaulting common initial values is
convenient than not having.
 DON'T try to create a default value for a first parameter if there is no
default value for the second.
Cont’d

#include<iostream>
using namespace std;
int addition(int a, int b=1)
{
return(a+b);
}
int main()
{ Output:
cout<<addition(5,2)<<endl; 7
5
cout<<addition(4);
return 0;
}
Cont’d

#include<iostream>
using namespace std;
int AreaOfCube (int height=1, int length=1, int width=1); Output:
int main() 1
2
{
8
cout<< AreaOfCube ()<<endl; 48
cout<< AreaOfCube ( 2) <<endl;
cout<< AreaOfCube (2,4) <<endl;
cout<< AreaOfCube (2,4,6);
}
int AreaOfCube (int height , int length, int width )
{
return(height* length*width); }
Overloaded functions

Unlike C, C++ lets you have more than one function


with the same name.
Functions with the same name are called overloaded
functions. C++ requires that each overloaded functions
differ in its argument list.
Overloaded functions enable you to have similar
functions that work on different types of data.
Cont’d

 Suppose that you wrote a function that returned the absolute value of what
ever number you passed to it:
int iabs(int i) {
if(i<0)
return (i*-1);
else Without using overloading, you have
return (i); } to call the function as:
float fabs(float x)
int ans = iabs(weight);//for int
{
arguments
if(x<0.0)
float ans = fabs(weight);//for float
return (x * -1.0);
arguments
else
return (x); }
Cont’d

 But with overloading, the above code can be used as:


int abs(int i);
float abs(float x);
int main() {

ians = abs(i); //calling abs with int arguments
fans = abs(p); //calling abs with float arguments
… }
int abs(int i) {
if(i<0) N.B: if two or more functions differ
return (i*-1); only in their return types, C++ can’t
else
overload them. Two or more
return i; }
functions that differ only in their
float abs(flaot x) {
return types must have different
if(x<0.0)
names and can’t be overloaded
return (x*-1.0);
else
return x; }
Passing array to function

 At some moment we may need to pass an array to a function as a


parameter.
 In C++ it is not possible to pass a complete block of memory by value
as a parameter to a function, but we are allowed to pass its address.
 In practice this has almost the same effect and it is a much faster and
more efficient operation.
 In order to accept arrays as parameters the only thing that we have to
do when declaring the function is to specify in its parameters the
element type of the array, an identifier and a pair of void brackets [].
 For example, the following function:

 accepts a parameter of type "array of int" called arg.


Cont’d

 In order to pass to this function an array declared as:


int myarray [40];
 it would be enough to write a call like this: procedure (myarray);
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n"; }
int main () {
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0; }
Cont’d

 As you can see, the first parameter (int arg[]) accepts


any array whose elements are of type int, whatever its
length.
 For that reason we have included a second parameter
that tells the function the length of each array that we
pass to it as its first parameter.
 This allows the for loop that prints out the array to
know the range to iterate in the passed array without
going out of range.
Recursive functions

 A function which calls itself is said to be recursive.


 Recursion is a general programming technique applicable to
problems which can be defined in terms of themselves. Take the
factorial problem, for instance which is defined as:
 factorial of 0 is 1

 factorial of a positive number n is n time the factorial of n-1.

 The second line clearly indicates that factorial is defined in terms


of itself and hence can be expressed as a recursive function.
Cont’d

//example on recursive functions : factorial calculator


#include <iostream>
If the user enter for eg. 4, then the
using namespace std; stack frames for these calls appear
long factorial (long a) { sequentially on the runtime stack, one
if (a > 1) after the other. Here is how it works:
Step 1: Factorial(4)
return (a * factorial (a-1));
Step 2: 4 * Factorial(3)
else Step 3: 4 * 3 * Factorial(2)
return (1); } Step 4: 4 * 3 * 2 * Factorial(1)
int main () { Step 5: 4 * 3 * 2 * 1
Step 6: 4 * 3 * 2
long num; Step 7: 4 * 6
cout << "Type a number: "; Step 8: 24 The output will be:
cin >> num; Type a number: 4
cout << num <<"!“ << " = " << factorial (num); 4! = 24
retrun 0; }
Cont’d

 The three necessary components in a recursive method are:


1. A test to stop or continue the recursion
2. An end case that terminates the recursion
3. A recursive call(s) that continues the recursion

 A recursive function must have at least one termination condition


which can be satisfied. Otherwise, the function will call itself
indefinitely until the runtime stack overflows.
Cont’d

 Both iteration and recursion are based on control structure. Iteration


uses a repetition structure (such as for, while, do…while) and recursive
uses a selection structure (if, if else or switch).
 Both iteration and recursive can execute infinitely-an infinite loop
occurs with iteration if the loop continuation test become false and
infinite recursion occurs if the recursion step doesn’t reduce the
problem in a manner that coverage on a base case.
 Recursion has disadvantage as well. It repeatedly invokes the
mechanism, and consequently the overhead of method calls. This can
be costly in both processor time and memory space. Each recursive call
creates another copy of the method (actually, only the function’s
variables); this consumes considerable memory.
Cont’d

#include<iostream>
using namespace std;
void CountDown(int nValue)
{
cout << nValue << endl;
if (nValue > 0) // termination condition
CountDown(nValue-1);
}
int main(){
CountDown(10);
return 0;}
Cont’d

 N.B: Use recursion if:


1. A recursive solution is natural and easy to understand
2. A recursive solution doesn’t result in excessive duplicate
computation.
3. The equivalent iterative solution is too complex.
Any Question?

You might also like