Friday, 6 April 2018

Inheritance

Inheritance is the process by which object of one class an acquire the properties of another class.

Inheritance helps for software reusability in which new classes are created from existing classes by absorbing  their attributes and behaviors.

If user want data member and member function of existing class, user can inherit data member and member function of old class with the help of inheritance.

The existing class from which new class is derived is known as base class or parent class or super class. The derived class is known as sub class or child class.

The derived class can add data members and member functions of its own so derived class can be larger than its base class.

When a class inherits another , the member of the base class becomes members of the derived class.

The syntax of deriving new class from old class-

class derivedclassname : accessmodifier baseclassname
 {
   //Body of the class
};


 The above syntax contains

1. The keyword class
2. derivedclassname which is user defined name for new class
3. The : (Colon) indicates that the derived class name is derived from the base class.
4. The access modifier is optional. If no access modifier is present, them access modifier is private by default.
5. baseclassname is the existing class name.

Ex:
class base
{
//body of the base class
};
Class derived1:private base   //private Derivation


};
Class derived2:public base     //public Derivation


};
Class derived3:protected base   //protected Derivation
{

};

Public Inheritance

When the access specifier for the a base class is public that is when base class is publicly inherited by a derived class all public member of the base class becomes public members of the derived class and all the protected members of the base class becomes protected members of the derived class.

Base class private elements remain private to the base class an are not accessible by the members of the derived class.

Program for demonstrating public Inheritance:

#include<iostream.h>
#include<conio.h>
class base
{
int i,j;
public:
void set(int a, int b)
{
i = a;
j = b;
}
void show( )
{
cout<<"Value of i is--->"<<i<<"\tValue of j is--->"<<j<<"\n";
}
};
class derived : public base
{
int k;
public:
derived(int x)
{
k = x;
}
void showk( )
{
cout<<"\nValue of k is--->"<<k<<"\n";
}
};
void main( )
{
derived ob(3);
clrscr( );
ob.set(1,2);
ob.show( );
ob.showk( );
getch( );
}

Output:-
Value of i is--->1             Value of k is--->2
Value of k is--->3


Protected Access Specifiers :
   When user declare class members as protected , these class members are private to their own class but can still be inherited and accessed by derived class.

Program  to demonstrate protected access specifies for data members of class.

