May 2013 - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Tuesday, 28 May 2013

Multilevel Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its second type, that is, Multilevel Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

So in Multilevel Inheritance, we actually have 2 Base Classes in total and 1 Child class. The class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.

The class B is known as Intermediate Base Class since it provides a link for the inheritance between A and C. The chain A B C is known as Inheritance Path. For pictorial representation, follow this link: Inheritance.

A derived class with multilevel inheritance is declared as follows:

class A {.....};            // Base class
class B: public A {.....};             // B derived from A
class C: public B {.....};             // C derived from B

This process can be extended to any number of levels. Let us understand this concept by a simple C++ program:

C++ Program For Multi-level Inheritance:


/* Double-Click To Select Code */

#include<iostream.h>
#include<conio.h>

class student
{
 protected:
  int roll;
 public:
  void get_number(int a)
  {
   roll = a;
  }

  void put_number()
  {
   cout<<"Roll Number: "<<roll<<"\n";
  }
};

class test : public student
{
 protected:
  float sub1;
  float sub2;
 public:
  void get_marks(float x,float y)
  {
   sub1 = x;
   sub2 = y;
  }

  void put_marks()
  {
   cout<<"Marks in Subject 1 = "<<sub1<<"\n";
   cout<<"Marks in Subject 2 = "<<sub2<<"\n";
  }

};

class result : public test
{
 private:
  float total;
 public:
  void display()
  {
   total = sub1 + sub2;
   put_number();
   put_marks();
   cout<<"Total = "<<total<<"\n";
  }
};

void main()
{
 clrscr();

 result student;
 student.get_number(83);
 student.get_marks(99.0,98.5);
 student.display();

 getch();
}

Program Output:



Multilevel Inheritance In C++

Please Comment If You Liked The Post.


Saturday, 25 May 2013

Single Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its first type, that is, Single Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance


So in Single Inheritance, we have one base class and one child class. It means that, there is only one child class, which is inheriting attributes and behavior from only one base class, as shown below:


Types Of Inheritance

Let us consider a simple example to illustrate Single Inheritance. The following program shows a base class 'B' and a derived class 'D'. Both have a private data member each, integer 'a' and integer 'c' respectively. Base class has a function to assign values to its data members. Derived class inherits from base class and its function then calls data members from base class. Then the logical operation is performed and the result is displayed.

C++ Program For Single Inheritance:

/* Double-Click To Select Code */

#include<iostream.h>
#include<conio.h>

class B
{
 private:
  int a;

 public:
  int b;
  void set_ab()
  {
   a = 5;
   b = 10;
  }

  int get_a()
  {
   return a;
  }
};

class D : public B
{
 private:
  int c;
 public:
  void mul()
  {
   c = b*get_a();
  }

  void display()
  {
   cout<<"a = "<<get_a()<<"\n";
   cout<<"b = "<<b<<"\n";
   cout<<"c = a*b = "<<c<<"\n\n";
  }
};

void main()
{
 clrscr();
 D d;
 
 d.set_ab();
 d.mul();
 d.display();
 
 d.b = 20;
 d.mul();
 d.display();

 getch();
}


Program Output:



Please Comment If You Liked The Post.


Sunday, 19 May 2013

C++ Program To Show Use Of Objects In Classes

Hi Guys,
In this post, we'll learn what are objects, the most important entity for which C++ is known better than C language. The main reason of C++ programming is to add the ability to create objects and classes are a central feature of C++ that support OOPS aka Object-Oriented Programming and classes are often called as user-defined types.


Objects are the basic run-time entities in an object-oriented system. They may represent a person, place, a bank account, a table of data or any other item that the program has to handle.When a program is executed, the objects interact by sending messages to one another.

Objects can interact without having to know the details of each other's data or code. Each object contains data, and code to manipulate the data. Well here is an example:

Objects In C++
Two Ways Of Representing An Object


C++ Code To Show Use Of Objects In Classes:



/* Double-Click To Select Code */

#include<iostream.h>
#include<conio.h>

class product  //Class name
{
 private:  // Private data member not accessible by object
  int number;
  float cost;
 
 public:
  void getdata(int a,float b);  //Function declaration
  void putdata();
};

void product::getdata(int a,float b)  //Function definition
{
 number = a;
 cost  = b;
}

void product::putdata()
{
 cout<<"Number : "<<number<<endl;
 cout<<"Cost : "<<cost<<endl;
}

void main()
{
 clrscr();
 product p;   //Declaration of object
 cout<<"\nObject P"<<"\n";
 
 p.getdata(100,299.95);  //Only public members are accessible by object
 p.putdata();
 
 product q;
 cout<<"\nObject Q"<<"\n";
 
 q.getdata(200,175.50);
 q.putdata();
 getch();
}

