write a program to insert an element into an array
Answer Posted / antony
/* Program to insert element into array */
#include<stdio.h>
#include<conio.h>
int n,pos;
void main()
{
int arr[50],i,ch;
void insert (int *);
void update (int *);
void delete (int *);
void search (int *);
void display (int *);
//clrscr();
printf("How Many Elements you will insert:-");
scanf("%d",&n);
printf("\n\tEnter Elements into Array");
for(i=0;i<n;i++)
scanf("\t%d",&arr[i]);
while(1)
{
printf("\n1.insert\n");
printf("2.Delete\n");
printf("3.Search\n");
printf("4.Display\n");
printf("5.Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(arr); display(arr); break;
case 2: delete(arr); display(arr); break;
case 3: search(arr); break;
case 4: display(arr); break;
case 5: exit(1);
}
}
getch();
}
void insert(int *arr)
{
int num,i;
printf("\nEnter the position");
scanf("%d",&pos);
if(pos==0 || pos>=n)
{
printf("Invalid position");
}
else
{
printf("\nEnter the number you want to insert into an array");
scanf("%d",&num);
/*shift the existing elements*/
for(i=n;i>=pos;i--)
arr[i]=arr[i-1];
arr[pos-1]=num;
}
}
void delete(int *arr)
{
int pos,i;
printf("\nEnter the position");
scanf("%d",&pos);
if(pos==0 || pos>=n)
{
printf("Invalid position");
}
else
{
for(i=pos-1;i<n;i++)
arr[i]=arr[i+1];
n--;
}
}
void display(int *arr)
{
int i;
printf("\nCurrent Array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",arr[i]);
}
}
void search(int *arr)
{
int i=0,tmp,tmp2=0;
printf("\nEnter the number u want to search:");
scanf("%d",&tmp);
for (i=0;i<=n;i++)
{
if(tmp==arr[i])
{
tmp2=i+1;
}
}
if (tmp2!=0)
{
printf("The element present in the position is: %d",tmp2);
}
else
{
printf("The element not present");
}
}
| Is This Answer Correct ? | 1 Yes | 2 No |
Post New Answer View All Answers
What is the best way to take screenshots of a window with c++ in windows?
What is a type library?
What is the basic of c++?
Where is atoi defined?
Is c++ built on c?
What are the advantages of pointers?
What are the differences between new and malloc?
What is oops in c++?
How would you use qsort() function to sort an array of structures?
Explain selection sorting. Also write an example.
How do we implement inheritance in c++?
What are the advantages of using a pointer? Define the operators that can be used with a pointer.
what is VOID?
which of the following is not an secondary constant a) array b) real c) union
Explain the difference between static and dynamic binding of functions?