xxxxxxxxxx
/*
=>Created in heap using pointers
*/
//Sum of given numbers to demonstrate dynamic array
#include <iostream>
using namespace std;
int main() {
int limit=0, sum=0;
cout << "How many numbers you want to insert ? " << endl;
cin >> limit;
int *p; // declared a pointer
p = new int[limit]; // pointed to an unnamed array into heap memory
for(int i=0; i<limit; i++){
cout << "Enter Value Number " << (i+1) << " : ";
cin >> p[i];
sum += p[i];
}
cout << "Sum of " << limit << " elements are: " << sum;
delete []p; // deleting the heap memory after using
p = NULL;// assining null insted of auto garbage value
return 0;
}
xxxxxxxxxx
class DynamicArray{
constructor(){
this.length=0;
this.data={}
}
get(index){
return this.data[index];
}
push(element){
this.data[this.length]= element;
this.length++;
return this.length;
}
pop(){
if(this.length == 0)
return undefined;
const popElement = this.data[this.length-1];
delete this.data[this.length-1];
this.length--;
return popElement;
}
insert(element, index){
if(index> this.length-1 || index<0)
return undefined;
this.length++;
for(let i= this.length-1; i>index; i--){
this.data[i] = this.data[i-1];
}
this.data[index] = element;
return this.data;
}
remove(index){
if(this.length == 0)
return undefined;
if(index > this.length-1 || index < 0)
return undefined;
const removedItem = this.data[index];
for(let i=index; i < this.length; i++){
this.data[i]=this.data[i+1];
}
delete this.data[this.length-1];
this.length--;
return removedItem;
}
}
const array = new DynamicArray();
array.push('Aayush');
array.push('Parth');
array.push('Abhishek');
array.push('Thalesh');
array.push('chiku');
console.log(array);
array.insert('Zoya',2);
console.log(array);