Program Output:


Objects In C++

Please Comment If You Liked The Post .


Monday, 13 May 2013

Shell Sort C Code And Algorithm

Shell sort is an in-place comparison sort. Donald Shell published the first version of this sort in 1959. It generalizes an exchanging sort, such as insertion or bubble sort, by starting the comparison and exchange of elements with elements that are far apart before finishing with neighboring elements. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange.

Shellsort is a multi-pass algorithm. Each pass is an insertion sort of the sequences consisting of every h-th element for a fixed gap h (also known as the increment). This is referred to as h-sorting. Shell sort is unstable,that is, it may change the relative order of elements with equal values.

It has "natural" behavior, in that it executes faster when the input is partially sorted.


Shell Sort C Code And Algorithm
Shell Sort In Action


Algorithm/Pseudo-Code:


Using Marcin Ciura's gap sequence, with an inner insertion sort.
/* Double-Click To Select Code */
# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
 
foreach (gap in gaps)
{
    # Do an insertion sort for each gap size.
    for (i = gap; i < n; i += 1)
    {
        temp = a[i]
        for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
        {
            a[j] = a[j - gap]
        }
        a[j] = temp
    } 
}



Here is the C Code for Shell Sort:

/* Double-Click To Select Code */

#include <stdio.h>
#include <conio.h>
#define MAX 20

void main()
{
 int arr[MAX],i,j,k,n,increment;
 clrscr();
 printf("Enter the number of elements: ");
 scanf("%d",&n);
 printf("\nEnter %d elements : \n",n);
 for(i=0 ; i<n ; i++)
 scanf("%d",&arr[i]);

 printf("\nUnsorted list is:\n");
 for (i = 0; i < n; i++)
 {
  printf("%4d",arr[i]);
 }
 increment=5;

 /*ACTUAL LOGIC STARTS*/

 while(increment>=1)
 {
  for(j=increment ; j<n ; j++)
  {
   k=arr[j];
   for(i = j-increment ; i >= 0 && k<arr[i] ; i = i-increment)
   arr[i+increment]=arr[i];
   arr[i+increment]=k;
  }
  increment=increment-2;  /*Decrease the incrementement*/
 }
 printf("\n\nSorted list is:\n");
 for (i = 0 ; i<n ; i++)
 {
  printf("%4d",arr[i]);
 }
 printf("\n\n *WWW.CODINGBOT.NET*");
 getch();
}


Output of Program:

Shell Sort C Code And Algorithm

Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Shell Sort which is released under the Creative Commons Attribution-Share-Alike License 3.0


Saturday, 11 May 2013

C Code To Find Transpose Of A Matrix

