Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Monday, July 27, 2015

Copy Array to another Reverse Order - C Program (Procedural)


Problem Question



Write a program to copy the contents of one array into another in the reverse order.

Explanation of Problem



The user enters 25 numbers in an array. The program needs to copy this array into another in reverse order.




Code



#include <stdio.h>
/**@Title: ReverseArray.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-07-2015*
*/

int main()
{
    int arr1[25], arr2[25], i, j;
    for ( i = 0, j = 24; i < 25; i++, j-- )
    {
        scanf ("%d", &arr1[i]);
        arr2[j] = arr1[i];
    }
    printf("\nArray 1\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr1[i]);
    }
    printf("\nArray 2\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr2[i]);
    }
    printf("\n\n");
    system("pause");
    return 0;
}





Explanation of Code



#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

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. If you use the traditional C, you may use void as the return type. 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.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

int arr1[25], arr2[25], i, j; -> Here we define the variables we are going to use in our program.
arr1[25], arr2[25] hold the user input numbers and reversed array respectively.
i, j are used as the loop variables to loop through the array.

    for ( i = 0, j = 24; i < 25; i++, j-- )
    {
        scanf ("%d", &arr1[i]);
        arr2[j] = arr1[i];
    }


Here we loop through both arrays and do the required things. Look at the for loop definition. We have used the "," (comma) operator to initialise and increment multiple variables. This saves a few lines of code. Loop variables are initialised in one go and incrmeented/decremented in one go as well.
We then take user input to build first array. In the next step we copy that value in the last element of the second array. The loop variable "i" traverses "arr1" from left to right, and loop variable "j" traverses "arr2" from right to left. Hence we increment "i" and decrement "j".

    printf("\nArray 1\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr1[i]);
    }
    printf("\nArray 2\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr2[i]);
    }


Here we just loop through both arrays and print them for reference.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.




Output(s)









Download Source Code





Thursday, July 09, 2015

Count Number Types C Program - Procedural


Problem Question



Write a program to get the number of odd, even, positive and negative numbers from an array of numbers.

Explanation of Problem



The user enters 25 numbers in an array. The program needs to print the number of odd, even, positive and negative numbers input by the user.




Code



#include <stdio.h>
/**@Title: CountNumberTypes.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-07-2015*
*/

int main()
{
    int elements[25], loopCounter, positiveCount = 0, negativeCount = 0, evenCount = 0, oddCount = 0;

    for (loopCounter = 0; loopCounter < 25; loopCounter++)
    {
        printf ("\nEnter Value #%d: ", loopCounter + 1);
        scanf ("%d", &elements[loopCounter]);
        if (elements[loopCounter] < 0)
        {
            negativeCount++;
        }
        else
        {
            positiveCount++;
        }
        if (elements[loopCounter] % 2 == 0)
        {
            evenCount++;
        }
        else
        {
            oddCount++;
        }
    }
    printf ("\nNumber of Positive Numbers: %d", positiveCount);
    printf ("\nNumber of Negative Numbers: %d", negativeCount);
    printf ("\nNumber of Even Numbers: %d", evenCount);
    printf ("\nNumber of Odd Numbers: %d\n", oddCount);
    system("pause");
    return 0;
}





Explanation of Code



#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

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. If you use the traditional C, you may use void as the return type. 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.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

int elements[25], loopCounter, positiveCount = 0, negativeCount = 0, evenCount = 0, oddCount = 0; -> Here we define the variables we are going to use in our program.
elements[25] hold the user input numbers.
loopCounter is used as the loop variable to loop through the array. The variables positiveCount, negativeCount, evenCount, oddCount are used to track the count of each type of number.

for (loopCounter = 0; loopCounter < 25; loopCounter++)
    {
        printf ("\nEnter Value #%d: ", loopCounter + 1);
        scanf ("%d", &elements[loopCounter]);
        if (elements[loopCounter] < 0)
        {
            negativeCount++;
        }
        else
        {
            positiveCount++;
        }
        if (elements[loopCounter] % 2 == 0)
        {
            evenCount++;
        }
        else
        {
            oddCount++;
        }
    }


Here we loop through the entire array, get user input, and each input is checked whether it's odd/even/negative/positive. Appropriate count variable is incremented to store the count.

printf ("\nNumber of Positive Numbers: %d", positiveCount);
printf ("\nNumber of Negative Numbers: %d", negativeCount);
printf ("\nNumber of Even Numbers: %d", evenCount);
printf ("\nNumber of Odd Numbers: %d\n", oddCount);


After the loop, here we print the values of each variable to give the output stating the count of each number type in the user input.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.




Output(s)









Download Source Code





Wednesday, August 27, 2014

Implementing a Stack using Array - Data Structures - C++ Program (Object Oriented)

Problem Question


To implement stack using array

Explanation of Problem


