SlideShare a Scribd company logo
1 of 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){
if (number < 0)
number = -number;
return number;}
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) {
if (number < 0)
number = -number;
cout<<number;
}
double larger(double x,
double y) {
double max;
if (x >= y)max = x;
else
max = y;
return max;
}
Void larger(double x, double
y) {
double max;
if (x >= y)
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
} // notice no semicolon
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) {
int c;
c = a+b;
return c;
}
Or you can simply put this in
the body
return (a+b);
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() {
cout << "x from main: " << x << "n";//5
cout << "y from main: " << y << “n“;//7
myFunction();//calling
return 0; }
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "n“;//5
cout << "y from myFunction: " << y << "n“;//10
Output:
x from main: 5
y from main: 7
x from myFunction: 5
y from myFunction: 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);
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“;
}
Output:
Main. Before swap, x: 5 y:
10
Swap. Before swap, x: 5 y:
10
Swap. After swap, x: 10 y:
5
Main. After swap, x: 5 y: 10
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;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
This ampersand(&) is what specifies
that their corresponding arguments
are to be passed by
reference instead of by value.
Output:
x=2, y=6, z=14
Cont’d
//Example on Pass By Reference using Reference(&)
#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);
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“; }
Output:
Main. Before swap, x: 5 y: 10
Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 10 y: 5
Cont’d
#include <iostream>
using namespace std;
void prevnext (int x, int &prev, int &next)
{
prev = x-1;
next = x+1;
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
The output is:
Previous=99, Next=101
Cont’d
// passing parameters by reference using Pointers(*)
#include <iostream>
using namespace std;
void duplicate (int *a, int *b, int *c) {
*a*=2;
*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; }
The output is:
x=2, y=6, z=14
Cont’d
#include <iostream>
using namespace std;
void prevnext (int x, int *prev, int *next)
{
*prev = x-1;
*next = x+1;
}
int main (){
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0; }
The output is:
Previous=99, Next=101
Cont’d
//Example on Pass By Reference using Pointer(*)
#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);
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“; }
Output:
Main. Before swap, x: 5 y: 10
Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 10 y: 5
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()
{
cout<<addition(5,2)<<endl;
cout<<addition(4);
return 0;
}
Output:
7
5
Cont’d
#include<iostream>
using namespace std;
int AreaOfCube (int height=1, int length=1, int width=1);
int main()
{
cout<< AreaOfCube ()<<endl;
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); }
Output:
1
2
8
48
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
return (i); }
float fabs(float x)
{
if(x<0.0)
return (x * -1.0);
else
return (x); }
Without using overloading, you have
to call the function as:
int ans = iabs(weight);//for int
arguments
float ans = fabs(weight);//for float
arguments
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)
return (i*-1);
else
return i; }
float abs(flaot x) {
if(x<0.0)
return (x*-1.0);
else
return x; }
N.B: if two or more functions differ
only in their return types, C++ can’t
overload them. Two or more
functions that differ only in their
return types must have different
names and can’t be overloaded
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>
using namespace std;
long factorial (long a) {
if (a > 1)
return (a * factorial (a-1));
else
return (1); }
int main () {
long num;
cout << "Type a number: ";
cin >> num;
cout << num <<"!“ << " = " << factorial (num);
retrun 0; }
If the user enter for eg. 4, then the
stack frames for these calls appear
sequentially on the runtime stack, one
after the other. Here is how it works:
Step 1: Factorial(4)
Step 2: 4 * Factorial(3)
Step 3: 4 * 3 * Factorial(2)
Step 4: 4 * 3 * 2 * Factorial(1)
Step 5: 4 * 3 * 2 * 1
Step 6: 4 * 3 * 2
Step 7: 4 * 6
Step 8: 24 The output will be:
Type a number: 4
4! = 24
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?

More Related Content

Similar to Chapter 1.ppt

Similar to Chapter 1.ppt (20)

Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Function
FunctionFunction
Function
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
 
Functions
Functions Functions
Functions
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
ACM init()- Day 4
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Functions
FunctionsFunctions
Functions
 

More from ethiouniverse

Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
chap4secondlawofthermodynamics-130703012656-phpapp01.ppt
chap4secondlawofthermodynamics-130703012656-phpapp01.pptchap4secondlawofthermodynamics-130703012656-phpapp01.ppt
chap4secondlawofthermodynamics-130703012656-phpapp01.pptethiouniverse
 
Addis abeb university ..Artificial intelligence .pptx
Addis abeb university ..Artificial intelligence .pptxAddis abeb university ..Artificial intelligence .pptx
Addis abeb university ..Artificial intelligence .pptxethiouniverse
 
Elementary Probability theory Chapter 2.pptx
Elementary Probability theory Chapter 2.pptxElementary Probability theory Chapter 2.pptx
Elementary Probability theory Chapter 2.pptxethiouniverse
 
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptx
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptxShort_note_Introduction_to_emerging_technologies_@QesemAcademy.pptx
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptxethiouniverse
 