Hello Guys,
Today I'm gonna show you the C Code, to find transpose of a M x N Matrix.
The transpose of a matrix was introduced in 1858 by the British mathematician Arthur Cayley. We know that in linear algebra, the transpose of a matrix A is another matrix AT (a created by any one of the following actions:

  • Reflect A over its main diagonal (which runs from top-left to bottom-right) to obtain AT
  • Write the rows of A as the columns of AT
  • Write the columns of A as the rows of AT

Formally, the i th row, j th column element of AT is the j th row, i th column element of A:
AT(i,j) = A(j,i)
If A is an m × n matrix then AT is an n × m matrix.

The same is reflected through this image:
Transpose Of A Matrix C Code
Transpose Of A Matrix

In simple terms,
if we have a matrix:
1 2
3 7
4 6

Its Transpose will be:
1 3 4
2 7 6


Here is the C Code to find transpose of a matrix:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>
 
void main()
{
 int m, n, c, d, matrix[10][10], transpose[10][10];
 clrscr(); 
 printf("Enter the number of rows and columns of the matrix a: \n");
 scanf("%d%d",&m,&n);
 printf("\nEnter the elements of matrix: \n");
 
 for( c = 0 ; c < m ; c++ )
 {
  for( d = 0 ; d < n ; d++ )
  {
   printf("a[%d][%d] = ",m,n);
   scanf("%d",&matrix[c][d]);
  }
 }

 printf("\nOriginal Matrix: \n");
 for( c = 0 ; c < m ; c++ )
 {
  for( d = 0 ; d < n ; d++ )
  {
   printf("%4d",matrix[c][d]);
  }
  printf("\n");
 }


 for( c = 0 ; c < m ; c++ )
 {
  for( d = 0 ; d < n ; d++ )
  {
   transpose[d][c] = matrix[c][d];
  }
 }

 printf("\nTranspose of entered matrix: \n");
 
 for( c = 0 ; c < n ; c++ )
 {
  for( d = 0 ; d < m ; d++ )
  {
   printf("%4d",transpose[c][d]);
  }  
  printf("\n");
 }
 getch();
}


Output:



C Code To Find Transpose Of A Matrix



Please Comment If You Liked This Post !! 



This article uses material from the Wikipedia article Transpose which is released under the Creative Commons Attribution-Share-Alike License 3.0


Wednesday, 8 May 2013

Heap Sort C Code And Algorithm

Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part of the Selection sort family. Although somewhat slower in practice on most machines than a well-implemented Quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.

Implementation:

The heapsort algorithm can be divided into two parts.
In the first step, a heap is built out of the data.
In the second step, a sorted array is created by repeatedly removing the largest element from the heap, and inserting it into the array. The heap is reconstructed after each removal. Once all objects have been removed from the heap, we have a sorted array. The direction of the sorted elements can be varied by choosing a min-heap or max-heap in step one.
Heapsort can be performed in place. The array can be split into two parts, the sorted array and the heap.  The heap's invariant is preserved after each extraction, so the only cost is that of extraction.

Algorithm & Pseudo Code For Heap Sort:

/* Double-Click To Select Code */

function heapSort(a, count) is
     input:  an unordered array a of length count
 
     (first place a in max-heap order)
     heapify(a, count)
 
     end := count-1 
    /* In languages with zero-based arrays the children are 2*i+1 and 2*i+2 */
     while end > 0 do
         (swap the root(maximum value) of the heap with the last element of the heap)
         swap(a[end], a[0])
         (decrease the size of the heap by one so that the previous max value will
         stay in its proper placement) 
         end := end - 1
         (put the heap back in max-heap order)
         siftDown(a, 0, end)
         
 
 function heapify(a, count) is
     (start is assigned the index in a of the last parent node)
     start := (count - 1) / 2 
     
     while start ≥ 0 do
         (sift down the node at index start to the proper place such that all nodes
          below the start index are in heap order)
         siftDown(a, start, count-1)
         start := start - 1
     (after sifting down the root all nodes/elements are in heap order)
 
 function siftDown(a, start, end) is
     input:  end represents the limit of how far down the heap
                   to sift.
     root := start

     while root * 2 + 1 ≤ end do          (While the root has at least one child)
         child := root * 2 + 1        (root*2 + 1 points to the left child)
         swap := root        (keeps track of child to swap with)
         (check if root is smaller than left child)
         if a[swap] < a[child]
             swap := child
         (check if right child exists, and if it's bigger than what we're 
          currently swapping with)
         if child+1 ≤ end and a[swap] < a[child+1]
             swap := child + 1
         (check if we need to swap at all)
         if swap != root
             swap(a[root], a[swap])
             root := swap          (repeat to continue sifting down the child now)
         else
             return



C Program For Quick Sort:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void heapsort(int[], int);
void heapify(int[], int);
void adjust(int[], int);

int main()
{
 int array[50],n,i;
 clrscr();

 printf("Enter the no. of elements to be sorted: ");
 scanf("%d",&n);

 printf("\nEnter the elements: \n");
 for(i=0 ; i<n ; i++)
 scanf("%d",&array[i]);

 printf("\nBefore Heapsort:");  //Array Before Mergesort
 for(i = 0; i < n; i++)
 {
  printf("%4d", array[i]);
 }
 printf("\n");

 heapsort(array,n);

 printf("\nAfter Heapsort:");  //Array After Mergesort
 for(i = 0; i < n; i++)
 {
  printf("%4d", array[i]);
 }
 printf("\n");
 getch();
 return 0;
}

void heapsort(int array[], int n)
{
 int i,t;

 heapify(array,n);

 for(i=n-1 ; i>0 ; i--)
 {
  t = array[0];
  array[0] = array[i];
  array[i] = t;
  adjust(array,i);
 }
}


void heapify(int array[], int n)
{
 int item,i,j,k;

 for(k=1 ; k<n ; k++)
 {
  item = array[k];
  i = k;
  j = (i-1)/2;

  while( (i>0) && (item>array[j]) )
  {
   array[i] = array[j];
   i = j;
   j = (i-1)/2;
  }
  array[i] = item;
 }
}

void adjust(int array[], int n)
{
 int item,i,j;

 j = 0;
 item = array[j];
 i = 2*j+1;

  while(i<=n-1)
 {
  if(i+1 <= n-1)
   if(array[i] < array[i+1])
    i++;
  if(item < array[i])
  {
   array[j] = array[i];
   j = i;
   i = 2*j+1;
  }
  else
   break;
 }
 array[j] = item;
}

Output Of Program:

Heap Sort C Code And Algorithm



Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Heap_Sort which is released under the Creative Commons Attribution-Share-Alike License 3.0