In this program we would be using the basic data structure array, to implement stack which is a widely used data structure. A stack is a LIFO (Last In First Out) data structure. This means the data that is entered in the stack latest, is the first to be taken out, just like a stack of plates. In the implementation of such a data structure, we need an important pointer, called Top of Stack that points to the Top of the stack. It is used to check the Stack Overflow (Stack Full) condition. The operation via which we insert a new element into the stack is called Push Operation. Taking the analogy of a stack of plates, when a new plate is inserted into the stack, the rest of the plates are “pushed” down, so the operation is called Push Operation. Just like that, when an element is removed, it is called Pop Operation.

Code


#include <iostream>
/**@Title: OOarray_Stack.cpp*
*@Programming Paradigm: Object Oriented*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-08-2014*
*/
class myArrayStack
{
private:
  int stackArray [ 1000 ];
  int topOfStack;

public:
  myArrayStack()
  {
    topOfStack = 0;
  }

  void pop()
  {
    if ( topOfStack <= 0 )
      std::cout << "\n\a\aStack Underflow!\n";
    else
      std::cout << std::endl << stackArray [ --topOfStack ] << " popped out of stack Successful\n";
  }

  void push(int element)
  {
    if ( topOfStack >= 1000 )
      std::cout << "\n\n\a\aStack Overflow!\n\n\a\a";
    else
    {
      stackArray [ topOfStack++ ] = element;
      std::cout << element << " pushed on stack successfully\n";
    }
  }

  void displayStack()
  {
    int i = 0;
    std::cout << std::endl << "Stack: ";
    if ( topOfStack <= 0 )
      std::cout << "\n\a\a!!!STACK EMPTY!!!\n";
    else
    {
      for ( i = 0; i < topOfStack - 1; i++ )
        std::cout << stackArray [ i ] << " ";
      std::cout << stackArray [ topOfStack - 1 ] << std::endl;
    }
  }
};