Lecture 1 Introduction to Emerging Technology.pptx
Lecture 1 Introduction to Emerging Technology.pptxLecture 1 Introduction to Emerging Technology.pptx
Lecture 1 Introduction to Emerging Technology.pptxethiouniverse
 
Chapter three Hiostry of Electrical engineering.pptx
Chapter three Hiostry of Electrical engineering.pptxChapter three Hiostry of Electrical engineering.pptx
Chapter three Hiostry of Electrical engineering.pptxethiouniverse
 
electrical materialsand accessories ch2.pptx
electrical materialsand accessories ch2.pptxelectrical materialsand accessories ch2.pptx
electrical materialsand accessories ch2.pptxethiouniverse
 
Energy Transport by Heat, Work and Mass (1).ppt
Energy Transport by Heat, Work and Mass (1).pptEnergy Transport by Heat, Work and Mass (1).ppt
Energy Transport by Heat, Work and Mass (1).pptethiouniverse
 
Thermody Properties of Pure Substance (1).ppt
Thermody Properties of Pure Substance (1).pptThermody Properties of Pure Substance (1).ppt
Thermody Properties of Pure Substance (1).pptethiouniverse
 
Thermodynamics concepts chapter one.pptx
Thermodynamics concepts chapter one.pptxThermodynamics concepts chapter one.pptx
Thermodynamics concepts chapter one.pptxethiouniverse
 
CS Artificial Intelligence chapter 4.pptx
CS Artificial Intelligence chapter 4.pptxCS Artificial Intelligence chapter 4.pptx
CS Artificial Intelligence chapter 4.pptxethiouniverse
 
CS Artificial intelligence chapter 2.pptx
CS Artificial intelligence chapter 2.pptxCS Artificial intelligence chapter 2.pptx
CS Artificial intelligence chapter 2.pptxethiouniverse
 

More from ethiouniverse (13)

Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
chap4secondlawofthermodynamics-130703012656-phpapp01.ppt
chap4secondlawofthermodynamics-130703012656-phpapp01.pptchap4secondlawofthermodynamics-130703012656-phpapp01.ppt
chap4secondlawofthermodynamics-130703012656-phpapp01.ppt
 
Addis abeb university ..Artificial intelligence .pptx
Addis abeb university ..Artificial intelligence .pptxAddis abeb university ..Artificial intelligence .pptx
Addis abeb university ..Artificial intelligence .pptx
 
Elementary Probability theory Chapter 2.pptx
Elementary Probability theory Chapter 2.pptxElementary Probability theory Chapter 2.pptx
Elementary Probability theory Chapter 2.pptx
 
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptx
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptxShort_note_Introduction_to_emerging_technologies_@QesemAcademy.pptx
Short_note_Introduction_to_emerging_technologies_@QesemAcademy.pptx
 
Lecture 1 Introduction to Emerging Technology.pptx
Lecture 1 Introduction to Emerging Technology.pptxLecture 1 Introduction to Emerging Technology.pptx
Lecture 1 Introduction to Emerging Technology.pptx
 
Chapter three Hiostry of Electrical engineering.pptx
Chapter three Hiostry of Electrical engineering.pptxChapter three Hiostry of Electrical engineering.pptx
Chapter three Hiostry of Electrical engineering.pptx
 
electrical materialsand accessories ch2.pptx
electrical materialsand accessories ch2.pptxelectrical materialsand accessories ch2.pptx
electrical materialsand accessories ch2.pptx
 
Energy Transport by Heat, Work and Mass (1).ppt
Energy Transport by Heat, Work and Mass (1).pptEnergy Transport by Heat, Work and Mass (1).ppt
Energy Transport by Heat, Work and Mass (1).ppt
 
Thermody Properties of Pure Substance (1).ppt
Thermody Properties of Pure Substance (1).pptThermody Properties of Pure Substance (1).ppt
Thermody Properties of Pure Substance (1).ppt
 
Thermodynamics concepts chapter one.pptx
Thermodynamics concepts chapter one.pptxThermodynamics concepts chapter one.pptx
Thermodynamics concepts chapter one.pptx
 
CS Artificial Intelligence chapter 4.pptx
CS Artificial Intelligence chapter 4.pptxCS Artificial Intelligence chapter 4.pptx
CS Artificial Intelligence chapter 4.pptx
 
CS Artificial intelligence chapter 2.pptx
CS Artificial intelligence chapter 2.pptxCS Artificial intelligence chapter 2.pptx
CS Artificial intelligence chapter 2.pptx
 

Recently uploaded

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 

Recently uploaded (20)

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 

