Tuesday, October 16, 2012

Copy Constructor & this pointer


Copy Constructor: Firstly, what is constructor? A constructor is a method define in a class by same name as of class. The work of constructor is to initialize the class members.Constructor is defined publicaly or privately. A Constructor never return any value,so it will never have any return type. A constructor without an argument is called default constructor. A constructor with an argument is known as parameterised constructor

 example:      class example
                       {
                          int a,b;            //data member 

                      public:
                                  
                            example()           //Default Constructor 
                           {
                              a=10;
                               b=10;
                           }
                           example(int x, int y)            //parameterised Constructor
                          {
                                a=x;   
                                b=y;
                           }
                       };

this pointer: Member function of every class object have a special kind of pointer known as this pointer, which points to the object itself. When we cal a member function it comes into existence with the value of this set to the address of object it is pointing. Using a this pointer any member function can find out the the address of the object which it is pointing. Using this pointer a member function can also access the data of the object.
  example:

Operator Overloading Program


Operator Overloading provide facility to give user define meaning to operator. With the help of operator overloading one can perform operation on non-standard data type(user defined data type). For example an '+' operator can add only predefine data type i.e int,long,float,double. Suppose we want to add two user defined data type say two matrix then the '+' operator is overloaded to perform addition of two matrix. The following program illustrate the operator overloading concept.

Default Arguments Program


When we have to define a function that will work on different no. of arguments for number of time then the solution is function overloading.But in case of overloading we have to pass the agruments again and again even if we are calling the function with same value of arguments for many time.C++ resolve this problem with the help of Default Arguments.Now if the function is called one or two or all the arguments missing,the compiler takes it value from the default agruments declare at function prototype.But the missing arguments must be the trailing arguments(those at the at of argument list).Have a look at example given below.

Program To Find Sum Of Digit


Some Basic C program frequently asked in Interview.

/* Program to find sum of digit of a number*/ 


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,s=0;
clrscr();
printf("Enter a number:\t");
scanf("%d",&a);
while(a>0)
{
b=a%10;
s=s+b;
a=a/10;
}
printf("Sum of digit is %d",s);
getch();
}

Program To Convert a Number into Binary



Some Basic C program frequently asked in Interview.

/*Program to convert a number into Binary*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter a number:\t");
scanf("%d",&a);
printf("\t");                  //'\t' is for tab 
while(a>0)
{
b=a%2;
printf("%d",b);
printf("\b\b");         // '\b' is for backspace
a=a/2;
}
getch();
}

Program to check a prime number.


Some Basic C program frequently asked in Interview.

/* Program to check whether a number is prime or not*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter a number:\t");
scanf("%d",&a);
b=2;
while(a%b!=0)
{
b++;
}
if(a==b)
{
printf("\n%d is prime number",a);
}
else printf("\n\t%d is not prime number",a);
getch();
}

Program to Calculate power of a number


Some Basic C program frequently asked in Interview.

/* Power of a Number*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter a number,and its power\t");
scanf("%d%d",&a,&b);
c=1;
while(b>=1)
{
c=c*a;
b--;
}
printf("%d",c);
getch();
}



Program To check a Number is Pallindrome & Armstrong


Some Basic C program frequently asked in Interview.

/*To check a number is pallindrome or not */

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,s=0;
clrscr();
printf("Enter a number:\t");
scanf("%d",&a);
c=a;
//the number is reversed inside the while loop.
while(a>0)
{
b=a%10;
s=(s*10)+b;
a=a/10;
}
//Here the reversed number is compared with the given number.
if(s==c)
{
printf("The no. %d is a pallindrome",c);
}
else
printf("The no. %d is not a pallindrome",c);
getch();
}




/*To check a number is armstrong or not */

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,s=0;
clrscr();
printf("Enter a number:\t");
scanf("%d",&a);
c=a;
//Sum of cube of each digit of given  number is claculated inside the while loop.
while(a>0)
{
b=a%10;
s=s+b*b*b;
a=a/10;
}
//Sum is compared with the given number.
if(s==c)
{
printf("The no. %d is a armstrong no.",c);
}
else
printf("The no. %d is not a armstrong no.",c);
getch();
}

C program to replace multiple spaces with a single space


Program to replace multiple spaces between two words in a string by a single space


#include<stdio.h>

#include<conio.h>

void main()

{
char s[50];
char *str=s;
int i,j;
clrscr();
printf("Enter the String:\n");
gets(s);
for(i=0;*(str+i)!='\0';i++)
   {
   if(*(str+i)==' '&*(str+i+1)==' ')
   {

   for(j=i;*(str+j)!='\0';j++)
     {
 *(str+j)=*(str+j+1);
 }
 i--;
   }

   }
     printf("\n%s",str);
   getch();
}

Count number of words in a string


Program to count number of words in a string enter by a user 


#include<stdio.h>

#include<conio.h>

#include<string.h>
void askstring()
{
char str[50];
int i,words=0;
printf("\nEnter a string\n");
scanf("%[^\n]c",str);
//printf("\nThe String is: %s",str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]==' ')
words++;

}
printf("\n Number of words in the stirng :%d",words+1);
}
void main()
{
clrscr();
askstring();
getch();
}

Frequently asked C programs