int main()
{
  myArrayStack myStack;
  int choice = 0, elementOfStack;
  std::cout << "\a\aWelcome to Stack v2.0\nMade by Rogue Coder\n\nThis Stack has a limit of 1000 elements.";
  do
  {
    std::cout << "\n\aMenu:\n1. Push\n2. Pop\n3. Display\n4. Exit\nYour Choice: ";
    std::cin >> choice;
    switch ( choice )
    {
    case 1:
      std::cout << "\nEnter the element you wish to push on stack: ";
      std::cin >> elementOfStack;
      myStack.push( elementOfStack );
      break;
    case 2:
      myStack.pop();
      break;
    case 3:
      myStack.displayStack();
      break;
    case 4:
      std::cout << "\n\n\a\aThank You for using Stack v2.0\nMade by Rogue Coder\nPress any key to exit.";
      std::cin.get();
      break;
    default:
      std::cout << "\n\n\a\a!!!Wrong Choice!!!\n\n";
      break;
    }
  }
  while ( choice != 4 );
  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.

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 stackArray[1000], topOfStack represent the private variables in our class myArrayStack. choice = 0, elementOfStack are the basic variables that are used in the main function. stackArray is the array which we are going to transform into a Stack. The variable, choice, is used to store the user’s choice in our menu driven program. elementOfStack denotes the value that user wishes to push onto the stack. topOfStack is the variable that acts as the pointer to top of the stack.

myArrayStack()
{
topOfStack = 0;
}
-> This is the constructor that is used to initialise topOfStack pointer.

void pop()
{
if ( topOfStack <= 0 )
std::cout << "\n\a\aStack Underflow!\n";
else
std::cout << std::endl << stackArray [ --topOfStack ] << " popped out of stack Successful\n";
}
-> This is the first method of our program, in which the program first inspects for stack underflow. If the topOfStack is already pointing at the base of stack(0), then it means the stack is empty, hence nothing can be popped. Thus, “stack underflow” is displayed. Else, the element is removed from the stack, i.e, topOfStack is decremented. Actually, all the referencing in stack depends on topOfStack pointer. Thus, if there is an element that is out of bounds of it can never be referenced. This is how we pop the element.

void push(int element)
{
if ( topOfStack >= 1000 )
std::cout << "\n\n\a\aStack Overflow!\n\n\a\a";
else
{
stackArray [ topOfStack++ ] = element;
std::cout << element << " pushed on stack successfully\n";
}
}
-> This is the second method in our program. In this method we implement the Push Operation. As the control enters here, we check the pointer topOfStack. If it has already crossed the top(we have a 100 element storage in our stack, thus 0-99), user gets the message of Stack Overflow. Else, the method uses the user input which is passed as the argument to this method. The element is then pushed on stack and the topOfStack is incremented by one.


void displayStack()
{
int i = 0;
std::cout << std::endl << "Stack: ";
if ( topOfStack <= 0 )
std::cout << "\n\a\a!!!STACK EMPTY!!!\n";
else
{
for ( i = 0; i < topOfStack - 1; i++ )
std::cout << stackArray [ i ] << " ";
std::cout << stackArray [ topOfStack - 1 ] << std::endl;
}
}
-> The third method of our program where the stack is displayed to the user. This is just for information purpose, though no such operation on stacks exists. Stacks actually have only push/pop operations so that only the most recent information can be referenced. So here, we just check if the stack is empty and display the appropriate message to the user, else the for loop traverses the array and displays the stack to the user.

myArrayStack myStack;
myStack.push( elementOfStack );
myStack.pop();
myStack.displayStack();
-> The first statement creates an instance of the class myArrayStack. The rest of the statements call different methods of the class of which myStack is an instance of.

do{..}while() -> The program loop which encapsulates the whole program. Until the user chooses to exit the program, the control loops within this.

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



Saturday, August 09, 2014

Implementing a Stack using Array - Data Structures - C++ Program (Procedural)

Problem Question


To implement stack using array

Explanation of Problem


In this program we would be using the basic data structure array, to implement stack which is a widely used data structure. A stack is a LIFO (Last In First Out) data structure. This means the data that is entered in the stack latest, is the first to be taken out, just like a stack of plates. In the implementation of such a data structure, we need an important pointer, called Top of Stack that points to the Top of the stack. It is used to check the Stack Overflow (Stack Full) condition. The operation via which we insert a new element into the stack is called Push Operation. Taking the analogy of a stack of plates, when a new plate is inserted into the stack, the rest of the plates are “pushed” down, so the operation is called Push Operation. Just like that, when an element is removed, it is called Pop Operation.

Code


/**@Title: Array_Stack.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-08-2014*
*/
#include <iostream>

int main()
{
  int stackArray[100], choice = 0, elementOfStack, topOfStack = 0, i;
  std::cout << "\a\aWelcome to Stack v1.0\nMade by Rogue Coder\n\nThis Stack has a limit of 100 elements.";
  do
  {
    std::cout << "\n\aMenu:\n1. Push\n2. Pop\n3. Display\n4. Exit\nYour Choice: ";
    std::cin >> choice;
    switch ( choice )
    {
    case 1:
      if ( topOfStack >= 99 )
        std::cout << "\n\n\a\aStack Overflow!\n\n\a\a";
      else
      {
         std::cout << "\nEnter the element you wish to push on stack: ";
         std::cin >> elementOfStack;
        stackArray [ topOfStack++ ] = elementOfStack;
        std::cout << "PUSH Operation Successful\n";
      }
      break;
    case 2:
      if ( topOfStack <= 0 )
        std::cout << "\n\a\aStack Underflow!\n";
      else
        std::cout << std::endl << stackArray [ --topOfStack ] << " popped out of stack Successful\n";
      break;
    case 3:
      std::cout << std::endl << "Stack: ";
      if ( topOfStack <= 0 )
        std::cout << "\n\a\a!!!STACK EMPTY!!!";
      else
      {
        for ( i = 0; i < topOfStack - 1; i++ )
          std::cout << stackArray [ i ] << " ";
        std::cout << stackArray [ topOfStack - 1 ];
      }
      break;
    case 4:
      std::cout << "\n\n\a\aThank You for using Stack v1.0\nMade by Rogue Coder\nPress any key to exit.";
      std::cin.get();
      break;
    default:
      std::cout << "\n\n\a\a!!!Wrong Choice!!!\n\n";
      break;
    }
  }
  while ( choice != 4 );
  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.

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 stackArray[100], choice = 0, elementOfStack, topOfStack = 0, i; -> These are the basic variables that form the backbone of our program. stackArray is the array which we are going to transform into a Stack. The variable, choice, is used to store the user’s choice in our menu driven program. elementOfStack denotes the value that user wishes to push onto the stack. topOfStack is the variable that acts as the pointer to top of the stack. The variable, i, is used as the loop counter.

if ( topOfStack > 99 )
std::cout << "\n\n\a\aStack Overflow!\n\n\a\a";
else
{
std::cout << "\nEnter the element you wish to push on stack: ";
std::cin >> elementOfStack;
stackArray [ topOfStack++ ] = elementOfStack;
std::cout << "PUSH Operation Successful\n";
}
-> This is the first case in our program. In this case we implement the Push Operation. As the control enters here, we check the pointer topOfStack. If it has already crossed the top(we have a 100 element storage in our stack, thus 0-99), user gets the message of Stack Overflow. Else, the program prompt for user input. The element is then pushed on stack and the topOfStack is incremented by one.

if ( topOfStack <= 0 )
std::cout << "\n\a\aStack Underflow!\n";
else
std::cout << std::endl << stackArray [ --topOfStack ] << " popped out of stack Successful\n";
-> This is the second case of our program, in which the program first inspects for stack underflow. If the topOfStack is already pointing at the base of stack(0), then it means the stack is empty, hence nothing can be popped. Thus, “stack underflow” is displayed. Else, the element is removed from the stack, i.e, topOfStack is decremented. Actually, all the referencing in stack depends on topOfStack pointer. Thus, if there is an element that is out of bounds of it can never be referenced. This is how we pop the element.

std::cout << std::endl << "Stack: ";
if ( topOfStack <= 0 )
std::cout << "\n\a\a!!!STACK EMPTY!!!";
else
{
for ( i = 0; i < topOfStack - 1; i++ )
std::cout << stackArray [ i ] << " ";
std::cout << stackArray [ topOfStack - 1 ];
}
-> The third case of our program where e stack is displayed to the user. This is just for information purpose, though no such operation on stacks exists. Stacks actually have only push/pop operations so that only the most recent information can be referenced. So here, we just check if the stack is empty and display the appropriate message to the user, else the for loop traverses the array and displays the stack to the user.

do{..}while() -> The program loop which encapsulates the whole program. Until the user chooses to exit the program, the control loops within this.

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



Sunday, July 20, 2014

Implementing a Linear Queue using Array - Data Structures - C++ Program (Object Oriented)

Problem Question


To implement Linear Queue using array

Explanation of Problem


In this problem, the basic need is to have an array as the basic data structure. We would be making logics and attaching them to this basic array of ours that would make it a linear queue. So basically, this is the enhancement of the basic data structure array, to evolve it into a linear queue. A linear queue is identified by two main pointers, one is the head or the front of queue, and the other is the tail or the rear of the queue. The most important thing to understand about a linear queue is that, all the new data gets inserted at the rear, and any deletions are done at the front, just like a real life queue. Any new person joins a queue at the rear and the person to leave the queue is the person at the front. Just keeping these two restrictions on the addition and deletion to an array, we get the linear queue in place.

NOTE: To keep the program simple, we have kept the size of the queue as 1000. You can alter that as per your needs.

Code


/**@Title: ooArray_Queue.cpp*
*@Programming Paradigm: Object Oriented*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 20-07-2014*
*@Updated: 28-07-2014*
*/
#include <iostream>

class myArrayQueue
{
private:
  int queueArray [ 1000 ];
  int frontOfQueue;
  int rearOfQueue;

public:
  myArrayQueue()
  {
    frontOfQueue = 0;
    rearOfQueue = 0;
  }

  void displayQueue()
  {
    int i;
    std::cout << "\nQueue:\n";
    if ( rearOfQueue == frontOfQueue )
      std::cout << "\n\aQUEUE EMPTY!!\n\a";
    else
      for ( i = frontOfQueue; i < rearOfQueue; i++ )
        std::cout << queueArray [ i ] << " ";
  }

  void enterIntoQueue(int element)
  {
    if ( rearOfQueue >= 1000 )
      std::cout << "\n\a!!QUEUE OVERFLOW!!\n";
    else
      queueArray [ rearOfQueue++ ] = element;
  }

  void removeFromQueue()
  {
    int i;
    if ( rearOfQueue <= frontOfQueue )
      std::cout << "\n\a!!QUEUE UNDERFLOW!!\n";
    else
    {
      std::cout << std::endl << queueArray [ frontOfQueue ] << " removed!";
      frontOfQueue++;
    }
  }
};

int main()
{
  myArrayQueue myQueue;
  int choice = 0, elementOfQueue;
  std::cout << "\aWelcome to Queue v2.1\n\aMade by Rogue Coder\n\nThe Queue has a limit of 1000 elements.";
  do
  {
    std::cout << "\n\n\aMenu:\n1. Enter\n2. Remove\n3. Display\n4. Exit\nYour Choice: ";
    std::cin >> choice;
    switch ( choice )
    {
    case 1:
      std::cout << "\nEnter the element to fed into Queue: ";
      std::cin >> elementOfQueue;
      myQueue.enterIntoQueue ( elementOfQueue );
      break;

    case 2:
      myQueue.removeFromQueue();
      break;

    case 3:
      myQueue.displayQueue();
      break;

    case 4:
      std::cout << "\n\n\aThank You for using Queue v2.1\n\aMade by Rogue Coder\nPress any key to exit.";
      std::cin.get();
      break;

    default:
      std::cout << "\n\n\a!!!WRONG CHOICE!!!\a";
      break;
    }
  }
  while ( choice != 4 );
  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.

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.

myArrayQueue()
{
frontOfQueue = 0;
rearOfQueue = 0;
}
-> This is the constructor of our myArrayQueue class. It is a special method that is used to initialise the variables when the class is referenced with a new object. Thus, we assign both head & tail of queue to point at the beginning of the queue, since we have newly formed, empty queue.

if ( rearOfQueue == frontOfQueue )
std::cout << "\n\aQUEUE EMPTY!!\n\a";
else
for ( i = frontOfQueue; i < rearOfQueue; i++ )
std::cout << queueArray [ i ] << " ";
}
-> This is our next method, which is used to display the queue to the user. The method first inspects the rearOfQueue, which if found to be pointing to same location as frontOfQueue, the queue is considered as empty. Else, the control is transferred to a for loop, which traverses the queue from front to rear, displaying each element one by one to the user.

else
queueArray [ rearOfQueue++ ] = element;
}
-> The next method is used to insert a new element into the queue. To do this, we first check the rearOfQueue. If it is at the maximum expected value, a message is displayed to the user, QUEUE OVERFLOW, since this means that the queue is full. Else, the new element is added at the rear of the queue, and the rear is incremented by one. The new element is passed from the calling function and is accepted as a parameter to the method.

else
{
std::cout << std::endl << queueArray [ frontOfQueue ] << " removed!";
frontOfQueue++;
}
}
-> In this method the rearOfQueue is inspected first. If it points to a location sa,e as frontOfQueue or before that, that means the queue is empty, and thus a message is displayed to the user, QUEUE UNDERFLOW. Else, the element at the front of queue is displayed to the user(for information) as deleted from queue followed by the frontOfQueue getting incremented by one to point to the new front of the queue. Actually, an element is never deleted in case of linear queues, it is only orphaned. Thus, due to memory constraints, queues are used in lesser situations.

