Creating a dynamic array using malloc() and performing a Linear search on the Dynamic Data Structure.
Language : C
[sourcecode language='c']
//Dyanamic Linear search
#include
#include
void main()
{
int *a,count, i,x,found,n,val;
char newN,ch;
printf(“Enter the size of array : “);
scanf(“%d”, &n);
do{
a=(int *)malloc(sizeof(int));
count=0;
while(n!=0)
{
count++;
n–;
}
printf(“\nA new array for size %d has been created, would you like to change the size ? :”, count);
fflush(stdin);
scanf(“%c”, &newN);
if(newN==’Y’ || newN==’y')
{
printf(“Enter new Size : “);
scanf(“%d”, &n);
a=(int *)malloc(sizeof(int));
}
}while(newN==’Y’ || newN==’y');
for(i=0;i
printf(“Enter value for %d element “, i+1);
scanf(“%d”, & val);
*(a+i)=val;
}
do{
found=0;
printf(“\nEnter the element to be searched :”);
scanf(“%d”, &x);
for(i=0;i
if(*(a+i)==x)
{found=1;
break;
}
}
if(found==1)
printf(“\nThe element has been found at position %d!”,i+1);
else
printf(“\n %d was not found!”,x);
fflush(stdin);
printf(“\nSearch another element ? (Y/N) : “);
scanf(“%c”, &ch);
found=0;
}while(ch==’y'||ch==’Y');
}
[/sourcecode]






