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 are arrays c++?
What does the linker do?
What is an associative container in c++?
List the issue that the auto_ptr object handles?
Why c++ is the best language?
Tell me can a pure virtual function have an implementation?
How many standards of c++ are there?
Can we get the value of ios format flags?
What are the 2 main types of data structures?
Do the names of parameters have to agree in the prototype, definition, and call to the function?
How do c++ struct differs from the c++ class?
In which header file does one find isalpha() a) conio.h b) stdio.h c) ctype.h
Explain linear search.
How do you flush a buffer in c++?
Write a program using display() function which takes two arguments.