Lab 07: Functions: National University of Technology
Lab 07: Functions: National University of Technology
Learning objectives
Group:
Date of Experiment:
Instructor’s Signature:
Description
A function groups a number of program statements into a unit and gives it a name. This unit can then
be invoked from other parts of the program. A function is a complete and independent program. It is
executed by main function or any other function of the program to perform its task.
Functions in C++ (and C) are similar to subroutines and procedures in various other languages.
Any sequence of instructions that appears in a program more than once is a candidate for being
made into a function. The function’s code is stored in only one place in memory, even though the
function is executed many times in the course of the program.
Simple Functions
Our first example demonstrates a simple function whose purpose is to print a line of 45 asterisks. The
example program generates a table, and lines of asterisks are used to make the table more readable.
Here’s the listing for TABLE:
#include<iostream>
using namespace std;
//--------------------------------------------------------------
// starline()
// function definition
voidstarline()
{
for(int j=0; j<45; j++) //function body
cout<< ‘*’;
cout<< endl;
}
Program consists of two functions: main() and starline(). You’ve already seen main() alone. What
other components are necessary to add a function to the program? functiondeclaration, the calls to
the function, and the function definition.
Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a
function without telling the compiler about it. There are two ways to do this. The approach we show
here is to declare the function before it is called.
(The other approach is to define it before it’s called; we’ll examine that next.). In the TABLE program,
the function starline() is declared in the line
voidstarline();
The declaration tells the compiler that at some later point we plan to present a function called starline.
The keyword void specifies that the function has no return value, and the empty parentheses indicate
that it takes no arguments.
(You can also use the keyword void in parentheses to indicate that the functiontakes no arguments,
as is often done in C, but leaving them empty is the more common practice in C++.)
We’ll have more to say about arguments and return values soon. Notice that the function declaration
is terminated with a semicolon. It is a complete statement in itself. Function declarations are also
called prototypes, since they provide a model or blueprint for the function.
They tell the compiler, “a function that looks like this is coming up later in the program, so it’s all right
if you see references to it before you see the function itself.”
starline();
This is all we need to call the function: the function name, followed by parentheses. The syntax of the
call is very similar to that of the declaration, except that the return type is not used. The call is
terminated by a semicolon.
Executing the call statement causes the function to execute; that is, control is transferred to the
function, the statements in the function definition (which we’ll examine in a moment) are executed,
and hence control returns to the statement following the function call.
Finally, we come to the function itself, which is referred to as the function definition. The definition
contains the actual code for the function. Here’s the definition for starline ():
The definition consists of a line called the declarator, followed by the function body. The function body
is composed of the statements that make up the function, delimited by braces.
It must use the same function name, have the same argument types in the same order (if there are
arguments), and have the same return type.
Notice that a semicolon does not terminate the declarator. Figure shows the syntax of the function
declaration, function call, and function definition.
When the function is called, control is transferred to the first statement in the function body. The other
statements in the function body are then executed, and when the closing brace is encountered,
control returns to the calling program.
An argument is a piece of data (an int value, for example) passed from a program to the function.
Arguments allow a function to operate with different values, or even to do different things, depending
on the requirements of the program calling it.
C++ allows programmers to divide their code up into chunks known as functions. A function with
simple description and a well-defined interface to outside world can be written and debugged without
worrying about the code that surrounds it. Using function we can structure our program in a more
modular way, accessing all the potential that structured programming can offer to us in C++.
Call by Value
This method of parsing value to a function is very simple. The values from the main function is
passed as arguments to the function as demonstrated below
main()
{
Int a;
Int b;
sum(5,6);
Return 0;
}
Call by Reference
Address of variables are passed as an argument to a function, which in turn are stored by pointers.
Here is how above example is modified to get the same result by using call by reference method.
main()
{
Int a;
Int b;
sum(&a,&b);
Return 0;
}
A function calling it self is called a recursive function. This means that the function will continue to call
itself and repeat its behavior until some condition is met to return a result. An example given below
would give a clearer understanding of the phenomena.
#include<iostream>
using namespace std;
int fact(int a)
{
int n=0, answer;
if (a!=0)
{
answer=a*fact(a-1);
return answer;
}
else
return 1;
}
int main()
{
int x;
cout<<"enter number to find factorial of"<<endl;
cin>>x;
int facto=fact(x);
cout<<facto;
return 0;
}
Here a demonstration provides a clearer picture to what is happening inside a recursive function
LAB TASK 1
Write a program to pass two integer type numbers as arguments to the function body, compare the
numbers in the function body and print the greater number on the screen. The output of the program
should be like:
LAB TASK 2
Write a program that converts the kilograms into grams by using a function. The output of the
program should be like: Hint: 1 kilogram = 1000 grams.
LAB TASK 3
Write a program that creates four-function calculator, so that it uses functions for each of the four
arithmetic operations. They can be fadd, fsub, fmul, and fdiv. Each of these functions should take
three arguments two of float type and one is of character type for the operator. The output of the
program should be like:
LAB TASK 4
LAB TASK 5