9.3.14

Compound Data Types: Arrays in C++

  Arrays

Before reading this tutorial, you should have knowledge of loop statements.

An array is a collection of several data items of the same data type. It consists of several contiguous memory locations storing data. It removes the cumbersome task of defining separate variables for each data item. A single variable can be used to store one or more data items. For example, if you want to store ages of 10 students of a class, you can easily declare an array of integer type of size 10 instead of declaring 10 variables of integer type each storing age of a student. The general form of the single dimension array is:-

type variable_name[size];

The type is the base type of the array and which is the type of each of the element of the array. The size is the no of the elements in the array. The variable_name is the name of the identifier holding the array. For example,

int age [10];

The age is an array of type integer whose size is 10. It can hold 10 data values. The specific element in the array  can be accessed using an index. An index is the offset from the first element of the array. For example, first element has an index of 0 while the third element has an index of 2. The integer age has elements from age[0] to age[9]. Here is a program which illustrates the working of arrays.
#include<iostream>
using namespacestd


#include<iostream>
using namespace std;
int main ()
{
           int age[10];
           int i,sum=0, avg=0;
           int max=0,min=100;
            for(i=0;i<10;i++)
            {
                       cout << "Enter the age of the student  " << i+1 <<endl;
                       cin >> age[i];
             }
            for(i=0;i<10;i++)
            {
                        sum=sum+age[i];
                        if(age[i]>max)
                        {
                                    max=age[i];
                        }
                        if(age[i]<min)
                        {
                                    min=age[i];
                        }
            }
            avg=sum/10;
            cout << "Average age of the students of the class : " << avg << endl;
            cout << "Maximum age of the student of the class : " << max << endl;
            cout << "Minimum age of the student of the class : " << min << endl;
            return(0);
}

The result of the program is:-


In the program the array is declared by the statement

            int age[10];

age is the identifier of the array which is of type integer and whose size is 10. In the for loop user is asked to enter the age of the student, the age is stored in the element of the array by the statement
                       
            cin >> age[i];

here i is the index of the array. The index starts from 0.  In the next for loop, average age, minimum age and maximum age of the students is calculated. Each element is accessed by index i. The sum of the elements of the array is calculated by the statement
            sum=sum+age[i];

age[i] is the (i+1)th element of the array. The maximum age is calculated by the if statement
                        if(max>age[i])
                        {
                                    max=age[i];
                        }
The minimum age is calculated by the another if statement
                       
                        if(min<age[i])
                        {
                                    min=age[i];      
                        }
The average is calculated by the statement

                        avg=sum/10;

The total no bytes used to store an array is equal to
                        Total bytes=size of(base type)×size of array.

Initializing Arrays

The arrays can be initialized by giving the initial values in a list and enclosed in curly brackets, which is placed after the equal sign which is put after the declaration of the array. For example,
           
            int age[5]={12,13,10,24,15};

elements of the array have values 12, 13, 10, 24, 15. The elements age[0] has value 12 and age[4] will have 15.  If the elements of the array are not initialized then they take some garbage value before they are assigned to some specified value. There is also another way of initializing all the elements of the array to be zero. For example,

            int age[5]={0};

will initialize all the elements of the array age to be zero. If you want some of the elements to be initialized with specific value and rest of the values to be zero then here is an example.
                       
            int age[5]={12,13};

The elements age[0] and age[1] will be initialized to 12 and 13 respectively and rest of the elements will be initialized to zero.


Null Terminated Strings
 
The most common use of one dimensional array is for character strings.  The null terminated string is a character array with a null character at the end. The characters form the string with a null character indicating the termination of the string. A null terminated string can be declared as

            char name[10];

it will hold 10 characters with a null at the end. The size of the array can be more than the length of the array. The array can be initialized as

            char name[10]={'j','e','s','u','s'};

The first 5 elements are initialized and rest elements are null characters. Here is a program which calculates the length of the string.

#include<iostream>
using namespace std;

int main()
{
            char name[15];
            int i=0;
            cout << " Enter your name " << endl;
            cin >> name;
            while(name[i]!='\0')
            {
                        i++;
            }
            cout << "Lenght of the name is : " << i << endl;
            return(0);
}

The result of the program is


The character array is declared by the statement

            char name[15];

The length of the name can be at most 15.  The arrays is assigned by taking the input from the user by the statements
                       
            cout << " Enter your name " << endl;
            cin >> name

Variable name is assigned the string entered by the user.  Each element of the array is referenced and checked whether it is null or not by the statement
                       
while(name[i]!='\0')

Until a null character is not encountered variable i is incremented by the statement
           
i++;

When a null character is encountered while loop is terminated and length is printed by the statement

            cout << "Length of the name is : " << i << endl;

 
Multidimensional Arrays
 
The multidimensional arrays are arrays of arrays. The general form of a multidimensional array is: -
            type variable_name[Size1][Size2]..[Size n];

The two dimensional array can be declared as

            int age[2][5];

this array has two rows and 5 columns. The three dimensional array can be declared as

            int age[2][3][5];

When an element of the array of n dimensional is referenced it uses n index values. For example first element of a two dimensional array declared above is referred as age[0][0] as the index starts from zero and last element is referred as age[1][4]. Here is a program which calculates the average of the elements of the row of the two dimensional array.