#include<conio.h>
#include<iostream.h>
class base
{
protected:
int i,j;
void set(int a, int b)
{
 i = a;
j = b;
}
void show( )
{
cout<<"\nValue of i is--->"<<i<<"\tValue of j is--->"<<j;
}
};
class derived : public base
{
int k;
public:
void setk( )
{
k = i*j;
}
void showk( )
{
cout<<"\tValue of the k is--->"<<k<<"\n";
}
};
void main( )
{
derived ob;
clrscr( )
{
ob.set(2,3);
ob.show( );
ob.setk( );
ob.showk( );
getch( );
}

Output:-
Value of i is--->2     Value of j is--->3    Value of the k is--->6

Private Inheritance

When the base class is inherited by using the private access specifiers, all public and protected members of the base class becomes private members of the derived class.


Write a program to demonstrate private

#include<conio.h>
#include<iostream.h>
class base
{
int i,j;
public:
void set(int a, int b)
{
i = a;
j = b;
}
void show( )
{
cout<<\nValue of i is--->"<<i<<"Value of j is--->"<<j<<"\";
}
};
class derived : private base
{
int k;
public:
derive(int x)
{
k = x;
}
void showk( )
{
cout<<"Value of k is--->"<<k<<"\n";
}
};
void main( )
{
derived ob(3);
clrscr( );
ob.set(1,2);   //ERROR, can not access set
ob.show( );   //ERROR, can not access set
getch( );
}

Note: The program will not compile because you are typing to access private members of the object.

Protected Inheritance 

It is possible to inherit a base class as protected.

When this is done all public and protected members of the base class becomes protected members of the derived class.

Program to demonstrate Protected Inheritance

#include<conio.h>
#include<iostream.h>
class base
{
protected:
int i,j;
public:
void setij(int a, int b)
{
i = a;
j = b;
}
void showij( )
{
cout<<"Value of i is--->"<<i<<"\tValue of j is--->"<<j<<"\n";
}
};
class derived : protected base
{
int k;
public:
void setk( )
{
setij(10,12)
k = i*j;
}
void showall( )
{
cout<<"Value of k is--->"<<k<<"\n";
showij( );
}
};
void main( )
{
derived ob;
clrscr( );
ob.setk( );
ob.showall( );
//ob.showij( );  //Ellegal not accessible
getch( );
}

Output:-
Value of k is--->120
Value of  i is--->10     Value of j is--->12

Thursday, 5 April 2018

Rules for Binary operator

Only existing can be overloaded. New operators can not be created.

The overloaded operator must have at least one operand that is user defined type.

We can not change the basic meaning of operator.

Overloaded operator follows the syntax rules of the original operators. They can not be overridden

There are some operators which can not be overloaded such as

Sizeof----------->Size of Operator

         ----------->Membership Operator

        ------------>Scope Resolution Operator

        ------------>Conditional Operator

We can use friend function to overload operators

Unary operators overloaded means of member function take no explicit argument and return no explicit value.

Binary operators overloaded through a member function take one explicit argument.

When binary operators overloaded through member function then left hand operand must be object of relevant class.

Limitation OR Pitfalls of Operator Overloading

The prefix ++ or - notation (Ex  ++x  or  --x) cause a variable to be updated before its value is used in the expression , where as postfix ++ or -- notation (Ex  x++  or   x--)  Cause it to be updated after its value is used. However , the statement,

++s;
Has exactly the same effect statement
s++;

When ++ and -- operators are overloaded that is there is no distincton between  the prefix and postfix overloaded operator function.

#include<conio.h>
#include<iostream.h>
class increment
{
int x,y,z;
public:
void getdata(int a, int b, int c)
{
 x = a;
y = b;
z = c;
}
void display( )
{
cout<<"\t x="<<x<<"\ty--"<<y<<"\tz--"<<z;
}
increment operator ++( )
{
increment temp;
temp.x = x++;
temp.y = y++;
temp.z = z++;
return temp;
}
};
void main( )
{
increment s1, s2, s3;
clrscr( );
s1.getdata(10, 20, 30);
cout<<"\n\toriginal data--->\n";
s1.display( );
s2 = ++s1;
cout<<"\n\tAfter overloading prefix increment data of object s2 is--->\n";
s2.display( );
getch( );
}

Output:-
original data--->
x=10   y--20    z--30
After overloading prefix increment data of object s2 is--->
x-10    y--20     z--30

--------------------------------------------------------------------------------------------------------------------------
#include<conio.h>
#include<iostream.h>
class increment
{
int x,y,z;
public:
void getdata(int a, int b, int c)
{
 x = a;
y = b;
z = c;
}
void display( )
{
cout<<"\t x="<<x<<"\ty--"<<y<<"\tz--"<<z;
}
increment operator ++( )
{
increment temp;
temp.x = ++x;
temp.y = ++y;
temp.z = ++z;
return temp;
}
};
void main( )
{
increment s1, s2;
clrscr( );
s1.getdata(10, 20, 30);
cout<<"\n\toriginal data--->\n";
s1.display( );
s2 = s1++;
cout<<"\n\tAfter overloading prefix increment data of object s2 is--->\n";
s2.display( );
getch( );
}

Output:-
original data--->
x=10   y--20    z--30
After overloading prefix increment data of object s2 is--->
x-10    y--20     z--30

Overloading Binary Operator

Binary operations are performed which require two operands to perform operations.

To add two numbers generally we use statement like
   C = sum(A,B);      //Functional Notation

This functional Notation can be replaced by natural looking expression
   C = A + B;
             By overloading '+' operator using an operator +( ) function.

The Overloaded function can be invoked by expression such as for binary operators-
   Syntax :
   X op Y;



#include<conio.h>

#include<iostream.h>
class complex 
{
float x;
float y;
public:
complex(double real, double imag)
{
x = real;
y = imag;
}
complex( )
{


}
complex operator+(complex c);
void display( );
};
complex complex ::operator+(complex c)
{
complex temp;
temp.x = x+c.x;
temp.y = y+c.y;
return (temp);
}
void complex::display( )
{
cout<<x<<" +j"<<y;
}
void main( )
{
complex c1(2.5,3.5);
complex c2(1.6,2.7);
complex c3;
clrscr( );
c3 = c1 + c2;
cout<<"\n\n\tc1 is--->"<<"\t";
c1.display( );
cout<<"\n\n\tc2 is--->"<<"\t";
c2.display( );
cout<<"\n\n\tc3 is--->"<<"\t";
c3.display( );
getch( );
}

Output:-
c1 is--->               2.5    +j3.5
c2 is--->               1.6    +j2.7
c3 is--->               4.1    +j6.2

Binary Operator Overloading using friend function

In many cases whether you overload an operator by using a friend or member function makes no functional difference. In those cases it is usually best to overload by using member function. However there is one situation in which overloading by using a friend increase flexibility of an overloaded operator.

We have seen how unary operator is overloaded, similar way we can overload binay operator. Binary operator requires two operands.

The syntax for overloading binary operator using friend function as follows:

friend Return_type operator op(Arguments)
{                      //Body of the operator function

}

WAP to overload binary '+' operator to add two complex numbers using friend function

#include<conio.h>
#include<iostream.h>
class complex
{
double real, ima;
public:
void getdata( )
{
cout<<"\n\tEnter real part of complex no.";
cin>>real;
cout<<"\n\tEnter imaginary part of complex no";
cin>>img;
}
void display( )
{
cout<<"\t"<<real<<"+i"<<img;
}
friend complex operator +(complex,complex);
};

complex operator +(complex c1, complex c2)
{
complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}
void main( )
{
complex A,B,C;
clrscr( );
cout<<"\n\tEnter data for first object";
A.getdata( );
cout<<"\n\tEnter Data for second object";
B.getdata( );
C = A + B;
cout<<"\n\tData for first object--->";
A.display( );
cout<<"\n\tData for second object--->";
B.display( );
cout<<"\n\tAddition of two complex no is--->";
C.display( );
getch( );
}

Output:-
Enter data for first object
Enter real part of complex no12

Enter imaginary part of complex no5.6

Enter Data for second object
 Enter real part of complex no5

Enter imaginary part of complex no3.5

Data for first object--->    12+i5.6 
Data for second object--->   5+i3.5
Addition of two complex no is--->      17+i9.1

Overloading Unary Operator

First we consider the unary operator. Let consider unary operator unary minus ( - ) , when it is used, it takes just one operand.

We know that unary minus (-) operator changes the sign of an operand when applied to basic data item.

We have overloaded this operator so that it should be operated to an object in the same way as applied to an int or float variables.

The unary minus when applied to an object should change the sign of each of data item.

Overloaded function can be invoked by expression such as for unary operator

                   Op  x;

                      OR

                   x  op;

#include<conio.h>
#include<iostream.h>
class space
{
int x, y, z;
public:
void getdata(int a, int b, int c)
{
  x = a;
  y = b;
  z = c;
}
void display( );
void operator-( );
};

void space::display( )
{
cout<<"\n\tx is--->"<<x;
cout<<"\n\ty is--->"<<y;
cout<<"\n\tz is--->"<<z;
}
void space::operator-( )
{
x = -x;
y = -y;
z = -z;
}
void main( )
{
space s;
clrscr( );
s.getdata( 10, -20, 30);
cout<<"\n\tBefore Overloading:";
s.display( );
-s;
cout<<"\n\tAfter Overloading:";
s.display( );
getch( );
}

Output:-
Before Overloading:
x is--->10
y is--->-20
z is--->30
After Overloading:
x is--->-10
y is--->20
z is--->-30

Unary Operator overloading using Friend function

We can also use unary operator with the friend function. By using this concept we can use operator function with different classes. The following program illustrates this features.

Note : 
 In the friend function , we are passing argument as the reference . If we pass argument as by value it will not reflect the correct result because we need all the changes outside which are made inside the operator function.

//WAP to overload unary '-' operator to negate different variables using friend function

#include<conio.h>
#include<iostream.h>
class space
{
int x, y, z;
public:
void getdata(int a, int b, int c)
{
z = a;
y = b;
z = c;
}
void display( )
{
cout<<"\n\tData--->";
cout<<"\t"<<x<<"\t"<<y<<"\t"<<z;
}
friend void operator -(space &op);
};
void operator -(space &op)
{
op.x = -op.x;
op.y = -op.y;
op.z = -op.z;
}
void main( )
{
space s;
clrscr( );
s.getdata( 10, -20, 30);
cout<<"\n\tBefore Operator overloading---";
s.display( );
-s;
cout<<"\n\tAfter Operator overloading---";
s.display( );
getch( );
}

Output:-
Before Operator overloading--- 
Data is--->  10   -20   30
After Operator overloading---
Data is--->   -10    20    -30

Operator Overloading

Cpp allows user to overload most operators so that they should perform special operations relative to classes that user create.

Cpp tries to make user defined data types behaves in much the same way as in built in types.

Cpp permits us to add two variables of user defined types with the syntax that is applied to basic types.

Cpp provides the operator special meaning to operator on user defined data type known as operator overloading.

Operator can overloaded by creating operator functions.

An operator function defines the operation that the overloaded operator will perform relative to class.

An operator function is created using keyword 'operator'.


Syntax is->

return type classname :: operator op(argument list)
{
  //operations

}

Where return type is the type of the value returned by the specified operations and 'op' is the operator being overloaded.

When unary operator is overloaded then the argument list is empty.

When binary operator is overloaded the argument list has only one parameter.

Here 'operator' is a keyword in a member function which tells that it's a operator overloading function.

A member function called as operator overloaded function should be created under public section of the class.

Wednesday, 4 April 2018

'new' and 'delete' Operators

In 'C' , we have used malloc( ), calloc( ), and realloc( ) function to allocate memory dynamically that is at the run time. 'C++' also provides these function but other than this it supports new unary operators 'new' and 'delete' to allocate and to free memory at run time in a better and easier way than the above functions.

Advantages of using 'new' an 'delete' over above functions are
 1. It automatically computers the size of the data object. So no need to computer the use sizeof( ) operator.
 2. It automatically returns the correct pointer type , so that it is not need to use type casting.
 3. Like any other operator , new and delete can be overloaded.

The 'new' operator can be used to create object of any data type. It has the following general form
pointer_variable = new data_type;

Here pointer_variable is a pointer of type data_type. The pointer_variable holds the address of the memory space allocated. 

The data_type may be any valid data_type.
Ex:
int *p;
p = new int;

The 'new' operator can be used to create memory space for any data type including user define data type , such as array , structure and class.

The general form of one dimensional array is as follows.
pointer_variable = new data_type[size];

Here size gives information about the number of elements in the Array


Ex int foo
foo = new int[5];

In this case, the system dynamically allocates a space for five elements of type of int and returns a pointer to the first element of the sequence.
⬜⬜⬜⬜⬜⬜⬜⬜

foo

Here foo is a pointer variable and thus the first element pointed by foo can be accessed either the expression foo[0] or *foo an second element as foo[1] or *(foo+1).

Note:
There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of memory using new. The most important difference is that the size of a regular array needs to be constant expression  and thus the size has to be determined at the moment of designing the program before it is run where as dynamic memory allocation performed by 'new' allows to assign memory during runtime using any variable value as size

'delete' Operator
Syntax: 
             delete pointer;
             Delete[ ] pointer;


The first statement releases the memory of a single element allocated using new and second one releases the memory allocated for array of element using 'new'.

#include<conio.h>
#include<iostream.h?
void main( )
{
int i,n;
int *p;
clrscr( );
cout<<"\nHow many elements you want to store ?";
cin>>n;
p = new int[n];
cout<<"\nEnter elements in Array";
for(i=0;i<n;i++)
{
cin>>p[i];
}
cout<<"\nYou have elements";
for(i=0;i<n;i++)
{
cout<<"\t"<<((p+i);
}
cout<<"\nHow many elements you want to store ?";
cin>>n
p = new int[n];
cout<<"\nEnter elements in Array";
for(i=0;i<n;i++)
{
cin>>p[i];
}
cout<<"\nYou have elements";
for(i=0;i<n;i++)
{
cout<<"\t"<<*(p+i);
}
delete[ ]p;              .//Deallocating memory
getch( );
}


Output:-
 How many elements you want to store ?4
Enter elements in Array 1 2 3 4 
You have element 1    2   3   4   

 How many elements you want to store ?6
Enter elements in Array 6  5   4   3  2  1
You have  6    5     4    3    2   1

'this' Pointer

We know that pointer is a variable which holds address of some other variable an we can access the data of another variable using pointer technique.

'this' is special type of pointer which holds the address of objects which invokes the member function of the class.

Whenever any object calls its member function, 'this' pointer is automatically set and contains the address of that object. In other words , whenever a member function gets called , an address of the object get passed to the function and this address gets collected in the 'this' pointer.

Hence 'this' pointer acts as an implicit argument to all the member function of the class and it is automatically passed to the member function when member function of class is called.

In operator overloading , we have been implicitly using the pointer 'this' to the member function.

When a unary operator is overloaded using a member function , we pass no argument to the function. When a binary operator is overloaded using a member function , we pass only one argument to the function and other argument is implicitly passed using pointer 'this'

#include<conio.h>
#include<iostream.h>
class abc
{
int a;
public:
void accept(int a1)
{
this->a=a1;
}
void display( )
{
cout<<"\n\tAddress of calling object is--->"<<this;
cout<<"\n\tValue of a is--->"<<this->a;
}
};
void main( )
{
abc A1;
clrscr( );
cout<<\n\tAddress of object is--->"<<&A1;
A1.accept(10);
A1.display( );
getch( );
}

Output:-
Address of object is--->0⤫8f9afff4
Address of calling object is--->0⤫8f9afff4  
Value of a is--->10

One important application of 'this' pointer is to return the object it points to.

The Statement 
return *this

inside a member function will return the object that invokes the function. This statement assumes importance when we want to compare two or more objects inside a member function and return the invoking object as a result.

#include<conio.h>
#include<iostream.h>
#include<string.h>
class person
{
char name[20];
int age;
public:
person(char nm[20],float ag)
{
strcpy(name,nm);
age=ag;
}
person *great(person *x)
{
if(x->age>=age)
return x;
else
return this:
}
void display( )
{
person p1("Irawen",101);
person p2("Pirawen",102);
clrscr( );
person *p=p1.great(&p2);
p->display( );
getch( );
}


Output:-
Name is--->Irawen              Age is--->101

Function Returning Pointer Object

We know that function can return any data type. In the same way we can return pointer variable that is user defined pointer variable or system defined pointer variable from the function.

The general syntax:
returntype * functionname(Argument_list)
{

}

Here returntype is the data type of the value which is returned by the function and functionname follows the usual rule of naming the identifiers.

Write a program to implement the concept of returning pointer object from function.

#include<conio.h>
#include<iostream'h>
class abs
{
int a;
public:
void accept(int a1)
{
a=a1;
}
abc *display(abc *B2)
{
abc *ab;
ab=B2;
cout<<"\n\tAddress of object accepted as argument--->"<<ab;
cout<<"\n\tValue of a is--->"<<ab->a;
return ab;
}
};
void main( )
{
abc ab1;
abc *B1;
clrscr( );
ab1.accept(10);
B1=ab1.display(&ab1);
cout<<"\n\tAddress of returning object--->"<<B1;
getch( );
}


Output:-
Address of object accepted as argument--->0⤫8f7bfff4
Value of a is--->10
Address of returning object--->0⤫8f7bfff4

Array of Pointers to Objects

We can create an array of objects using pointers. For this we can use following syntax.

classname *pointer_var[size];

WAP to demonstrate array of pointers to objects

#include<conio.h>
#include<iostream.h>
class emp
{
char name[20];
float age;
public:
void getdata( );
void putdata( );
};
void emp::getdata( )
{
cout<<"\n\nEnter name and age of employee";
cin>>name>>age;
}
void emp::putdata( )
{
cout<<"\n\n\t"<<Name is--->"<<name<<"\tAge is--->"<<age;
}
void main( )
{
emp lct[3];
emp *lect[3];
int i;
for(i=0;i<3;i++)
{
lect[i]=&lct[i];
}
for(i=0;i<3;i++)
{
cout<<"\n\tEnter Details of Lecturer"<<(i+1);
lect[i]->getdata( );
}
cout<<"\n\tInformation about of employee";
for(i=0;i<3;i++)
{
lect[i]->putdata( );
}
getch( );
}


Output:-
Enter Details of Lecturer 1
Enter name and age of employee Irawen 101
Enter Details of Lecturer 2
Enter name and age of employee Pirawen 102
Enter Details of Lecturer3
Enter name and age of employee Ntirawen 103
Information about of employee
Name is---> Irawen        Age is--->101
Name is--->Pirawen       Age--->102 
Name is--->Ntirawen     Age--->103

Pointer To Object

As we create a simple object of class similarly we can create object of the pointer type of class.

For Example if we have a class with the name item, then we can create an object for item class as
item x;

Whenever item is a class and x is an object of item class, similarly we can define object of the type pointer as item *ptr;

There are two ways to access the members of class using pointers
 1. The members of class can be accessed by using the arrow operator in the similar way as it is used in the structure variable.
 pointer_var->class_member;
  2. Another way is (*pointer_var).class_member;
      
  In this notation parenthesis is necessary since dot has a higher precedence over the indirection operator(*).


#include<conio.h>
#include<iostream.h>
class max
{
int m,n;
int largest(void)
{
if(m>n)
{
return m;
}
else
{
return n;
}
}
public:
void getdata( )
{
cout<<"\n\tEnter any two nos--->";
cin>>m>>n;
}
void putdata( )
{
cout<<"\n\tLargest no is--->"<<largest( );
}
};
void main( )
{
clrscr( );
max *obj;
obj->getdata( );
(*obj).putdata( );
getch( );
}

Output:-
Enter any two nos---> 34 89
Largest no is---> 89

Pointers to Strings

A string is an array of characters terminated by a special character called as a null character.

Pointer to the string is a pointer which is initialized to the base address of the first location in string.

Syntax for declaring a pointer to string.

Datatype *pointer_variable;
Ex : char *ptr;

To initialize the pointer to the address of the string , assign the pointer to the name of string or to the address of the first element of the string.

char str[10]="Irawen";

char *ptr;

ptr=str;    OR       ptr=&str[0];

WAP to find the length of string using pointer

#include<conio.h>
#include<iostream.h>
void main( )
{
char str[10], *ptr;
int cnt=0;
clrscr( );
cout<<"\n\n\tEnter Any String";
cin>>str;
ptr=&str[0];
while(*ptr!='\0')
{
cnt++;
ptr++;
}
cout<<"\n\n\tLength of the Given String is--->"<<cnt;
getch( );
}

Output:-
Enter Any String Irawen
Length of the Given String is--->6

WAP to copy one string into another string and print both the strings on output screen using pointers to strings.

#include<conio.h>
#include<iostream;h>
void main( )
{
char str1[20], str2[20];
char *ptr1, *ptr2;
clrscr( );
cout<<"\n\n\tEnter First String";
cin>>str1;
ptr1=&str1[0];
ptr2=&str2[0];
while(*ptr1!='\0')
{
*ptr2=*ptr1;
ptr1++;
ptr2++;
}
*ptr2='\0';
cout<<"\n\n\tEnter String is--->"<<str1;
cout<<"\n\n\tCopied String is--->"<<str2;
getch( );
}

Output:-
Enter First String Irawen
First String is--->Irawen
Coiped String is--->Irawen

WAP to concat two strings by using pointers to strings.

#include<conio.h>
#include<iostream.h>
void main( )
{
char str1[20], str2[10], *ptr1, *ptr2;
clrscr( );
cout<<"\n\n\tEnter the First String";
cin>>str1;
cout<<"\n\n\tEnter the Second String";
cin>>str2;
ptr1=&str1[0];
ptr2=&str2[0];
while(*ptr1!='\0')
{
ptr1++;
}'
while(*ptr2!='\0')
{
*ptr1=*ptr2;
ptr1++;
ptr2++;
}
*ptr1='\0'
cout<<"\n\n\tConcatenated String is--->"<<str1;
getch( );
}

Output:-
Enter the First String Ira
Enter the Second String wen
Concatenated String is--->Irawen

WAP to reverse the given string using pointers

#include<conio.h>
#include<iostream.h>
void main( )
{
char str1[10], *ptr1;
int len=0;
clrscr( );
cout<<"\n\n\tEnter the String";
cin>>str1;
ptr1=&str1[0];
while(*ptr1!='\0')
{
len=len+1;
ptr1++;
}
len--;
ptr1--;
cout<<"\n\n\tReverse String is--->";
while(len>0)
{
cout<<*ptr1;
ptr1--;
len--;
}
getch( );
}

Output:-
Enter the String irawen
Reverse String is--->newari

Tuesday, 3 April 2018

Pointer in Arrays

Consider the declaration
int b[5];
int *ptr;
The pointer to array is given as below
ptr=&b[0];
which is same as
ptr=b;
If the pointer is incremented to the next data elements , then address of the incremented value of the pointer will be same as the value of the next element.

ptr=&b[0]            *ptr=b[0]
ptr+1=&b[1]        *(ptr+1)=b[1]
ptr+2=&b[2]        *(ptr+2)=b[2]
ptr+3=&b[3]        *(ptr+3)=b[3]

The expression-
  value[i] is same as (value+i)
that is
b[i] ==*(b+i)
b[0] ==*(b+0)
b[1] ==*(b+1)
b[2] ==*(b+2)
b[3] ==*(b+3)

WAP to initialize and display five elements from array by using pointer to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[5]={10,20,30,40,50};
int *ptr, i;
clrscr( );
ptr=&a[0];
cout<<"\n\n\tElements in array are--->";
for(i=0;i<5;i++)
{
cout<<" "<<*ptr;
ptr++;
}
getch( );
}


Output :-
Element in array are---> 10 20 30 40 50

WAP to search  an element from array using pointers to array

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[5];
int *ptr, i, f=0, item;
clrscr( );
ptr=&a[0];
cout<<"\n\n\tEnter Five elements";
for(i=0;i<5;i++)
{
cin>>*ptr;
ptr++;
}
cout<<"\n\n\tEnter Element to search";
cin>>item;
ptr=&a[0];
for(i=0;i<5;i++)
{
if(*ptr==item)
{
cout<<"\n\n\tElement is searched in array at"<<" "<<i+1<<"th location";
f=1;
break;
}
ptr++;
}
if(f==0)
cout<<"\n\n\tElement is not searched in array";
getch( );
}

Output:-
Enter Five element 12 23 34 45 56

Enter Element to search 56

Element is searched in array at 5 th location

WAP to insert an element at location of array by using pointer to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[10], i, *ptr1,n,loc,ele;
clrscr( );
cout<<"\n\n\tEnter Size of the Array";
cin>>n;
ptr1=&a[0];
cout<<"\n\n\tEnter Element in the Array";
for(i=0;i<n;i++)
{
cin>>*ptr1;
ptr1++;
}
cout<<"\n\n\tEnter Location to insert in to array";
cin>>loc;
cout<<"\n\n\tEnter Element to insert into Array";
cin>>ele;
ptr1--;
for(i=n-1;i>=0;i--)
{
if(i==loc-1)
{
*(ptr1+1)=*ptr1;
*ptr1=ele;
}
*(ptr1+1)=*ptr1;
ptr1--;
}
ptr1=&a[0];
cout<<"\n\n\tElement in the Array after Insertion--->";
for(i=0;i<n+1;i++)
{
cout<<" "<<*ptr1;
ptr1++;
}
getch( );
}

