Tuesday 23 October 2012

Functions and Structures in C++


Slm Unit
Functions and Structures in C++
Unit 4 Functions and Structures in C++
Structure
4.1 Introduction
4.2 Introduction to Functions
Self Assessment Questions
4.3 Passing Data to Functions
Self Assessment Questions
4.4 Scope and Visibility of variables in Functions
Self Assessment Questions
4.5 Structures in C++
Self Assessment Questions
Summary
Terminal Questions
4.1 Introduction
This unit has the following objectives
· To understand what are functions and how they enable program organisation
· To understand different types of variables and their use in C++
· To learn to what are structures and grouping data of different data types together
4.2 Introduction to Functions
Functions provide an easy means to organize the programs into smaller modules and use them again without rewriting all the code. It enables reuse of program code. Functions enable programmers to group program code under one name and invoke them whenever required. We have been using several library functions till now without worrying about the code to implement them. Programmers can define their own functions in C++. In this unit, we will learn how to implement user defined functions.
Every function has three components: return value, function name, and a set of arguments. Function name enables users to refer to the functions and is also used when user wants to call and execute the code defined in the function. Every function may or may not return a value. During declaration of function, the datatype of the return value should be specified. If there is no value returned it should be specified as void.The function main() which we had been using in all the programs is one of the default functions which also has been defined as having no return value. When you have several user defined functions in a program, the statements in the main() function is executed first irrespective of where it is located in the program.
Every function can have no or any number of arguments. Arguments are input to the functions and are used inside the function. During declaration of the function, the datatypes of the arguments should be specified. Each argument should be separated with a comma. The arguments should match during function call with respect to datatype and order of the arguments. In case of default arguments the value need not be specified during call.
Every user-defined function should be declared in the program before it is used. The definition can be present in any part of the program. The following is an example of declaration of a function named square which inputs a number and returns the square of the number.
int square(int);
Please note that all the arguments are enclosed within brackets. If there are no arguments, void should be specified within the brackets. The following is the declaration of a function which does not have return value and does not have any arguments.
void xyz(void);
The functions can be invoked or called by referring to the function name followed by the variables or constants that has to be passed as arguments. If there are no arguments that has to be passed to the functions, then the function name should be followed by a pair of paranthesis. The following program would invoke the xyz function:
xyz();
To invoke a square function which inputs a number and returns a number following statement can be used:
s=square(n);
Where s and n are integer variables. The function will compute square of n and the result will be stored in variable s. Please note that during function call, constants can also be passed.
To understand the relevance of functions and its use, let us take an example. Let us suppose you would like to write a program that computes the combination of n items taken r at a time. The mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the numbers have to be computed three times. The code for implementing factorial of a number has been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly implemented without functions, the code has to be repeated three times in the program to compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also difficult to correct or debug. To avoid this problem, we can define a user defined function named fact which would input a number and compute the factorial of that number and return the result. The declaration for the function will be as below
int fact(int);
We can compute the factorial of n just by specifying fact(n) which would call the function fact and execute the statements. The complete program for implementing the above problem is as below:
//function.cpp
# include <iostream.h>
int fact(int); // function declaration
void main()
{
int n,r,ncr ;
cout<< “enter n”;
cin>>n;
cout<< “enter r” ;
cin>>r ;
ncr=fact(n)/(fact(r)*fact(n-r));
cout<<”NCR=” <<ncr;
}
int fact(int number) //function definition
{
int f=1;
for(int i=number;i>1;i--)
f=f*i;
return f; //return computed value
}
In the above program, the user inputs value for n and r. To compute the value of ncr, the fact function is invoked or called first by passing n variable. When the compiler encounters the first statement of the function, it copies the value of the variable n to the variable number. The variable number has scope only inside the function fact and is known as local variable. It cannot be accessed outside the function and so is the variable f and i that has been defined in the function. The factorial of the variable number (same value as n) is computed and then returned to the calling program through the return statement. The return statement is used to return values or results to the main program. This process is repeated for the values r and n-r as well. All the results are then used in the formula in the main program to compute the value of ncr.
If the function does not have any return value, the return statement can be skipped. The control goes back to the main program once the last statement in the program is encountered. Alternatively, simply using the return statement without any variable would also imply that no value is being returned to the main program.
Self Assessment questions
1. Functions enable to reuse code. True/False
2. void print() would return _______ value
3. ________ statement is used to return value to the main program.
4. Function call should always contain function name followed by paranthesis even if there are no arguments. True/False
4.3 Passing Data to Functions
Data can be passed to functions in two ways. One method is passing by value. The fact function discussed in previous section implements passing by value. In this way of passing variables, a copy of the variable(main program) is created during function call with the name specified in the function and initialized with the value in the original variable. All the operations in the function is then performed on the function variable. The values in the variables declared in the main program remains unchanged by the function operations.
Another alternative to passing arguments is passing by reference. In passing by reference, no copy of the variable is created. However, the variables in the main program are referred to by different name in the function. Since no copy is created, when the values in the function variables are modified, the values in the variables in the main program are also modified. Passing by reference provides an easy mechanism for modifying the variables by functions and also enables to return multiple variables.
To pass arguments by reference, all the variable names in the argument list should be prefixed with & (ampersand) or address of operator during function declaration and definition. The following example shows the implementation of passing by reference.
Function call is same for passing by reference.
//passingbyreference.cpp
# include <iostream.h>
int swap(int& m, int& n); // function declaration
void main()
{
int a,b ;
cout<< “enter two numbers”;
cin>>a>>b;
swap(a,b);
cout<<”The value of a is”<<a<<endl;
cout<<”The value of b is”<<b<<endl;
}
void swap(int& m, int& n)
{ int temp;
temp=m;
m=n;
n=temp;
}
In the above program, the variables a and b are passed by reference which implies that they will be accessed directly. The variables are however will be referred as m and n in the function and are swapped. The result is that the function swaps the values in the original variables a and b.
More than one user defined functions can have same name and perform different operations. This is a powerful feature of C++ and is known as function overloading. Every overloaded function should however have a different prototype. The following program implements a overloaded function printline()
//fnoverload.cpp
# include <iostream.h>
void printline();
void printline(char ch);
void printline(char ch, int n);
void main()
{
printline();
printline(“*”);
printline(“*”, 20);
}
void printline();
{ for(int i=0;i<25;i++)
cout<<”-“;
cout<<endl;
}
void printline(char ch);
{for (int i=0;i<25;i++)
cout<<ch;
cout<<endl;
}
void printline(char ch, int n);
{ for (int i=0;i<n;i++)
cout<<ch;
cout<<endl;
}
In the above program, the function printline has three different prototypes depending on the arguments passed to it. The relevant function is invoked depending on the type and number of arguments passed to it.
Functions can also contain default arguments. Default arguments are those whose values need not be explicitly passed during function call. However the default arguments should be specified in the end of the argument list to avoid ambiguity arising during function overloading. The default values are specified in the function declaration along with the data type of the argument. The variable name may or may not be specified during declaration.
The above program can also be implemented through default arguments as shown below.
//defaultarg.cpp
# include <iostream.h>
void printline(char ch=”*”, int n=25);
void main()
{
printline();
printline(“-”);
printline(“-”, 20);
}
void printline(char ch=”*”, int n=25);
{ for(int i=0;i<n;i++)
cout<<ch;
cout<<endl;
}
As shown in the above example, the values for the variables ch and n will be taken * and 25 respectively if not specified (as in first and second function calls). However if the values are specified explicitly, then the default values will not be considered.
Arrays can be used as arguments to functions. It is similar to passing any other variables as shown in the following example
# include<iostream.h>
void display(int arr[3][4]);
void main()
{ int matrix1[3][4], matrix2[3][4], sum[3][4];
int i,j;
cout<<”Enter the elements of matrix one”;
for(i=0; i<3;i++)
for(j=0:j<4;j++)
cin>>matrix1[i][j];
cout<<”Enter the elements of matrix two”;
for(i=0; i<3;i++)
for(j=0:j<4;j++)
{
cin>>matrix2[i][j];
sum=matrix1[i][j]+ matrix2[i][j];
}
cout<<”sum is”;
display(sum);
}
void display(int arr[3][4] )
{
for(int i=0;i<3;i++)
{for(int j=0;j<3;j++)
cout<<arr[i][j]<<” “;
cout<<endl;}
}
Self Assessment questions
1. The values in the original variable remain unchanged during ________ type of function call
2. The advantage of passing by reference is _____________
3. The feature of C++ which enables two or more functions to have same name but different prototypes are known as ___________
4. Default values for the arguments have to be specified during _____________
4.4 Scope and Visibility of variables in Functions
Functions save memory as all the calls to the function cause the same code to be executed. However, with this there is overhead of execution time as there must be instructions for jump to the function, saving data in registers, pushing arguments to stack and removing them, restoring data, instructions for returning to the calling program and return values. To save execution time of functions, one of the feature in c++ is inline functions. An inline function’s code is put with the code in the calling program for every function call. The inline function is written like any other function except that the function declaration begins with the keyword inline. This type of function is suitable for small functions which has to be repeatedly called. This enables the user to write programs using functions which would make programs look neat and less lengthy, at the same time the actual code is inserted in all the places where the function is called after compilation enabling faster execution of the program.
The several types of variables can be created in C++ which can be different in terms of life, visibility and the way it is initialized. These are also known as storage classes.
We will discuss three types of storage classes in this section : Automatic, External and Static variables.
Automatic variables is default variable in C++. All the variables we have created and used in programs are automatic variables. These variables can also be declared by prefixing the keyword auto. One of important characteristics of these variables are that they are created only when the function or program block in which they are declared are called. Once the execution of function or module execution is over, the variables are destroyed and the values are lost. The reason for limiting the lifetime of automatic variables is to save memory. When the variables are not be used by the function, they are removed from the memory. They can be accessed only within the function where they are declared. Beyond which they are not idenfiable. By default the automatic variables are not initialized to any specific values unless and until specified. They contain junk value depending on the value stored in the memory. Therefore it is necessary to initialize automatic variables to avoid problems in debugging.
External variables are variables external to any function. Thus they can be accessed by multiple functions. This is the easiest way to share data among various functions. However too many external variables can create problems in debugging as the programmer will have tough time figuring out which function modified which data. Object oriented programming provides an alternative to use external variables. This feature is just to support backward compatibility with C. External variables are also known as global variables and are automatically initialized to zero. These variables are declared before main and declaration statement does not belong to any function.
The following program shows the difference between an external variable and an automatic variable.
//external.cpp
# include<iostream.h>
int x;
void f1();
void f2();
void main()
{
x=x+2;
f1();
f2();
cout<<x;
}
void f1()
{ int x;
x=x*2;
}
void f2()
{ x++;
}
In the above program, we have defined an external variable x. This variable will be automatically initialized to zero. The statement x=x+2; will store two in x. The function f1 will not have any impact on the value of the external variable as there is another local automatic variable x defined in the function which will be modified (Please note that when automatic and global variable have same name, the local variable will override the global variable).
The function f2 will increment global variable by one. Thus the final output of the above program will be 3.
External variables have a life of the file/program in which they are defined.
Static variables are a mix of external and automatic variables. They have the scope of the function in which they are defined like automatic variables. But they can retain their values even after the function execution is over and are automatically initialized to zero like external variables. The following program shows the use of the static variables.
// static.cpp
# include <iostream.h>
void main()
{
int num;
char ch;
do
{
cout<<”Enter a number”;
cin>>num;
f1(num);
cout<<”Do u want to enter another number”;
cin>>ch;
}while (ch==’y’)
}
void f1(int x)
{ static int sum, n;
sum=sum+x;
n=n+1;
avg=sum/n;
cout<< “Average is”<<avg;
}
The above program allows the user to enter any number of integers and computes the average of the numbers till then. The static variables sum and n are intitialised to zero. They are updated when user enters a new number and the function is called. The values of these variables are retained even after the function returns back to the main program.
The summary of all three storage classes is shown below:
Automatic
Static
External
Visibility
Function
Function
Program
Lifetime
Function
Program
Program
Intialised to
Junk value in memory
Zero
Zero
Purpose
Variables used by single function
Same as automatic but the value should be retained when function terminates
Variables used by several functions
Self Assessment questions
1. Inline functions help in saving ______________ of programs
2. Static variables are initialized to _________ automatically.
3. External variables are accessible throughout the _________.