do {…} while() ->The do-while loop is our program loop which is used to make the program interactive and menu-driven. The user enters the choice. Depending on the choice, the switch-case logic calls the method of the object. When the user wishes to enter into the queue, the program accepts the user input and calls the method which does the same, and passes the element to the method when calling it. When the user chooses ‘4’, the program exits.

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


Friday, July 04, 2014

Implementing a Linear Queue using Array - Data Structures - C++ Program (Procedural) [UPDATED]

Problem Question


To implement Linear Queue using array

Explanation of Problem


In this problem, the basic need is to have an array as the basic data structure. We would be making logics and attaching them to this basic array of ours that would make it a linear queue. So basically, this is the enhancement of the basic data structure array, to evolve it into a linear queue. A linear queue is identified by two main pointers, one is the head or the front of queue, and the other is the tail or the rear of the queue. The most important thing to understand about a linear queue is that, all the new data gets inserted at the rear, and any deletions are done at the front, just like a real life queue. Any new person joins a queue at the rear and the person to leave the queue is the person at the front. Just keeping these two restrictions on the addition and deletion to an array, we get the linear queue in place. But the major drawback of using a queue is that, removing elements from queue means orphaning the front of queue at each deletion. This means the space is not reusable.

NOTE: To keep the program simple, we have kept the size of the queue as 100. You can alter that as per your needs.