#include<iostream>
using namespace std;

int main ()
{
            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};
            int i,j;
            int sum=0,avg=0;
            for(i=0;i<2;i++)
            {
                        for(j=0;j<5;j++)
                        {
                                    sum=sum+age[i][j];
                        }
                        avg=sum/5;
                        cout << "Average of the elements of the row " << i+1  << " is " << avg << endl;
                        sum=0;
            }
            return(0);
}

The result of the program is: -


The program initializes and declares the two dimensional array by the statement

            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};

Elements of the first row and second row are initialized as {12,13,14,15,15} and
{ 12,16,17,13,12}  respectively. The elements are accessed using the statement as

            sum=sum+age[i][j];

age[i][j] refers to the element of row i and column j. This statement calculates the sum of the elements of the row.  After the sum of the elements of a row is calculated then average is calculated by the statement.
           
avg=sum/5;

sum is again initialized to zero. Then again the same process repeats for the second row.

After an introduction of arrays, let us move on to discuss pointers.

20.7.13

C++ : Interfaces


The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation detail separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows:
class Box
{
   public:
      // pure virtaul function
      virtual double getVolume() = 0;
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.

Abstract Class Example:

Consider the following example where parent class provides an interface to the base class to implement a function called getArea():
#include <iostream>
 
using namespace std;
 
// Base class
class Shape 
{
public:
   // pure virtual function providing interface framework.
   virtual int getArea() = 0;
   void setWidth(int w)
   {
      width = w;
   }
   void setHeight(int h)
   {
      height = h;
   }
protected:
   int width;
   int height;
};
 
// Derived classes
class Rectangle: public Shape
{
public:
   int getArea()
   { 
      return (width * height); 
   }
};
class Triangle: public Shape
{
public:
   int getArea()
   { 
      return (width * height)/2; 
   }
};
 
int main(void)
{
   Rectangle Rect;
   Triangle  Tri;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
   // Print the area of the object.
   cout << "Total Rectangle area: " << Rect.getArea() << endl;

   Tri.setWidth(5);
   Tri.setHeight(7);
   // Print the area of the object.
   cout << "Total Triangle area: " << Tri.getArea() << endl; 

   return 0;
}
When the above code is compiled and executed, it produces following result:
Total Rectangle area: 35
Total Triangle area: 17
You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.

C++ : Encapsulation


Definition:

  • Data Hiding is also known as Encapsulation.
  • Encapsulation is the process of combining data and function into a single unit called class.
  • Data Hiding is the mechanism where the details of the class are hidden from the user.
  • The user can perform only a restricted set of operations in the hidden member of the class.
  • Encapsulation is a powerful feature that leads to information hiding,abstract data type and friend function.
  • They encapsulate all the essential properties of the object that are to be created.
  • Using the method of encapsulation the programmer cannot directly access the class.


Access Specifier:

There are three types of access specifier.They are

  • Private :Within the block.
  • Public:Whole over the class.
  • Protected:Act as a public and then act as a private.

Within a class members can be declared as either public protected or private in order to explicitly enforce encapsulation.
The elements placed after the public keyword is accessible to all the user of the class.
The elements placed after the protected keyword is accessible only to the methods of the class.
The elements placed after the private keyword are accessible only to the methods of the class.
The data is hidden inside the class by declaring it as private inside the class. Thus private data cannot be directly accessed by the object.

For example,
In order to make the design and maintenance of a car reasonable the complex of equipment is divided into modules with particular interfaces hiding design decisions. 


General Form:

class class name
{
private:
datatype data;
public:
Member functions;
};

main()
{
classname objectname1,objectname2……………;


Example:

class Square
{
private:
int Num;

public:
void Get()    {
    cout<<"Enter Number:";
    cin>>Num;
}
void Display()    {
    cout<<"Square Is:"<<Num*Num;
}
};

void main()
{
Square Obj;
Obj.Get();
Obj.Display();
getch()
}


Features and Advantages of Data Encapsulation:

The advantage of data encapsulation comes when the implementation of the class changes but the interface remains the same.
It is used to reduce the human errors. The data and function are bundled inside the class that take total control of maintenance and thus human errors are reduced.
Makes maintenance of application easier.
Improves the understand-ability of the application.
Enhanced Security.
Note:Thus the concept of encapsulation shows that a non member function cannot access an object’s private or protected data.

In details we can say that Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example:
class Box
{
   public:
      double getVolume(void)
      {
         return length * breadth * height;
      }
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible.

Data Encapsulation Example:

Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example:
#include <iostream>
using namespace std;

class Adder{
   public:
      // constructor
      Adder(int i = 0)
      {
        total = i;
      }
      // interface to outside world
      void addNum(int number)
      {
          total += number;
      }
      // interface to outside world
      int getTotal()
      {
          return total;
      };
   private:
      // hidden data from outside world
      int total;
};
int main( )
{
   Adder a;
   
   a.addNum(10);
   a.addNum(20);
   a.addNum(30);

   cout << "Total " << a.getTotal() <<endl;
   return 0;
}
When the above code is compiled and executed, it produces following result:
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.