Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Data Structure 01 : Operations on arrays
//
// main.cpp
// dataStructures01
//
#include <iostream>
int const SIZE =6;
int A[SIZE] = {1,2,2,4,5} , N = 5; // what is N??
bool isFull(){ if(N == SIZE){ return true; }else{ return false; } }
bool isEmpty(){ if(N == 0 ) return true; else return false; }
int find_location_to_insert(int ITEM)
{
int first = 0 , last = N-1 , K; // why not used SIZE instead of N ??
for( K = first ; K <= last ; K++)
{if(A[K] > ITEM)
{
return K;
}
}return K;
}
void insert(int K , int ITEM)
{// j =4 , k = 3
int j = N-1;
while(j >= K){ // TO SOLVE NEXT LINE PROBLEM ADD -1 TO J
A[j+1] = A[j]; // if j is the last index j+1 will be out of boundary !!
j--; }
A[K] = ITEM;
N++; // why !!
}
void traverse(){
int first = 0 , last = N-1;
for(int l = first ; l <= last ; l++){
std::cout<< A[l]<<"\t";
}
}
int find_location_to_delete(int ITEM){
int first = 0 , last = N-1 , K;
for( K= first ; K <= last ; K++){
if(A[K] == ITEM){ // delete 2 index 1
return K;
}
}
K = -1; // there is somwthing wrong here !!
return K;
}
int Delete(int K , int ITEM){
ITEM = A[K];
for(int j =K ; j <= N ; j++){// TO SOLVE NEXT LINE PROBLEM ADD -1 TO J
A[j] = A[j+1]; // {1,2,2,4,5} out of boundary !!
}
N--; // why!!
return ITEM;
}
int main() {
int ch , ITEM , K , loop = 1;
while(loop){
std::cout<< "\n\n";
std::cout<< "1- insert value\n";
std::cout<< "2- delete value\n";
std::cout<< "3- traverse array\n";
std::cout<< "4- exit\n\n";
std::cout<< "your choice: \n"; std::cin>>ch;
switch(ch){
case 1:
if(isFull()){ std::cout<< "\n Array is full\n"; break;}
std::cout<< "\n For Insertion, Put a value:";
std::cin>> ITEM;
K = find_location_to_insert(ITEM);
insert(K, ITEM);
break;
case 2:
if(isEmpty()){ std::cout<<"\n Array is empty\n"; break;}
std::cout<< "For Deletion, Put a value : ";
std::cin>> ITEM;
K = find_location_to_delete(ITEM);
if(K==-1){ std::cout<<"\n"<<ITEM<<"not found in array\n";}
else{ std::cout<< "\n"<<Delete(K,ITEM)<<" deleted from array \n";}
break;
case 3:
if(isEmpty()){ std::cout<<"\n array is empty\n"; break;}
traverse();
break;
case 4:
loop = 0; break;
default:std::cout<< "\n invalid choice\n";
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment