Functions and Structures
Functions and Structures
3.1 Introduction
In previous unit, you have studied execution flow of programs based on
certain conditions/statements. You have also studied how to store collection
of values in single variable using array. In this unit, we will discuss the reuse
of code using function, how to declare and define a function. We will also
discuss scope and visibility of variables, use of storage classes, declaration
of strings and how to initialize values to strings. Finally we will discuss user
defined data types, structures and unions.
Objectives:
After studying this unit you should be able to:
explain functions and how they enable program organization
discuss different types of variables based on scope
define strings and explain its uses
describe different types of string library functions
define structure and union
differentiate between structures and unions
If function has more than one parameter they should be separated with a
comma.
A function that accepts data from other functions does so by accepting one
or more parameters from the sending function. Information that is passed to
a function is called arguments to the function or simple arguments.
Definition of function
A function definition provides the actual body of the function. A c++ function
definition consists of a function header and function body. Function header
is similar to prototype of function. Function header specifies return type of
function, function name and parameter list. The only difference between the
header and the prototype is the semicolon. If you specify semicolon at the
end of function heading, it generates a syntax error. Function body is group
of statements or syntactical statement. Function needs to be declared
before it is used, but can be defined anywhere in the program or linked file.
The idea of declaring a function before defining it is called forward
declaration. If you define a function before calling it, you do not necessarily
need a definition.
The general syntax of function definition is:
return-type function_name (parameter list) // function header
{
Statements; //Function body
}
The arguments should match during function call with respect to data type
and order of the arguments. In case of default arguments, the value need
not be specified during call.
Let us discuss 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);
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. However, the variables 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.
You can also have more than one user defined functions that 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 example
(printoverload.cpp) program implements an overloaded function print line ()
# 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;
Manipal University Jaipur B2114 Page No.: 58
Object Oriented Programming – C++ Unit 3
}
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 while declaring the function along with the data
type of the argument. The variable name may or may not be specified
during declaration.
The prgram (printoverload.cpp) can also be implemented through default
arguments as shown below example (default.cpp).
//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;
}
In the example 3.4, variable ch and n values are declared as value of
variable n is 25 and value of ch is *. 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 pass any other
variables as shown in the example program (matrix.cpp) below:
//matrix.cpp
# 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;}
}
}
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. The static variables sum and n are
initialized 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 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
Initialized Junk value in Zero Zero
to memory
Purpose Variables used Same as automatic but the Variables used
by single value should be retained by several
function when function terminates functions
3.5 Strings
C++ implements strings as character array. We know that C language does
not support a built in string type. We have to use character arrays to store
and manipulate strings. One problem with character array is that memory
crashes due to insufficient declaration. To avoid that problem C++ provides
a new class called string. The string object may be used like any other
built-in data type. C++ provides a data type "string", by using string data
type we can declare and initialize string values easily.
Strings are used to store character names like name, address, password etc.
Stings are similar to arrays. Like array, string sizes are also defined during
declaration statement. Main difference between string and array is that
every string in c++ must be terminated by null character (’/0’) to mark end of
the string. Strings, unlike other arrays can be input without using a loop.
When inputting strings using cin statement, the compiler stops taking input
from the user once it encounters space or linefeed (pressing enter key).
3.5.1 Declaration and initialization of strings
The string variable declaration and initialization can be done by using single
statement. The strings can also be initialized as arrays.
The following example declares an array of 6 elements of type char
initialized with the characters that form the word "hello" plus a null character
'\0' at the end. It is specified by enclosing the text (hello) between double
quotes.
char str[6]= “hello”;
Strings can also be defined without specifying the size, but in that case they
have to be initialized to a string constant as shown in the following example.
char str[]=”hello world”
However, there is no built in mechanism in C++ that disallows the user to
enter characters than the string maximum size. The extra characters
entered by the user will be truncated. To keep a check on the number of
characters, setw () function can also be used. To use this function,
iomanip.h header file should be included. Let us see one example of it in the
following program (stringexample.cpp).
#include<iostream.h>
#include<iomanip.h>
const int size=10;
void main()
{
char str[size];
cout<<”enter a string”;
cin>>setw(size)>>str;
}
In the program shown above, the user can enter only nine characters
because last one character stores null character (’/0’). While the strings are
input, cin stops reading once it encounters space or linefeed character
(when user presses enter). To read the text containing blank space and to
read multiple lines of text cin.get function can be used. The following
statement will allow the user to input a maximum of 39 characters which can
even include blanks. It will stop reading once it encounters linefeed
character.
cin.get(str, 40);
To read multiple line of text from the user, you have to specify a terminating
character which will be used to recognize end of input. In the following
example, the terminating character is $.
cin.get(str,40,$);
The above example will allow users to enter a maximum of 39 characters
which can include embedded blanks and linefeed.
3.5.2 Standard C++ String functions
C++ standard library provides several string functions used to manipulate
strings. All string library functions are defined in the header file string.h.
Whenever you use string standard function, the header file “strig.h” has to
be included. The table 3.1 lists some of commonly used string functions
Table 3.1: String library functions
String Library
Meaning
function
strlen() Used to find the length of string
strrev() Used to arrange the characters in the string variable in
reverse order except for the null character.
strcpy Used to copy the contents of one string to another.
strcmp Used to compare two strings.
Strlen Function
This function is used to find the length of the string. The general syntax is:
strlen(string variable)
strlen(n) function returns the number of characters or length of the string n.
In the statement shown above, the string constant OOPS is assigned to the
string variable name q. The assignment of a string variable cannot be done
using an assignment operator. It should be done using strcpy function.
Strcmp function
Strcmp function is used to compare two strings. The syntax of strcmp is :
strcmp(string1,string2)
Every character of string1 will be compared with the corresponding
character of string2. The ASCII values of the character will be used to
decide the return value. The function returns an integer and the value
returned will differ based on the conditions as shown below:
If string1 < string2, value returned will be <0
If string1==string2, value returned will be 0
If string1> string2, value returned will be greater than zero.
Thus, a return value 0 implies that strings are equal and a non-zero return
value implies that the two strings are not equal. Please note that the above
function is case sensitive. strcmpi () function can be used if the two strings
have to be compared without case sensitiveness.
The following program (stcmpexample.cpp) implements strcmp function
// stcmpexample.cpp
#include <iostream.h>
#include <string.h>
void main ()
{
char str1[30], str2[30];
for(int i=0;i<10;i++)
{
cout<<"Enter first string: ";
cin>>str1;
}
for(int i=0;i<10;i++)
{
cout<<"Enter first string: ";
cin>>str2;
}
if(strcmp(str1,str2)==0)
cout<<"Both strings are equal";
else
cout<<"Strings are unequal";
return 0;
}
Self Assessment Questions
12. The string variable declaration and initialization can be done by using
single statement. (True/False)
13. _____________ Function is used to copy the contents of one string to
another.
14. To read blanks between the strings or to read multiple lines of text,
_________ function which is a member function of cin can be used
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 need 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. member variable name).
Structures can be nested within each other. When accessing the members
and sub members 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 now define a structure named room, which contains variables of type
distance:
struct room
{ distance length;
distance width;
distance height;
} bedroom;
In the definition of room given above, we have declared a variable bedroom
of type room along with the definition. To access the members of the
bedroom you 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 declaration of room dining, the values 12 and 3 refer to
dining.length.feet and dining.length.inches respectively. Similarly, the
second and third set of values represent feet and inches of width and height
respectively.
You can also create array of structures. For this, the index number should
be specified immediately after the structure variable. For example, the
statement
employee emp[50] ;
will create an array of structure employee.
To access the first array member, you can say emp[0].empid
The below program (structexample.cpp) implements a structure point with
x and y co-ordinates.
//structexample.cpp#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 program shown above, 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 declaration. 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 user defined 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 program shown below (enumerated.cpp)
creates an enumerated datatype that 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)
Manipal University Jaipur B2114 Page No.: 73
Object Oriented Programming – C++ Unit 3
3.7 Summary
Let us recapitulate the important points of this unit:
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 inputs 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 a 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.
Strings are nothing but character arrays. C++ standard library provides
several string functions used to manipulate strings.
Structures and unions data types enable users to create user defined
data types. Structure, is a group data item which has heterogeneous
collection of data.
Enumerated data types create data types that can store pre-defined and
fixed set of values.
Union is a special class type that can hold only one of its non-static data
members at a time.
Union declaration is similar to structure declaration as it allows us to
group together dissimilar type elements inside a single unit.
3. What is a string? Explain with example how string can be declared and
initialized.
4. Differentiate between structures and unions.
5. Define a structure named product with elements productcode,
description, unitprice and qtyinhand. Write a C++ program that
implements the structure and enables to store at least 100 product data.
6. Write a function that takes input as radius of the circle from keyboard
and return the area of the circle.
7. Write a function that takes two integers, finds out which is smaller and
then assigns zero to the smaller variable and returns the value.
3.9 Answers
Self Assessment Questions
1. function prototype
2. function signature
3. return
4. True
5. pass by value
6. returning multiple values and modifying original values
7. Function overloading
8. declaration
9. execution time
10. zero
11. Program file
12. True
13. Strcpy
14. get
15. False
16. struct
17. dot operator (structure variable name.member name)
Terminal Questions
1. One method of passing data to function is 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.
cout<<p[i].qtyinhand;
}
}
6. //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) //function defintion
{ int a;
a= 3.14*radius*radius;
return a;
}
7. //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) //function definition
{ if (m<n)
m=0;
else if (m>n)
n=0
else
{
m=0;
n=0;
}
}
References:
An Introduction to Object-Oriented Programming in C++, 2nd edition,
By Graham M. Seed, Springer Science & Business Media.
Object Oriented Programming with C++ - Sixth Edition,
by E Balagurusamy. Tata McGraw-Hill Education.
Object-Oriented Systems in C++, by Dr. Durgesh Pant, Mahesh Kumar
Sharma, K.S. Vaisla, Firewall Media.