WHAT IS A FUNCTION
Function Declaration
SCOPE OF VARIABLES
INTERACTION BETWEEN FUNCTIONS
(a) Call by Value
(d) const Parameters
(e) Default Argument
INLINE FUNCTIONS
OVERLOADED FUNCTIONS
RECURSION
WHAT IS A FUNCTION
A Function is a predefined block of executable code that provides solution to smaller or micro tasks. Functions are called within programs and can be reused by one or many programs. A program can send values (called parameters) into the function for processing the task, and the function can send the processed result (called return value) back to the program from where it was called. Functions are the building blocks of C++ where all program activity occurs. Using functions we can structure our programs in a modular way. Syntax for a function is:
data-type function_name
( parameter1, parameter2, ...)
{
statement
}
where, data type specifies the type of data that is returned by this function to the program from where it was called. function_name is an identifier or name of the function by which it can be called. parameter1, parameter 2, … etc comprise of a data-type specifier followed by an identifier, like any regular variable declaration (for example: int x) and they act within the function as a regular local variable. They allow to pass arguments to the function when it is called from a program. Different parameters are separated by commas. All function parameters must be declared individually. statement is the function’s body having a block of statements enclosed by curly braces.
For
example, below is a function named fn that executes some program statements. It makes use of 2 integer
parameters i, j for
computations and finally returns an integer value as result
to the calling program.
int fn ( int i, int j )
{
program statements;
}
Types of Functions : There are 4 type of functions:
1.
Function with no parameter and no return value
2.
Function with no parameter and with return value
3.
Function with one or more parameters and no return value
4. Function with one or more parameters and with return value
Function
Declaration: A function declaration informs the
compiler about the function to be used in
the program. It is specified by function name, return type,
and parameters. It ends with a semicolon. In most C++
compilers, function declaration is not a
must if the function definition comes before main()
Example: int fn ( int i, int j );
Function Definition: A function definition provides actual body of the function and contains the functional code.
Example:
int fn ( int i, int j )
{
program statements;
}
PROGRAM 46
Q. Write a
program to print sum of 2 numbers using function. Pass 2 integer parameters
into a function that returns sum of the 2 numbers.
#include <iostream> using namespace std;
int addition (int a, int b) { int
s; s =
a+b; cout <<
"I am inside Function\n"; return (s); }
main () { int sum; sum
= addition (5,3); cout
<< "The result is " << sum; } |
OUTPUT
I am inside Function .
The result is 8 .
In the above program, you declare the function named addition which will be provided with 2 integer values a and b from the main program. These two values have to be added up,
stored in local variable s and
returned back to the calling program. The calling program (main program) will
receive the value in its local variable sum
and then prints the result.
We can see how the main function begins by declaring the variable sum of type int. Next, we see the call to a function named addition which has been passed with 2 parameter values: 5, 3
Within the main function we have called the function named addition passing two values 5 and 3, that correspond to int a, int b parameters declared within the function named addition.
At the point at which the function is called from within main program, the control is lost by main program
and passed onto the function addition. The value of both arguments passed in the call (5
and 3) are copied to the local variables int a and int b within
the function.
Function
addition declares another local variable (int s), and by
means of the expression s = a+b, it assigns value of a+b to s. Since a = 5 and b = 3, value
in s = 8. Now this
value has to be send to main program for printing. The following line of code
will return the value of s to the main function:
return (s);
The
value that was send from the function is received in the main program and
assigned to the variable sum. The following line of code in main prints the result onto the
screen:
cout << “The result is “ << sum;
SCOPE OF VARIABLES
The scope of variables declared within a function or any other inner block is only within that function or block and cannot be used outside it. Variables that can only be accessed within functions or blocks of code, are called Local variables. From the previous example (Program 46), it would have been impossible to use the variables a, b or s directly within main function since they are variables local to the function addition. Similarly, it would have been impossible to use the variable sum directly within function addition, since this is a variable that is within (local to) the main function.
PROGRAM 47
Q. Write a
function to multiply 2 numbers. From main program, pass required parameters
into the function and get a return value. Parameters have to be send to the
function:
(1) as numeric
values,
(2) as
variables.
#include <iostream> #include <iomanip> using namespace std; int multiply (int a, int b) { int m; m=a*b; return (m); } main () { int
x=5, y=8, z; z = multiply (7,9); cout << "Passing by Value Result
is : " << z << endl; cout
<< "Passing by Variable Result is: " << multiply (x,y) << endl; } |
OUTPUT
INTERACTION BETWEEN FUNCTIONS
As learned
earlier, function is a predefined block of code that provides solution to
smaller or micro tasks and they can be reused by one or many programs. Programs
interact with functions by calling the function at specific point of the
program to perform the task. When a function is called, the program may send
values (for processing) as parameters into the function and the function may
return a result back to the program. Passing
of parameters to the function is carried out by these common methods:
a. Call by Value b.
Call by Reference c. Passing of Pointers
d. Constant Parameters e. Default Arguments
(a) Call
by Value
In this method, parameters are send to a
function as actual-values or values-in-variables. Within the function, these values are copied into variables that
are local to the function. Any changes made to these variables in the function,
do not get affected in the main/parent program. Let’s get it clarified by a
simple program.
PROGRAM 48
Q. Write a program to initialize an int variable. Print it. Pass it to a function using Call by Value. Increment it. Print it from function. Return back to main program. Print the variable.
#include <iostream> using namespace std; void fn (int n) {
++n; cout << "Number in fn function
after increment : " << n << "\n"; } main ( ) {
int n = 2;
cout << "Number in main() before function call : " <<n <<"\n";
fn (n);
cout<< "Number in main() after function call : " << n; } |
OUTPUT
#include <iostream> using namespace std; fn (float &b, float d) { b+=
d; } main ()
{ float balance = 100000, deposit; cout<<"Your Account balance is: Rs. "<<balance<<"\n"; cout<<"Enter Amount to Deposit: Rs. "; cin
>> deposit; fn
(balance, deposit); cout<<"Updated Account Balance:
Rs. " << balance; } |
(c) Passing of Pointers
In this method, parameters are send to a
function as pointers. This is
similar to call by reference method. As learned earlier, Pointers are variables that store the address of the location used
by another variable. Pointers can be
passed as parameters to a function and can also be returned back from the
function. Change in value of actual variable will affect if changed within
function.
PROGRAM 50
Q. Write a program to accept two numbers
and swap (exchange) them. Display values before and after the swap. Use passing of pointers method in functions.
#include <iostream> using namespace std; exchange (int *p, int
*q) { int
t; t =
*p; *p
= *q; *q
= t; } main() { int
a,b; cout
<< "Enter 2 Numbers :
"; cin>>
a >> b; cout<<"\n\nInitial
values\n\n"; cout<<"a
= "<< a << "\t b = " << b; exchange
(&a, &b); cout<<"\n\nAfter
exchange of values\n\n"; cout<<"a
= "<< a << "\t b = " << b; } |
(d) const Parameters
In this method, parameters are send to a function as constant values. These values can only be used for computations and cannot be changed by the function (eg: value of pi in maths). The keyword “const” is used to represent a constant value. The compiler generates an error if the function modifies the const parameter.
PROGRAM 51
Q. Write a program using functions that
calculate the area of a circle. The parameters passed are: radius of circle and constant value pi
(3.14). Function definition must come after the main()
Note: For function definition that comes come after the main(), remember to add function declaration before main()
#include <iostream> using namespace std; float Area
(int r, const float i); // function declaration main() { int radius; float Pi =
3.14; float a; cout << "What is the required
Radius : "; cin >>
radius; a = Area
(radius , Pi); cout << "Area of Circle with
Radius " << radius << " is " << a <<
" sq.units"; } float Area (int r, const float i) // function definition { float
ar; ar = i * r * r; return (ar); } |
In this
method, parameters are send to a function as replaceable default values. Here, total number of parameters needed for a function, may
or may not be send. Default values can be assigned as trailing parameters in such a function. The
function can be invoked using lesser than the total number of parameters.
Any missing trailing parameters assume their default values. Default values are
specified when the function is declared. It is used in situations where values
of some arguments remain same for maximum instances. Default values are
considered for parameters from right to left in the function call.
PROGRAM 52
Q. Write a program using functions with default argument values to calculate the interest for customers of a bank. Get values for the principal amount, time period & rate of interest. If the customer specified time period < 1, then time = 1 year. Similarly, if rate of interest < 10 then, use Flat interest rate of 10%.
#include <iostream> using namespace std;
/* Function "interest" is declared
with 3 parameters */ /* Parameter "time" is assigned
default value of 1 year */ /* Parameter "rate" is assigned
default value of 10 % */
float interest(float
amount, float time = 1, float rate = 10);
// function declaration
main() { float pa, t, roi, i; cout<< "Enter Principal Amount : "; cin
>> pa; cout<< "Enter Time Period : "; cin >> t; cout<< "Enter Rate of Interest :
"; cin >> roi; /* If
Time period entered by user < 1, default value = 1 year (look at function
declaration) */ /* If
Interest Rate entered by user < 10, default value = 10% (look at
function declaration) */ if (( t < 1 )
&& (roi < 10)) { t = 1; roi
= 10; i = interest (pa); } else if (roi < 10) { roi = 10; i
= interest (pa,t); } else if (t < 1) { t = 1; i
= interest (pa, t, roi); } else i = interest
(pa, t, roi); cout<< "\nPrincipal Amount : " <<
pa; cout<< "\nTime Period : " << t; cout<< "\nRate of Interest :
" << roi; cout<< "\nInterest Amount : " << i; } float interest (float
amount, float time, float rate) { float
interestAmount; interestAmount = (amount * time * rate) /
100; return (interestAmount); } |
OUTPUT
Inline Functions
are expanded inline (on the spot) wherein, the function call is replaced
by the function code. The
keyword inline is used to suggest C++ compiler to insert the function within the program. Here, control is not transferred from the program to the function.
Instead, the function statements are executed right in the main program where
that function is called. It is used
to save time
when short functions
are called many
times within a program. The time is saved as there is no overhead of function call &
return. Inline functions are not used for recursive functions or when it has
multiple static variables as it takes more memory. Syntax for defining an inline function:
inline return-type function-name (argument-list)
{
Function statements;
PROGRAM 53
Q. Write a program using inline functions to accept a full name and print the total number of vowels in it.
#include <iostream> #include <string> using namespace std; inline int
vowels(string s) { char
vw [ ] = {'a','e', 'i', 'o', 'u', 'A','E', 'I', 'O', 'U'}; int
i=0, j, tot=0; while(s[i]!='\0') { for(j=0;j<10;++j) //
j<10 -> here 10 is the total vowel count in vw { if (s[i]==vw[j]) tot++; } ++i; } return (tot); } main() { string s; cout << "Enter any Full Name :
";
getline(cin,s); cout
<< "Total number of Vowels in "<< s << " is
: "<< vowels(s); } |
OUTPUT
OVERLOADED FUNCTIONS
Function overloading in C++ is a feature that allows two different functions to have the same name if their parameter types or number of parameters are different. That means, you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters.
It also means that a single
function can be redefined multiple times (with different parameters &
return types) so that it could be reused
to perform different tasks. This ability of functions is also known as function
polymorphism or compile time polymorphism (polymorphism means ‘having different forms’). The correct
function is invoked depending upon the data
type and the number of arguments
passed to the function.
PROGRAM 54
Q. Write a
program using function overloading to multiply 2 numbers, divide 2 numbers and square a number.
#include <iostream> using namespace std; int operate (int a, int b) { return
(a*b); } float operate (float a, float b) { return
(a/b); } int operate (int a) { return
(a*a); } main () { int
x=5, y=2;
float n=5.0, m=2.0; cout
<< "Multiplication Value = " << operate (x,y); cout
<< "\nDivision Value =
" << operate (n,m); cout
<< "\nSquared Value = " << operate (x); } |
In the above program, we have defined three
functions with the same name, operate. First operate function accepts two parameters of type int
and returns the multiplication value. The second operate function accepts two float
numbers and returns the division value. The third operate function accepts one int
number and returns the square value. The
compiler knows which function is to be called by examining the data types
passed or the number of arguments passed into the function.
Recursion is the process in which a function calls itself for repeating a task. It is useful in operations like sorting, repeated computations
etc.
Lets have a look at how recursion can be applied to find the factorial of a number (n!). The mathematical formula to find factorial of a number is:
n! = n x (n-1) x (n-2) x (n-3) ... x 1
5! (factorial of 5) would be: 5 x 4 x 3 x 2 x 1 = 120
PROGRAM 55
Q. Write a
program using recursive function to calculate the Factorial of a number.
#include
<iostream> using namespace std; long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } main () { long n; cout << "Please type a number: "; cin >> n; cout << "Factorial of "<< n <<
" = " << factorial
(n); }
|
No comments:
Post a Comment