Tuesday, June 03, 2014

Basic Operations on Array (Traversal, Insertion, Deletion, Search) - Data Structures - C++ Program (Procedural)

Problem Question


Implement the data structure, Array, and write a program to perform basic operations, Traversal, Insertion, Deletion, and Search on it.

Explanation of Problem


In this program, we are required to use array and perform the basic operations listed above on it. Since traversal is nothing but going through all the elements, there is no point performing only traversal since there won't be any output of it. So the loop that displays the whole array in my program is to be considered as traversal of the array. Search is implemented as sequential search for simplicity of the program.

Code


#include <iostream> //Support C++
#include <cstdlib> //For exit()

/**@Title: Array.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 03-06-2014*
*/

using namespace std;

int main()
{
  int Arr[100],choice=0,j,del,ins,pos,flag=0,len;
  cout<<"\nWelcome to ArrOps v1.0\nMade by Rogue Coder\n\n\aEnter the size of the array(upto 100): ";
  cin>>len;
  cout<<"\n\aEnter the elements of the array ";
  for(int i = 0; i < len; i++)
    cin>>Arr[i];
  do
  {
    cout<<"\nCurrently, the Array is: ";
    for(int i = 0; i < len; i++)
      cout<<" "<<Arr[i];
    cout<<"\n\nChoices:"
      <<"\n1. Delete an item"
      <<"\n2. Insert an item "
      <<"\n3. Find the position of an item"
      <<"\n4. Exit\n"
      <<"\nYour Choice: ";
    cin>>choice;
    switch(choice)
    {
    case 1:
      cout<<"\n\aEnter the item you wish to delete : ";
      cin>>del;
      for(int i = 0; i < len; i++)
      {
        if(Arr[i] == del)
        {
          len--;
          for(j = i; j < len + 1; j++)
            Arr[j] = Arr[j+1];
          flag = 2;
          i = -1;
        }
      }
      if(flag==2)
        cout<<"\a!!!Entry Deleted!!!\n";
      if(flag!=2)
        cout<<"\a!!!Entry not found!!!\n";
      flag = 0;
      break;

    case 2:
      if (len >= 100)
        cout<<"\n\nALREADY AT LIMITS!!\n\n";
      else
      {
        len++;
        cout<<"\aEnter the position where to insert: ";
        cin>>pos;
        cout<<"\aEnter the item : ";
        cin>>ins;
        for(j = len + 1; j >= pos; j--)
          Arr[j] = Arr[j - 1];
        Arr[pos - 1] = ins;
        cout<<"\n\a!!!New item added!!!\n";
      }
      break;

    case 3:
      cout<<"\aEnter the item to be found : ";
      cin>>ins;
      for(int i = 0; i < len; i++)
      {
        if(Arr[i] == ins)
        {
          cout<<"\aThe item is at: " << i+1 << endl;
          flag = 1;
        }
      }
      if(flag!=1)
        cout<<"\a!!!Value was not found in the array!!!";
      flag = 0;
      break;

    case 4:
      cout<<"\n\aThank you for using ArrOps v1.0\n\aMade by Rogue Coder\nPress any key to exit\a";
      cin.get();
      exit(0);
    default:
      cout << "\n\nWrong Choice\n\n";
      break;
    }
  }
  while(choice!=4);
  cin.get();
  return 0;
}

Explanation of Code


#include <iostream> -> The compiler calls the Preprocessor to include the IOSTREAM(Standard Input / Output Streams Library) header file into the program, thus letting the use of the Standard Input / Output Streams functions like std::cin and std::cout. As per C++11 specification, including <iostream> automatically includes also <ios>, <streambuf>, <istream>, <ostream> and <iosfwd>.

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

std::cin (extern istream cin) -> Standard Input Stream, and object of class istream. It is generally used with the extraction operator (>>), though we can use member functions like get (cin.get()), read (cin.read()), etc. for the input. The use of extraction operator is much more popular due to the fact that it aids in getting formatted input.

std::cout (extern ostream cout) -> Standard Output Stream, and object of class ostream. It is generally used with the insertion operator (<<), though we can use member functions like write (cout.write()) for the output. The use of insertions operator is much more popular due to the fact that it aids in giving formatted output.

using namespace std; -> In modern IDEs, we have to explicitly write std::cout instead of cout to use the ostream cout object. Namespace std helps in easing off the pain of writing std:: again and again. Though make sure you are not trapped! The classes defined in std should not be redefined by you. So in case you want to define a class 'distance', you can't do so if you have used std namespace. Tough you can define 'Distance' (capital D).

std::endl (ostream& endl (ostream& os)) -> This is a function which is used to insert a newline character and flush the stream. Because this function is a manipulator, it is designed to be used alone with no arguments in conjunction with the insertion (<<) operations on output streams.