Code


/**@Title: Array_Queue.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 04-07-2014*
*@Updated: 28-07-2014*
*/
#include <iostream>
int main()
{
  int queueArray [ 100 ], choice = 0, frontOfQueue = 0, rearOfQueue = 0, elementOfQueue, i;
  std::cout << "\aWelcome to Queue v1.1\n\aMade by Rogue Coder\n\nThis Queue can handle 100 elements.";
  do
  {
    std::cout << "\nMenu:\n1. Enter\n2. Remove\n3. Display\n4. Exit\nYou Choice: ";
    std::cin >> choice;
    switch ( choice )
    {
    case 1:
      if ( rearOfQueue >= 100 )
        std::cout << "\n\a!!QUEUE OVERFLOW!!\n";
      else
      {
        std::cout << "\nEnter the element to be fed into Queue: ";
        std::cin >> elementOfQueue;
        queueArray [ rearOfQueue++ ] = elementOfQueue;
      }
      break;
    case 2:
      if ( rearOfQueue <= frontOfQueue )
        std::cout << "\n\a!!QUEUE UNDERFLOW!!\n";
      else
      {
        std::cout << std::endl << queueArray [ frontOfQueue ] << " removed!";
        frontOfQueue++;
      }
      break;
    case 3:
      std::cout << "\nQueue:\n";
      if ( rearOfQueue == frontOfQueue )
        std::cout << "\n\a!!QUEUE EMPTY!!\n";
      else
        for ( i = frontOfQueue; i < rearOfQueue; i++ )
          std::cout << queueArray [ i ] << " ";
      break;
    case 4:
      std::cout << "\n\n\aThank You for using Queue v1.1\n\aMade by Rogue Coder\n\aPress any key to exit";
      std::cin.get();
      break;
    default:
      std::cout << "\n\n\a\a!!!WRONG CHOICE!!!\n\n\a\a";
      break;
    }
  }
  while( choice != 4 );
  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. Though 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 queueArray [ 100 ], choice = 0, frontOfQueue = 0, rearOfQueue = 0, elementOfQueue, i -> These are the variables that will be used to hold various values in the program. queueArray is the basic array which we will be using to implement Linear Queue. frontOfQueue and rearOfQueue represent the head and tail of the linear queue respectively. choice is used to store the user’s choice in the menu, and elementOfQueue represents the element we are working with, in case of insertion. i acts as the loop counter in the various for loops used through the program.

do {…}while( choice != 4 ); -> This is our main program loop in which the control is trapped until the user decides to exit the program with the choice 4.

if ( rearOfQueue >= 100 )
std::cout << "\n\a!!QUEUE OVERFLOW!!\n";
else
{
std::cout << "\nEnter the element to be fed into Queue: ";
std::cin >> elementOfQueue;
queueArray [ rearOfQueue++ ] = elementOfQueue;
}
-> This is the insertion case. When the user enters the choice as ‘1’, the program first checks the value of variable rearOfQueue, which in case exceeds the highest possible for the array depending on its size, (99 in our case, since the size of the array is 100, and C++ uses 0 as starting index), the program prints a message “QUEUE OVERFLOW” denoting that the queue is full, else it prompts for user input, the element that the user wants to insert into the linear queue. This element is then stored in a variable, elementOfQueue and is appended at the end of the queue, using the statement, queueArray [ rearOfQueue++ ] = elementOfQueue;. The element gets inserted at the rear of the queue, and the pointer starts pointing to one position next (incremented).

if ( rearOfQueue <= frontOfQueue )
std::cout << "\n\a!!QUEUE UNDERFLOW!!\n";
else
{
std::cout << std::endl << queueArray [ frontOfQueue ] << " removed!";
frontOfQueue++;
}
-> This is case 2 of our program, when the user wants to remove from the queue. In such a case the rearOfQueue is inspected. If it is pointing to frontOfQueue, i.e., the start of the queue, that means, the queue is empty, and hence a message is displayed, “QUEUE UNDERFLOW”, else the element at the front of the queue is displayed to the user as being removed(just for information), and frontOfQueue is incremented by one to point to the new front end of the queue. Actually removing from queue means orphaning the front element. This is the major drawback of queue data structure, that space not reusable.

std::cout << "\nQueue:\n";
if ( rearOfQueue == frontOfQueue )
std::cout << "\n\a!!QUEUE EMPTY!!\n";
else
for ( i = frontOfQueue; i < rearOfQueue; i++ )
std::cout << queueArray [ i ] << " ";
-> This is the case 3 of our program. This is nothing but a simple array traversal logic. At first we inspect the rearOfQueue. If it is pointing to frontOfQueue, then it means the queue is empty, and the user is notified of that. Else, the control enters into a loop, where the loop traverses the queue fron front to the rear, printing each element on the user’s display.

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


Friday, June 27, 2014

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

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 method, displayArray, which 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 in the method findPosition.

Code


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

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

class myArray
{
private:
  int arr[1000];

public:
  int arraySize;

  myArray()
  {
    std::cout << "\n\aEnter the size of the array(Upto 1000): ";
    std::cin >> arraySize;
    std::cout << "\n\aFill the array with " << arraySize;
    std::cout << " elements: ";
    int i = 0;
    for ( i = 0; i < arraySize; i++ )
      std::cin >> arr[i];
  }

  myArray(int argArraySize)
  {
    arraySize = argArraySize;
    std::cout << "\n\aFill the array with " << arraySize;
    std::cout << " elements: ";
    int i = 0;
    for ( i = 0; i < arraySize; i++ )
      std::cin >> arr[i];
  }

  void insertIntoArray(int insertAt, int insertMe)
  {
    if ( arraySize < 1000 )
    {
      arraySize++;
      if ( insertAt > arraySize )
      {
        std::cout << "\nThe array as yet has " << arraySize - 1;
        std::cout << " elements.\nThus the new element will be inserted at position " << arraySize;
        std::cout << " in the array.\n";
        insertAt = arraySize;
      }
      int i = 0;
      for ( i = arraySize + 1; i >= insertAt; i-- )
        arr[i] = arr[i - 1];
      arr[insertAt - 1] = insertMe;
    }
    else
      std::cout << "\n\n\aALREADY AT LIMITS\n\n\a";
  }

  void findPosition(int findMe)
  {
    int i = 0, flag = 0;
    for ( i = 0; i < arraySize; i++)
    {
      if ( arr[i] == findMe )
      {
        std::cout << "The number was found at: " << i + 1 << std::endl;
        flag = 1;
      }
    }
    if ( flag != 1 )
      std::cout<<"The number was not found!" << std::endl;
  }

  void deleteFromArray(int deleteMe)
  {
    int i = 0, j = 0, flag = 0;
    for ( i = 0; i < arraySize; i++)
    {
      if ( arr[i] == deleteMe )
      {
        arraySize--;
        for ( j = i; j < arraySize + 1; j++ )
          arr[j] = arr[j + 1];
        flag = 1;
        i = -1;
      }
    }
    if ( flag != 1 )
      std::cout<<"The number was not found!" << std::endl;
  }

  void displayArray()
  {
    int i = 0;
    std::cout << "\n\aCurrently the array is:";
    for (i = 0; i < arraySize; i++)
      std::cout << " " << arr[i];
  }
};

int main()
{
  std::cout << "\n\aWelcome to ArrayOps v2.0\n\aMade by Rogue Coder\n";
  myArray arrayObject;
  int choice = 0, num, pos;
  do
  {
    arrayObject.displayArray();
    std::cout << "\a\nChoices:\n1. Insert\n2. Delete\n3. Find\n4. Exit\nYour Choice: ";
    std::cin >> choice;
    switch (choice)
    {
    case 1:
      std::cout << "\nEnter the number to be inserted: ";
      std::cin >> num;
      std::cout << "\nEnter the position where to enter: ";
      std::cin >> pos;
      arrayObject.insertIntoArray(pos, num);
      break;
    case 2:
      std::cout << "\nEnter the number to be deleted: ";
      std::cin >> num;
      arrayObject.deleteFromArray(num);
      break;
    case 3:
      std::cout << "\nEnter the number to be found: ";
      std::cin >> num;
      arrayObject.findPosition(num);
      break;
    case 4:
      std::cout << "\n\n\aThank You for Using ArrayOps v2.0\n\aMade by Rogue Coder\n\aPress any key to exit.";
      std::cin.get();
      exit(0);
      break;
    default:
      std::cout << "\a\n\nWRONG CHOICE\a\n\n";
      break;
    }
  }
  while ( choice != 4 );
  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.

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.

class myArray -> The class that would wrap the array, int arr[1000], and the methods that are used to accessed it.

int arraySize -> This variable is used to store the size of the array. Though we have defined the array to be of length 1000, but 'arraySize' represents a bound on this length upto which the methods should access the array elements.

myArray()
{
std::cout << "\n\aEnter the size of the array(Upto 1000): ";
std::cin >> arraySize;
std::cout << "\n\aFill the array with " << arraySize;
std::cout << " elements: ";
int i = 0;
for ( i = 0; i < arraySize; i++ )
std::cin >> arr[i];
}
This is the constructor for the myArray class. When the object is created for myArray class, the constructor is called. Since before we perform any operations on the array, we should have an initial array in hand. Thus, the constructor prompts the user to enter an initial arraySize and fill the array with that many elements.

myArray(int argArraySize)
{
arraySize = argArraySize;
std::cout << "\n\aFill the array with " << arraySize;
std::cout << " elements: ";
int i = 0;
for ( i = 0; i < arraySize; i++ )
std::cin >> arr[i];
}

I have made this constructor but never called it. If you wish to make a different kind of object initialisation, you can use this constructor. To use this, you'll have to pass the arraySize to the object when it is created. You can either get the user input and use that user input to act as the argument for the constructor, else you can use a constant int for the purpose.

void insertIntoArray(int insertAt, int insertMe)
{
if ( arraySize < 1000 )
{
arraySize++;
if ( insertAt > arraySize )
{
std::cout << "\nThe array as yet has " << arraySize - 1;
std::cout << " elements.\nThus the new element will be inserted at position " << arraySize;
std::cout << " in the array.\n";
insertAt = arraySize;
}
int i = 0;
for ( i = arraySize + 1; i >= insertAt; i-- )
arr[i] = arr[i - 1];
arr[insertAt - 1] = insertMe;
}
else
std::cout << "\n\n\aALREADY AT LIMITS\n\n\a";
}
This method is used to insert a value into the array. It takes to arguments, first, the position where to enter, second, the value to be entered. The if condition in the beginning of this method is used to do a little bounds checking, to make sure if the array is at limits (1000 in this case), no more insertions are possible. In case the if condition fails, a message telling the user that the array has reached it's limits is issued. In case the if condition stands true, i.e., the array is still in it's limits, we proceed with the insertion. The first thing to do in such case is to increment the value of variable arraySize so that the upper bound on the limit of traversal can be set to correct value. Then we check if the position that user asked is greater than this new value of arraySize. This would mean, insertion outside the bound on the limit. Thus, a message is issued telling the suer the current array size, and thus inserting at the last possible position in the array. To do that, insertAt's value is changed to that of arraySize, in the case explained above only!. Next, a for loop is used to traverse the array upto the position that the user asked. The user asks for a position in the range, [1 , arraySize ], and the computer sees the array in the range [0 , arraySize - 1 ], thus the values of 'i' in the for loop. When the correct position is reached, the value is inserted into the array.

void findPosition(int findMe)
{
int i = 0, flag = 0;
for ( i = 0; i < arraySize; i++)
{
if ( arr[i] == findMe )
{
std::cout << "The number was found at: " << i + 1 << std::endl;
flag = 1;
}
}
if ( flag != 1 )
std::cout<<"The number was not found!" << std::endl;
}
This method is used to find the position of an element in the array, i.e., to implement sequential search on the array. The variable 'i' is the loop counter, and the variable, 'flag' is used to determine success/failure of the search. The for loop searches for the element to be found traversing the array sequentially, and matching the element with every element of the array as the loop moves forward. On each successful match, which is checked by the if condition inside the for loop, the user is signalled by a message denoting the position of the element in the array. To keep the output as per user's perception of array's range, i.e., [1 , arraySize], the 'i+1' is printed and not 'i'. The flag is set to 1 on a successful search. On exiting the loop, the flag value is checked again. If the value is not 1, it indicates that the search was unsuccessful, and hence the user is signalled a failure message.

void deleteFromArray(int deleteMe)
{
int i = 0, j = 0, flag = 0;
for ( i = 0; i < arraySize; i++)
{
if ( arr[i] == deleteMe )
{
arraySize--;
for ( j = i; j < arraySize + 1; j++ )
arr[j] = arr[j + 1];
flag = 1;
i = -1;
}
}
if ( flag != 1 )
std::cout<<"The number was not found!" << std::endl;
}
This method is used to delete an element from the array. If the element has multiple occurrences in the array, this method would delete all the occurrences of that element. We have 'i' and 'j' as the loop counters, and 'flag' to signal success/failure, which is a consequence of success/failure of the search. The outer for loop simply performs a sequential search on the array to find the element that the user requested to delete from the array. If the element is found, the arraySize is decremented since a deletion implies reduction in array's size. Next, the inner for loop, which starts from the position where the search was successful, i.e., the current value of 'i', and goes on to one more than upper bound on the array limit, i.e., arraySize+1 (because we decremented the arraySize already, but we might still need the last element of the array), moves the elements one position left, thereby deleting the element from the array. The flag is set to 1 since it was a success case. Then the value of 'i' is set to -1, since the out loop will increment the value of 'i', and in case we have 2 successive occurrences of the element, we won't be able to remove both without traversing the array again. Why does this happen? Consider we didn't have the statement i=-1. let the element is present at position 3 and 4. When the loop found the element at position 3, it shifted the array elements one position left. Now the loop would increment the counter. The element formerly on 4, is now on 3, and since the counter has moved to 4, we would skip that occurrence! That's why we need the statement, i=-1. It would force the loop to restart (restart from 0 since i=-1, and the loop will increment it to 0) on each successful search-and-delete operation. Since i=-1 is executed only if the search was successful, we don't end up being caught in an infinite loop. Once we exit the outer for loop, the value of flag is checked. If that value is not 1, it denotes failure, and thus the user is signalled the same.

void displayArray()
{
int i = 0;
std::cout << "\n\aCurrently the array is:";
for (i = 0; i < arraySize; i++)
std::cout << " " << arr[i];
}
This method is used to display the current state of the array. It has a for loop that prints the array upto the arraySize bound.

myArray arrayObject; -> The object is instantiated, and thus the constructor is called.

int choice = 0, num, pos; -> 'choice' is used to hold the value of user's choice in the switch menu, 'num' is used to get the user's input of the element to be inserted/deleted/searched. 'pos' is used to get the user input denoting, the position of the element in case of insertion operation.

case 1:
std::cout << "\nEnter the number to be inserted: ";
std::cin >> num;
std::cout << "\nEnter the position where to enter: ";
std::cin >> pos;
arrayObject.insertIntoArray(pos, num);
break;
Case 1, which gets the user input on what element to be inserted and where it is to be inserted. Then the method insertIntoArray is called with the user input as arguments.

case 2:
std::cout << "\nEnter the number to be deleted: ";
std::cin >> num;
arrayObject.deleteFromArray(num);
break;
Case 2, where the user asks to delete a number, 'num', from the array, and the method deleteFromArray is called with the user input as argument.

case 3:
std::cout << "\nEnter the number to be found: ";
std::cin >> num;
arrayObject.findPosition(num);
break;
Case 3, where the user asks to find the position(s) of occurrence(s) of the number, 'num' in the array. The method findPosition is called with the user input as argument.

case 4:
std::cout << "\n\n\aThank You for Using ArrayOps v2.0\n\aMade by Rogue Coder\n\aPress any key to exit.";
std::cin.get();
exit(0);
break;
Case 4, where the user exits the program.

default:
std::cout << "\a\n\nWRONG CHOICE\a\n\n";
break;
Default case, used to handle unspecified cases, that is, wrong choices in the menu.

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


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