Some Basics C program frequently asked in interviews

1.Find factorial of a number using recursive function.


#include<stdio.h>

#include<conio.h>

int fact(int);
void main()
{
int a,b;
printf("Enter no.");
scanf("%d",&a);
clrscr();
b=fact(a);
printf("%d",b);
getch();
}
int fact(int x)
{
int r=1;
if(x==1) return 1;
else r=x*fact(x-1);
return r;
}

2. Getting a multiple word string having spaces from user using scanf function.

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
printf("Enter name:\n");
scanf("%[^\n]s",&name);              /* notice the format specifier used here i.e 
%[^\n]s

*/
printf("%s",name);                          
getch();
}

Binary Search Tree


Binary Search Tree is a binary tree where left child of a node is less than the key of the Parent node and the key in the right child is greater than the parent node.We can design many kind of BST(Binary Search Tree) for some nodes or values.And there average searching time may be different.In Binary Search tree searching is easy. Time complexity of searching in case BST is nlogn.


Binary Tree
Traversal of a Binary TreeThe traversal of binary tree invloves visiting each node in the tree exactly once. Binary tree traversal is usefull in many applications.There are 3 popular method of Binary tree traversal.These methods are:-
1) Inorder Traversal.(Left,Root,Right)
2) Preorder Traversal.(Root,Left,Right)
3) Postorder Traversal.(Left,Right,Root)

 For the above tree:   Inorder Traversal is    5 , 10 , 12 , 20 , 30.
                                    Preorder Traversal is   20 , 10 , 5 , 12 , 30.           
                                    Postorder Traversal is   5 , 12 , 10 , 30 , 20.





Stack implementation using C++

stack example

First of all,what is stack? A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. The end is often known as Top of Stack. For example a no. of books kept one above another, if we have to keep a new book there, we will kept it above all the books and suppose we have to take out a book at first we will pick the book which is at the top.



Insertion Sort algorithm in C++


Insertion Sort is a sorting algorithm used to sort an array element. From the name of the algorithm itself we can make out that here sorting is done with the help of insertion. Now suppose we are provided with a list of number e.g    18  16  14  17  8 . We have to arrange this number in a sorted order. In Insertion sort what it does that it will  pick the number present at the beginning of the given array say A, and place it in another array say B. And  then next number of the array A is picked up as a Key. Now it will compare  with the number present in array B if it is larger than that number then it will inserted in array B after the smaller number present in the array or if it is smaller than the existing number then it will be placed before the existing element of B. Similarly now the 3rd element is taken up as a Key and same comparison is done again. For rest of the element of array A same comparison is done.Have a look at this example.
       
         

Linked List Implementation using C++


Linked List is a sequential storage data structure. It provides a more flexible storage system. Linked List overcome the limitations of arrays. In case of array,on writing a program we had to decide the maximum amount of memory that would be needed for our arrays. If the number of element store in the array is less than the maximum size declare then left space is wasted. Linked List overcome this limitation by providing sequential storage mode. A Linked List consist of sequential node that are linked with each other. Each node in a Linked List has two parts. First part contain the data and second part contain the address of the next node.

Merge Sort program in c in a simple way:




/*Merge Sort program in c in a simple way*/

#include<stdio.h>
#include<conio.h>
#include<math.h>
void merge(int a[],int p,int q,int r);
void mergesort(int a[],int p,int r)
{
int q;
if(p<r)
{
  q=floor((p+r)/2);
  mergesort(a,p,q);
  mergesort(a,q+1,r);
  merge(a,p,q,r);
  }
}
int b[5];
void merge(int a[],int p,int q,int r)
{
int i,j,k;
k=0;
i=p;
j=q+1;

while(i<=q && j<=r)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=q)
b[k++]=a[i++];
while(j<=r)
b[k++]=a[j++];

for(i=r;i>=p;i--)
{
a[i]=b[--k];
}
}
void main()
{
int a[]={12,17,8,6,2};
int i;
clrscr();
mergesort(a,0,5);
for(i=1;i<=5;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Simple Linked List Program to add a node


1.Simple linkedlist program to add a node at the front using c++ class.

//this is just a basic program to understand how a node is added into a linkedlist. 


#include<iostream.h>
#include<conio.h>
class node
{
public:
int data;
node *next;
node()
{
data=0;
next=NULL;
}
node(int x)
{
data=x;
next=NULL;
}
};
class linked_list
{
node *head;
public:
int addNodeAtFront(node &n);
void display();
linked_list()
{
head=NULL;
}
};
int linked_list::addNodeAtFront(node &n)           /*method declaraction*/
{
int i=0;
n.next=head;                                                /*here adress inside the head is now given to next
head=&n;                                                                  pointer of node class*/
i=1;
return i;
}
void linked_list::display()
{
node *ptr=head;
while(ptr!=NULL)
  {
  cout<<"\t"<<ptr->data;
  ptr=ptr->next;
  }
}
void main()
{
int x,q;
linked_list l;
clrscr();
cout<<"Enter a value:\t";               
cin>>x;
node n(x);
q=l.addNodeAtFront(n);           /*call to addNodeAtFront method of class Linked_list*/
if(q==1)
  {
  cout<<"Inserted";
  l.display();
  }
 getch(); 
}