In the program below, inside the main
function, while entering elements in an array it runs one more time and also the insertion function is inserting random values.
I think I am doing a mistake in the insertion function. Here I want to first shift the elements and then I want to insert when it found an element smaller than that I want to insert.
#include<stdio.h>
#include<stdlib.h>
struct Array
{
int *A;
int length;
int size;
} p;
void Display(struct Array p)
{
int i;
for(i=0;i<p.length;i++)
{
printf(" %d ",p.A[i]);
}
}
// I think I am doing a mistake in the insertion function below. Here I want to first shift the elements and then I want to insert when it found an element smaller than that I want to insert.
void inserting(struct Array *p,int x)
{
int i=p->length-1;
if(p->length=p->size)
{
return;
}
while(i>=0 && p->A[i]>x)
{
p->A[i+1]=p->A[i];
i--;
}
p->A[i+1]=x;
p->length++;
}
int main()
{
int i,ch,index,el,choice=1,c;
printf("Enter size of array\n");
scanf("%d",&p.size);
p.A=(int *)malloc(p.size * sizeof(int));
printf("Enter length of Array\n");
scanf("%d",&p.length);
printf("ENTER elements in an array\n");
for(i=0;i<p.length;i++)
{
scanf("%d\n",&p.A[i]);
}
// The above loop takes input one more time than expected.
inserting(&p,20);
Display(p);
return 0;
}