Aim
Write a menu driven program that implement
following operation (using separate function) on a linear array
1) Insert a new element at end as well as
at a given position
2) Delete an element whose value is given
or whose position is given.
3) To find a location of given element
4) To display the elements of linear array
Source Code
#include
<iostream>
using
namespace std;
void
takeArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
}
void
printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << "
";
}
}
void
insertAtEnd(int arr[], int size)
{
int newKey;
cout << "Enter the new Element
to insert ";
cin >> newKey;
size = size + 1;
arr[size - 1] = newKey;
printArray(arr, size);
}
void
insertAtPosition(int arr[], int size)
{
int pos;
cout << "Enter the position :
";
cin >> pos;
int newKey;
cout << "Enter the new key :
";
cin >> newKey;
for (int i = size - 1; i >= pos - 1;
i--)
{
arr[i + 1] = arr[i];
}
arr[pos - 1] = newKey;
printArray(arr, size);
}
void
deleteElement(int arr[], int size, int x)
{
int
i, j;
int found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == x)
{
for (j = i; j < (size - 1); j++)
arr[j] = arr[j + 1];
found = 1;
i--;
size--;
}
}
if (found == 0)
cout << "\nElement doesn't
found in the Array!";
else
{
cout << "\nElement Deleted
Successfully!";
cout << "\n\nThe New Array
is:\n";
for (i = 0; i < size; i++)
cout << arr[i] <<
" ";
}
cout << endl;
}
int
Search(int arr[], int n, int key)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "Element is
found";
}
}
return -1;
}
int
SearchIndex(int arr[], int size, int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key)
{
return i;
}
}
return -1;
}
int
main()
{
int size, key;
cout << "Enter the size of an
Array: ";
cin >> size;
int ch;
int arr[10];
takeArray(arr, size);
while (1)
{
cout << "\n1.Insert at end
" << endl;
cout << "2.Insert at
position " << endl;
cout << "3.Search key is
present or not " << endl;
cout << "4.Search key is
index " << endl;
cout << "5.Display
Element" << endl;
cout << "6.Delete
Element" << endl;
cout << "6.Exit"
<< endl
<< endl;
cout << "Enter the Choice:
";
cin >> ch;
switch (ch)
{
case 1:
insertAtEnd(arr, size);
break;
case 2:
insertAtPosition(arr, size);
break;
case 3:
cout << "Enter the key
to Search: ";
cin >> key;
Search(arr, size, key);
break;
case 4:
cout << "Enter the key
to Search its index value : ";
cin >> key;
cout << "Element is
found at index " << SearchIndex(arr, size, key) << "
position" << endl;
break;
case 5:
printArray(arr, size);
cout << endl;
break;
case 6:
int x;
cout << "Enter the
Element to delete: ";
cin >> x;
deleteElement(arr, size, x);
case 7:
exit(0);
default:
cout << "invalid";
break;
}
}
}
Result/Output
thanks
ReplyDelete