4.5 Structures in C++
We have seen in unit three how we can group data of same type together with arrays. Data that are of different types but are logically related can also be grouped together. This can be done through structures. Structures are a group of dissimilar data that are related with each other. For example, if you want to store all the details of an employee such as employee id (integer), name (string), department code(integer), and salary as one entity, you can do this using structure as shown below:
struct employee
{ int empid;
char name[35];
int deptcode;
float salary;
};
Structure is a feature in C++ that enables you to define a user-defined datatype. Once you specify the definition of the structure, you can create variables of that structure. In the above definition, we have defined a structure using the keyword struct followed by the name of the structure (employee). All the data items that needs to be defined are defined by specifying the datatype and name of the variable. Once the definition is done, variables of type employee can be created. For example, the following statement creates a variable e1 of type employee.
employee e1;
Structure variables can be initialized during declaration. The values for all the members should be specified separated by comma and all the values enclosed within flower brackets as shown below
employee e1= {1234, “Ajay”, 12, 6900.00};
Structure variables can be copied and assigned to another structure variable as shown below
employee e2;
e2=e1;
To access the members of the structure variables, dot operators can be used. For example to access empid of structure variable e1, you would say e1.empid (structure variable. membervariable name).
Structures can be nested within each other. When accessing the members and submembers dot operators can be used. Let us suppose you have defined a structure named distance with two members length and width as declared below:
struct distance
{ int feet;
int inches;
}
Let us define now a structure named room which contains variables of type distance
struct room
{ distance length;
distance width;
distance height;
} bedroom;
In the above definition, we have declared a variable bedroom of type room along with the definition.
To access the members of the bedroom we can use
bedroom.length.feet
bedroom.length.inches
bedroom.width.feet
bedroom.width.inches and so on
To initialize nested structures you have to group together all the elements of the structure
room dining = {{12, 3},{13,0},{11,2}}
In the above declaration, the values 12 and 3 refer to dining.length.feet and dining.length.inches repectively. Similarly the second and third set of values represent feet and inches of width and height respectively.
Array of structures can be created. The index number should be specified immediately after the structure variable. For example, the statement
employee emp[50] ;
will create a array of structure employee.
To access the first array member, you can say emp[0].empid
The following program implements a structure point with x and y co-ordinates.
#include<iostream.h>
#include<conio.h>
# include<math.h>
struct point
{ int x,y;
} p1,p2;
void main()
{
int s;
cout<< “Enter the co-ordinates for first co-ordinate” ;
cin>> p1.x>>p1.y;
cout<<”enter the co-ordinates for second co-ordinate”;
cin>>p2.x>>p2.y;
s=sqrt(((p2.y-p1.y)*(p2.y-p1.y))+((p2.x-p1.x)*(p2.x-p1.x))) ;
cout<<endl<<”the distance between the two points is”<<s;
getch();
}
In the above program we have defined a structure point which stores x and y co-ordinates of the point. Along with the declaration we have also created two point variables p1 and p2. This is a way to create variables along with the structure decalaration. This can be a separate statement also as discussed earlier. The program accepts two points from the user and displays the distance between them.
Structures are good mechanism of creating userdefined datatypes. C++ specifies another method known as enumerated data type to enable users create their own datatypes. Enumerated data types can store fixed set of values and you can perform arithmetic on them as well. They are defined using the keyword enum. The following program creates an enumerated datatype which stores different days of the week.
//enumerated.cpp
#include <iostream.h>
enum weekday {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
void main ( )
{ weekday day1,day2;
day1=Mon;
day2= Fri;
int diff=day2-day1;
cout<<”days between =”<<diff;
if (day1<day2)
cout<<”day1 comes before day2”;
}
In the above program enumerated datatype weekday is created. The first value (Sun) is assigned zero by default and so on. The variables day1 and day2 can be assigned only the values specified in the datatype declaration or their integer equivalent. They cannot be assigned any other value.
Self Assessment Questions
1. Structures group data of similar type. True/False
2. ___________ keyword is used to create structures.
3. Member data of the structure are accessed by ________ operator
Summary
Functions provide good mechanism to organize data. Functions are given a name which can be used to call the function and execute the statements in the functions. Functions can also take input which are known as arguments which passed during function call. Arguments can be passed either by value or by reference. They can also have return value which can return an computed value back to the main program. Inline functions enable programmers to save processing time by reducing the overheads involved in function call.
Programs can make use of automatic, external and static variables which have different types of utility depending on the way the variable should be accessed and whether the value has to be retained.
Structures and enumerated data types enable to users to create user defined datatypes. Structure group data items that have different datatypes. Enumerated datatypes create datatypes that can store pre-defined and fixed set of values.
Terminal Questions
1. Define a structure named product with elements productcode, description, unitprice and qtyinhand. Write a C++ program that implements the structure and enables to store atleast 100 product data.
2. Write a function that input radius of the circle and return the area of the circle.
3. Write a function that takes two integers, finds out which is smaller and then assigns zero to the smaller variable and returns the value.
Answers to SAQs in 4.2
1. True
2. no value
3. return
4. True
Answers to SAQs in 4.3
1. passing by value
2. returning multiple values and modifying original values
3. Function overloading
4. declaration
Answers to SAQs in 4.4
1. execution time
2. zero
3. Program file
Answers to SAQs in 4.5
1. False
2. struct
3. dot operator (structure variable name.member name)
Answers to TQs
1. //arrayproduct.cpp
# include <iostream.h>
structure product
{ int productcode;
char description;
float unitprice;
int qtyinhand;
}p[100];
void main()
{ int i;
for(i=0;i<100;i++)
{
cout<<”enter product code”;
cin>>p[i].productcode;
cout<<”enter product description”;
cin>>p[i].description;
cout<<”enter unit price”;
cin>>p[i].unitprice;
cout<<”enter qty in hand”;
cout<<p[i].qtyinhand;
}
}
2. //areacircle.cpp
# include <iostream.h>
int carea(int radius); // function declaration
void main()
{
int radius ;
cout<< “enter radius”;
cin>>radius;
cout<<”The area of circle is”<<carea(radius)<<endl;
}
int carea(int radius)
{ int a;
a= 3.14*radius*radius;
return a;
}
3. //smallzero.cpp
# include <iostream.h>
void smallzero (int& m, int& n); // function declaration
void main()
{
int a,b ;
cout<< “enter two numbers”;
cin>>a>>b;
smallzero(a,b);
cout<<”The value of a is”<<a<<endl;
cout<<”The value of b is”<<b<<endl;
}
void smallzero(int& m, int& n)
{ if (m<n)
m=0;
else if (m>n)
n=0
else
{
m=0;
n=0;
}
}
  • 0 likes

No comments:

Post a Comment