In this program we will learn how to enter data on the last index of array by assigning new memory location.
//Code starts
#include<iostream>
#include<conio.h>
using namespace std;
class array{
private:
int a[10],size,data,index;
public:
array(); //constructor
void create();
void print();
void insert();
};
array::array()
{
size=5;
index=size;
}
void array::create()
{
for(int i=0;i<size;i++)
{
cout<<"Enter data at index ["<<i<<"] : ";
cin>>a[i];
}
}
void array::print()
{
for(int i=0;i<size;i++)
{
cout<<"Data at index ["<<i<<"] = "<<a[i]<<endl;
}
}
void array::insert()
{
cout<<"Enter data to be inserted : ";
cin>>data;
for(int i=size-1;i=0;i++)
{
a[i+1]=a[i];
}
size++; // assigning new memory
a[index]=data; //copying new data on last index
cout<<"Data after insertion of "<<data<<" on index["<<index<<"]"<<endl;
}
int main() //mainfunction
{
array a; //creating object of class
a.create(); //calling create function of class
cout<<"-------------------------------------"<<endl;
a.print(); // calling print function of class
cout<<"-------------------------------------"<<endl;
a.insert(); //calling insert function of class
cout<<"-------------------------------------"<<endl;
a.print(); // calling print function of class
getch();
}
//Code ends
OUTPUT:
//Code starts
#include<iostream>
#include<conio.h>
using namespace std;
class array{
private:
int a[10],size,data,index;
public:
array(); //constructor
void create();
void print();
void insert();
};
array::array()
{
size=5;
index=size;
}
void array::create()
{
for(int i=0;i<size;i++)
{
cout<<"Enter data at index ["<<i<<"] : ";
cin>>a[i];
}
}
void array::print()
{
for(int i=0;i<size;i++)
{
cout<<"Data at index ["<<i<<"] = "<<a[i]<<endl;
}
}
void array::insert()
{
cout<<"Enter data to be inserted : ";
cin>>data;
for(int i=size-1;i=0;i++)
{
a[i+1]=a[i];
}
size++; // assigning new memory
a[index]=data; //copying new data on last index
cout<<"Data after insertion of "<<data<<" on index["<<index<<"]"<<endl;
}
int main() //mainfunction
{
array a; //creating object of class
a.create(); //calling create function of class
cout<<"-------------------------------------"<<endl;
a.print(); // calling print function of class
cout<<"-------------------------------------"<<endl;
a.insert(); //calling insert function of class
cout<<"-------------------------------------"<<endl;
a.print(); // calling print function of class
getch();
}
//Code ends
OUTPUT:
0 comments:
Post a Comment