Chapter 1.ppt

  • 1. Computer Programming II Chapter One Function in C++
  • 2. 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.
  • 3. 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.
  • 4. 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.
  • 5. 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.
  • 6. 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.
  • 7. 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.
  • 8. Other predefined functions and their purpose
  • 10. 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
  • 11. Cont’d For Example:- int abs(int number){ if (number < 0) number = -number; return number;} 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) { if (number < 0) number = -number; cout<<number; } double larger(double x, double y) { double max; if (x >= y)max = x; else max = y; return max; } Void larger(double x, double y) { double max; if (x >= y) max = x; else max = y; Cout<<max; }
  • 12. 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{}.
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 16. 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);
  • 17. 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
  • 18. 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.
  • 19. 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.
  • 20. Cont’d Function definition (for a void function) General Form: void FunctionName( FormalParameterList ) { statement body of function -------- -------- }
  • 21. 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 { }.
  • 22. 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.
  • 23. 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.
  • 24. 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
  • 25. 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 } // notice no semicolon
  • 26. 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) { int c; c = a+b; return c; } Or you can simply put this in the body return (a+b);
  • 27. 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;
  • 28. 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.
  • 29. 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.
  • 30. 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() { cout << "x from main: " << x << "n";//5 cout << "y from main: " << y << “n“;//7 myFunction();//calling return 0; } void myFunction() { int y = 10; cout << "x from myFunction: " << x << "n“;//5 cout << "y from myFunction: " << y << "n“;//10 Output: x from main: 5 y from main: 7 x from myFunction: 5 y from myFunction: 10
  • 31. 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
  • 32. 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.
  • 33. 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
  • 34. 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.
  • 35. 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.
  • 36. 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
  • 37. 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.
  • 38. 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.
  • 39. 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.
  • 40. 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); 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“; } Output: Main. Before swap, x: 5 y: 10 Swap. Before swap, x: 5 y: 10 Swap. After swap, x: 10 y: 5 Main. After swap, x: 5 y: 10
  • 41. 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.
  • 42. 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; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; This ampersand(&) is what specifies that their corresponding arguments are to be passed by reference instead of by value. Output: x=2, y=6, z=14
  • 43. Cont’d //Example on Pass By Reference using Reference(&) #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); 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“; } Output: Main. Before swap, x: 5 y: 10 Swap. Before swap, x: 5 y: 10 Swap. After swap, x: 10 y: 5 Main. After swap, x: 10 y: 5
  • 44. Cont’d #include <iostream> using namespace std; void prevnext (int x, int &prev, int &next) { prev = x-1; next = x+1; } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } The output is: Previous=99, Next=101
  • 45. Cont’d // passing parameters by reference using Pointers(*) #include <iostream> using namespace std; void duplicate (int *a, int *b, int *c) { *a*=2; *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; } The output is: x=2, y=6, z=14
  • 46. Cont’d #include <iostream> using namespace std; void prevnext (int x, int *prev, int *next) { *prev = x-1; *next = x+1; } int main (){ int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } The output is: Previous=99, Next=101
  • 47. Cont’d //Example on Pass By Reference using Pointer(*) #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); 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“; } Output: Main. Before swap, x: 5 y: 10 Swap. Before swap, x: 5 y: 10 Swap. After swap, x: 10 y: 5 Main. After swap, x: 10 y: 5
  • 48. 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)
  • 49. 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 ; }
  • 50. 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.
  • 51. Cont’d #include<iostream> using namespace std; int addition(int a, int b=1) { return(a+b); } int main() { cout<<addition(5,2)<<endl; cout<<addition(4); return 0; } Output: 7 5
  • 52. Cont’d #include<iostream> using namespace std; int AreaOfCube (int height=1, int length=1, int width=1); int main() { cout<< AreaOfCube ()<<endl; 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); } Output: 1 2 8 48
  • 53. 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.
  • 54. 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 return (i); } float fabs(float x) { if(x<0.0) return (x * -1.0); else return (x); } Without using overloading, you have to call the function as: int ans = iabs(weight);//for int arguments float ans = fabs(weight);//for float arguments
  • 55. 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) return (i*-1); else return i; } float abs(flaot x) { if(x<0.0) return (x*-1.0); else return x; } N.B: if two or more functions differ only in their return types, C++ can’t overload them. Two or more functions that differ only in their return types must have different names and can’t be overloaded
  • 56. 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.
  • 57. 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; }
  • 58. 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.
  • 59. 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.
  • 60. Cont’d //example on recursive functions : factorial calculator #include <iostream> using namespace std; long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () { long num; cout << "Type a number: "; cin >> num; cout << num <<"!“ << " = " << factorial (num); retrun 0; } If the user enter for eg. 4, then the stack frames for these calls appear sequentially on the runtime stack, one after the other. Here is how it works: Step 1: Factorial(4) Step 2: 4 * Factorial(3) Step 3: 4 * 3 * Factorial(2) Step 4: 4 * 3 * 2 * Factorial(1) Step 5: 4 * 3 * 2 * 1 Step 6: 4 * 3 * 2 Step 7: 4 * 6 Step 8: 24 The output will be: Type a number: 4 4! = 24
  • 61. 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.
  • 62. 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.
  • 63. 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;}
  • 64. 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.