int Arr[100],choice=0,j,del,ins,pos,flag=0,len; -> 'Arr' is the array of 100 integers. 'choice' is used for the switch and do-while loop. 'j' is one of the loop counters. 'del' is used to get user input for the number he wishes to delete. 'ins' is used to get the user input for the number he wishes to insert in the array. 'pos' is used to get the input from the user for the position where to insert a number in the array. 'flag' is used to print various messages. 'len' is used to denote the length of the array (upto 100).

for(int i = 0; i < len; i++)
cin>>Arr[i];
-> The user enters the array elements one by one. This loop can be considered an initial traversal operation.

cout<<"\nCurrently, the Array is: ";
for(int i = 0; i < len; i++)
cout<<" "<<Arr[i];
-> This is array traversal operation in my program. This step occurs before the menu is displayed to the user. This display of the array elements can be considered as a help to the user to keep track of the things.

cout<<"\n\aEnter the item you wish to delete : ";
cin>>del;
for(int i = 0; i < len; i++)
{
if(Arr[i] == del)
{
len--;
for(j = i; j < len + 1; j++)
Arr[j] = Arr[j+1];
flag = 2;
i = -1;
}
}
if(flag==2)
cout<<"\a!!!Entry Deleted!!!\n";
if(flag!=2)
cout<<"\a!!!Entry not found!!!\n";
flag = 0;
-> This is the case 1 where the user is asked to enter the element he wants to delete from the array. The user input gets stored in the variable 'del'. Using the for loop, we search for the element in array and if the element is found we delete it. A first, the variable 'len' is decremented so that the effective length of the array (which is traversed in various operations) is decreased. To delete the element, we shift the array entries successive to this found element one position left, thus overwriting the position. The inner for loop achieves this. The flag is set to 2 if the element is found. The line i = -1; in the inner for loop forces the outer loop to run again searching the array from element zero so that all possible matches can be deleted. Consider a case where the array holds, 1 as the first three elements. When the loop first runs, it deletes 1 at Arr[0]. But on second iteration, the 1 at Arr[1] will be shifted to Arr[0], and the outer for loop has already traversed 1 and thus won't be able to delete it. Thus I used i = -1; so that in case the number is found the program is forced to perform the search from element 0 so that none of the occurrences of the number to be deleted are left undeleted. Now if the flag was set to 2, that means the number was found and thus deleted, hence a message number deleted is printed, else Number not found is printed on the screen.

if (len >= 100)
cout<<"\n\nALREADY AT LIMITS!!\n\n";
else
{
len++;
cout<<"\aEnter the position where to insert: ";
cin>>pos;
cout<<"\aEnter the item : ";
cin>>ins;
for(j = len + 1; j >= pos; j--)
Arr[j] = Arr[j - 1];
Arr[pos - 1] = ins;
cout<<"\n\a!!!New item added!!!\n";
}
Here we handle the second case of insertion into the array. At first we check if the number of elements in the array are greater than or equal to 100. Since our Array is designed to handle 100 ints, if the if condition comes out to be true, we print that array is at limits and break from the case. But if that is not the case, we continue with the insertion process. At first the variable 'len' is incremented so that the effective length of the array (which is traversed in various operations) is increased. Then the user is asked to enter number and the position where to inser that number. A for loop is used that startes from the end of the array and goes left till the position where we wish to insert the number. It keeps shifting the entries one unit right in the array. That;s the reason why the loop is started at len + 1 (and not len) and goes till pos (and not pos + 1). Once this is done, the number the user wanted to insert is inserted at Arr[pos - 1] because the array is from 0 to len-1, and the user assumes it to be from 1 to len. "New item added" is printed on screen.

cout<<"\aEnter the item to be found : ";
cin>>ins;
for(int i = 0; i < len; i++)
{
if(Arr[i] == ins)
{
cout<<"\aThe item is at: " << i+1 << endl;
flag = 1;
}
}
if(flag!=1)
cout<<"\a!!!Value was not found in the array!!!";
flag = 0;
Here we habdle the situation of searching an element in the array. The user is asked to enter the number he wants to search. Then the for loop executes a sequential search on the array. Each time the element is found, a message indicating the success and the position of the element is printed on the screen. The 'flag' in such case is set to 1. Out of the loop, we check the value of 'flag' variable, if not 1, implies that the number was not present in the array and thus a message if failure is printed on the user's screen.

exit(0); -> This function is used to exit the program with an error code as it's argument. '0' implies normal exit. Other values are used for debugging purposes.

std::cin.get() -> This statement is used to pause our program, until user presses a key. This function is not necessary in your program, I use it to see my outputs at a paused screen. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)




Download Source Code


No comments:

Post a Comment

Need help?