Part 1: Dynamic Arrays Create a integer dynamic array. You must create your inte
ID: 649295 • Letter: P
Question
Part 1: Dynamic Arrays
Create a integer dynamic array. You must create your internal array on the heap (using malloc or new). Your dynamic array should have the following operations:
1) Insert - inserts an element at the specified index. Use geometric expansion to increase the size of your list if the index is out of the current bounds.
void insert(Vector * array, int index, int value);
2) Delete - deletes an element from the list at the specified index (use 0 for delete).
void remove(Vector * array, int index);
3) Read - return the number from the specified index, return 0 if the index is out of bounds
int read(Vector * array, int index);
You should have 3 loops in your main.
1) Loop 1: generate 100 random positive integers to fill your array
2) Loop 2: print your numbers using the read function
3) Loop 3: delete all numbers from your array using the remove function
Upon exiting, be sure to free all memory
Part 2: Profiling Your Code
1) Create another version of your insert function that uses incremental expansion (only add 1 to your array size when more space is needed
2) Using the clock() function from the time.h library, profile both geometric and incremental expansion using a loop of 10000 insertions
Your profiling code should look like:
start_t = clock();
//whatever you are profiling
end_t = clock();
result = (double) (end_t - start_t) / CLOCKS_PER_SEC;
Be sure to keep all non-essential code outside of the profiling code. It can throw off your profiling time.
3) Print out the times for each implementation
The code shouls be in C, and use both a seperate header file and a seperate source file. There should be no memory leak when ran with valgrind.
Explanation / Answer
#include<stdio.h>
#include<conio.h>
#include<time.h>
int insert(int *);
int read(int *);
int remov(int *);
void main()
{
int a[100];
int ch;
printf(" Enter 1 to insert element in array: ");
printf(" Enter 2 to view element in array: ");
printf(" Enter 3 to Delete element in array: ");
printf(" Enter any key to Exit: ");
printf(" enter the choice ");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert(a);
getch();
break;
case 2:
read(a);
getch();
break;
case 3:
remov(a);
getch();
break;
default:
exit(0);
}
}
}
int insert(int *a)
{
int i,n;
printf("Enter the no. of elements in array: ");
scanf("%d",&n);
printf(" Enter %d elements in array: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
a[i]='';
return *a;
}
int read(int *a)
{
int i;
for(i=0;a[i]!=NULL;i++)
{
printf(" Element of array=%d",a[i]);
}
return *a;
}
Int remov(int *a)
{
int c,i,j;
for(i=0;a[i]!=NULL;i++)
{
}
printf("Enter the position to delete element: ");
scanf("%d",&j);
if(j<=i)
{
for(c=j-1;c<i-1;c++)
{
a[c]=a[c+1];
}
printf(" Array after Deletion");
for(c=0;c<i-1;c++)
{
printf(" %d",a[c]);
}
}
return *a;
}