Output:-
Enter Size of the Array 5
Enter Element in the Array 12 23 34 45 56
Enter Location to insert in to array 3
Enter Element to insert into Array 90
Element in the Array after Insertion is---> 12 12 23 90 45 56

WAP to delete an element from an array from the specified location using pointers to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[10],i,*ptr1,n,loc;
clrscr( );
cout<<"\n\n\tEnter Size of the Array";
cin>>n;
ptr1=&a[0];
cout<<"\n\n\t Enter the Elements in the Array";
for(i=0;i<n;i++)
{
cin>>*ptr1;
ptr1++;
}
cout<<"\n\n\t Enter the Location of element to be deleted";
cin>>loc;
ptr1=&a[loc];
for(i=loc-1;i<n;i++)
{
*ptr1=*(ptr1+1);
ptr1++;
}
ptr1=&a[0];
cout<<"\n\n\tElements in Array after deletion is--->";
for(i=0;i<n-1;i++)
{
cout<<" "<<*ptr1;
ptr1++;
}
getch( );
}

Output:-
Enter Size of the Array 5
Enter the Elements in the Array 12 23 34 45 56
Enter the location of element to be deleted 3
Elements in Array after deletion is---> 12 23 34 56

Pointers to Functions

1. Cpp allows functions to be referenced by a pointer.
2. A pointer to a function must be declared to be a pointer to the datatype returned by the functions like void , int , float and so on....
3. In addition , the argument type of the function must also be specified when a pointer is declared.
4. The argument declaration is a list of a formal argument separated by commas and enclosed in parenthesis.
5. The general Syntax of a pointer to a function is
    Returntype (*variable) (list of parameters);
   Ex : void (*ptr) (float a, float b, float c);
   In the above declaration , a pointer to a function returns void and takes formal arguments of two float and one int.
 Ex : float (*ptr) (char a, double b, int c, float d)
 In the above declaration , a pointer to a function returns a floating point value and takes the formal argument of char , double , int and float type.
6. After the declaration of pointer to a function , the address of the function must be assigned to a pointer.


WAP to find sum of three numbers and average using pointer to function.

#Include<conio.h>
#include<iostream.h>
void calavg(int a, int b, int c);
void (*ptr)(int a, int b, int c);
void main( )
{
int a1, b1, c1;
clrscr( );
cout<<"\n\tEnter Any three Values";
cin>>a1>>b1>>c1;
ptr=&calavg;
(*ptr)(a1,b1,c1);
getch( );
}
void calavg(int a, int b, int c)
{
int sum;
float avg;
sum=a+b+c;
avg=sum/3.0;
cout<<"\n\n\tSum of three nos is--->"<<sum;
cou<<"\n\n\tAverage is--->"<<avg;
}

Output:-
Enter Any three Values 2.23  45
Sum of three nos is--->80
Average is--->26.66666

WAP to demonstrate how a pointer to a function is declared to perform simple arithmetic operation addition, subtraction, multiplication and division of two nos.

#include<conio.h>
#include<iostream.h>
void calop(int a, int b);
void (*ptr)(int a, int b)
void main( )
{
int a1,b1;
clrscr( );
cout<<"\n\n\tEnter Any two nos";
cin>>a1>>b1;
ptr=&calop;
(*ptr)(a1,b1);
getch( );
}
void calop(int a1,int b1)
{
cout<<"\n\n\tAddition is---><<(a1+b1);
cout<<"\n\n\Subtraction is--->"<<(a1-b1);
cout<<\n\n\tMultiplication is--->"<<(a1*b1);
cout<<"\n\n\tDivision is---><<(a1/b1);
}

Output:-
Enter Any two nos 12  6
Addition is--->18
Subtraction is--->6
Multiplication is--->72
Division is--->2

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (354) Python Quiz (22) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses