Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Implementation of Queues ?

What comes to our mind with the word 'Queue' is quite often not a positive one. Long lines of people, waste of time & often leads to some inconveniences. 




But, one thing is universal, about Queues, that is ? of course the "First Comer leaves first, from the beginning". So, everybody joined in the queue eventually will be moved towards the front.

I'm not intending to talk about ordinary queue here. I'm actually talking about Queue the data structure we've to study during lessons of initial programming concepts.

Queue is an abstract data types because of the separate implementation, away from the actual operations with the data structure itself.

What're these Implementations ? Well Similar  to Stacks, Queues also contain three operations which could be implemented in abstract manner.

  1. Insert
  2. Remove
  3. Peek Front
 Let's look into the C++ implementation of each on of these operations. Look at the class file.

// Queue.h
class Queue
{
    private:

        int maxSize;
        double *queueArray;
        int front;
        int rear;
        int numofitems;
        bool stats;

    public:
        ~Queue(); // destructor
        Queue(int size); // parametrized constructor 
        void insert(double item); // insert
        void remove(); // remove
        bool isFull(); // check is full
        bool isEmpty(); // check is empty
        double peekFront(); // peek front item

}; 
Implementation of the parametrized constructor should be as follows.

Queue::Queue(int size)
{
    stats;
    maxSize = size;
    queueArray = new double[maxSize];
    front = 0; // front is 0
    rear = -1; // initialize rear to -1
    numofitems = 0; // number of items 0
}

1. First, Insert. Well insert is where we can add items to the Queue. We've to do this from behind of the existing Queue.

void Queue::insert(double item)
{
    if(!isFull()) // Queue shouldn't be full 
    {
        queueArray[++rear] = item; // increment rear & assign value to the Queue
        numofitems++; // increment number of items by one
        front++; // increment front 
    }
    else
    {
        cout<<"Your Queue is Full!"<<endl;
    }   
}

2. Second, Remove. As mentioned before this operation should be happened at the beginning of the Queue.



void Queue::remove()
{
    if(!isEmpty())// checks whether the queue is empty
    {
        queueArray[rear--]; // removes item
        cout<<"An Item is removed!"<<endl;
    }
    else
    {
        cout<<"Queue is Empty!"<<endl;
    }
}  

3. Third, We can implement a method to check the front item of the Queue. So whenever there's an operation, this returns the front item.

double Queue::peekFront()
{
    return queueArray[rear];
}


Look at the following picture. It shows, the two types of Queues that exist. The above implementations can be applied to linear queues but not circular queues.




Image clearly, shows that, not like in Linear Queue the incrementation of the last item to the next item is problematic as the 0th Item removes first.

We've to set rear = 0 when, rear == maxSize - 1. Look at the method implementation below.


void Queue::inc(double &index)
{
    if(index==maxSize-1) // if index is the last element
    {
        // set index to zero
        index = 0;
    }
    else
    {
        index = index+1;
    }
}


Now, the enqueue() - insert item to queue method implements as show below.

void Queue::enQueue(double item)
{
    if(!isFull())
    {
        inc(rear);
        qArray[++rear] = item;
        cout<<"Item added!"<<end;
        nItems++;
        front++;
    }
    else
    {
        cout<<"Your Queue is Full"<<endl;
    }
}

Thank You!

Stacks with C++ ?

Data is important. Storing & Organizing Data has been the key goal of most complex Computer Programs. Not just Store & organize, retrieve Data in the most efficient & reliable way could have unprecedented importance. To achieve this goal, we can use Data Structures.
 
Data Structures are particular way of storing data & manage the data the way we want it. Among the Composite, Abstract & Primitive data structures, Stack is of course abstract.

Stack? Stack is a data structure with Sequential Access as stored data could be accessed in a sequence Like in Cassette Tape. Stack is built on (LIFO) Last In First Out principle.

Three operations are involved with Stack. Push, Pop & Peek. These, operations proves the sequential accessibility of Stack.


The C++ code could be developed for these operations like follows. First, create Stack.h, Stack.cpp & main.cpp files in C++ project. Header file (*.h) includes the attribute & method declarations.

//Stack.h
class Stack
{
      private:
              int maxSize;
              double *Store;
              int top; // index
      public:
             ~Stack(); // destructor frees up the memory
             Stack(int s);
             double pop(); // pop operation
             void push(double num); // push operation & push number
             double peek(); // peek the top value
      };

*.cpp file includes the method definitions of the Stack class.

//Stack.cpp
#include "Stack.h"
#include <iostream>
using namespace std;

Stack::Stack(int s)
{
     maxSize = s; // determines the size of array
     top = -1; // initial index number
     Store = new double[maxSize];
}
               
double Stack:: peek()
{     
      if(top == -1)
      {
             cout<<"Stack is Empty"<<endl;
             return -999;
      }
      else if (top == maxSize)
      {
              cout<<"Stack is Full"<<endl;
              return Store[top];
      }
      else
      {
              return Store[top];
      }
}

double Stack::pop()
{
       if(top ==-1)
       {
             cout<<"Stack is Empty"<<endl;
             return -999;                   
       }
       else
       {
             return Store[top--];
       } 
                   
}
            
void Stack::push(double j)
{
       if(top == maxSize-1)
       {
              cout<<"Stack is Full"<<endl;
       }
       else
       {
              Store[++top] = j;
       }
}

'main.cpp' should be the main execution file which ultimately helps to run the program.

//main.cpp
#include "Stack.h"
#include<iostream>
using namespace std;

int main()
{       
     Stack *a = new Stack(5);
     a->push(10);
     cout<<a->peek()<<endl;
     a->push(20);
     a->push(30);
     a->push(40);
     a->push(50);
     a->push(60); // these values won't be inserted
     a->push(70); // as Stack size is 5 & it's full
     cout<<a->peek()<<endl; //peeks the final value should be 50
     system("PAUSE");
     return 0;
}


Even though, the C++ Programming Code sometimes may be problematic for those who're not familiar with C++, the Concept of Stacks is Clear.

1. Push - Enter an Item. If stack isn't Full.
2. Pop -  Remove an Item, if Stack isn't Empty.
3. Peek - Check the Item at the Top.

The idea is similar to a Stack of Books. "If you need to Remove the firstly entered material you've to remove all other material to do so."




Thank You!

Structures & Enumeration with C++ ?

I'd had the idea of having a note about Structures & Enumerations for a long time. Today, It's unveiling like this.
  • Structures
To begin with, I'd like to remind a little bit about the variables in C++. Variables in C++ can be initialized and used just like any other programming language. Look at the simple example below.

#include <stdio.h>

int main()
{
        int a = 1232;
        int b = 1234;
        printf("Value of a : %i \n",a);
        printf("Value of b : %i \n",b);
        return 0;
}
  


But, with the case sensitive nature of C++, any programmer should be having a large number of variables & large amount of lines of code in excessive programs. To avoid this, we used arrays in C++ like follows.

#include <stdio.h>
#define ARRAY_SIZE(array) (sizeof(arr)/sizeof(*arr))
int main()
{

        int arr[]={1232,1234,1236,1238};

        for(int a=0;a<=ARRAY_SIZE(arr);a++)
        {
                printf("Array Value : %i \n",arr[a]);
        }

        printf("Array Size : %i",ARRAY_SIZE(arr));

        return 0;
}


Since, arrays just allow us to store similar type of data. We move to Structures. Look at the example below.

#include <stdio.h>
struct var
{
        int a;
        double b;
        char c;
};

int main()
{
        var v;

        v.a=1232;
        v.b=123.2123;
        v.c='A';

        printf("Value of Variable is : %i \n",v.a);
        printf("Value of Variable is : %f \n",v.b);
        printf("Value of Variable is : %c \n",v.c);

        return 0;
}


In this example, it's obvious that Structures do leave the opportunity for us to store different types of data at the same time under the structure name which is useful.

  • Enumeration
Enumeration allows us to make our own variables & most importantly allows to permit a set of values for that variable. Look at the following example.

#include <iostream>
using namespace std;

enum days_of_week{Sun,Mon,Tue,Wed,Thu,Fri,Sat};

int main()
{
        days_of_week day1, day2;

        day1 = Thu;
        day2 = Mon;

        if(day1<day2)
        {
                cout<<"Day1 Comes before Day2"<<endl;
        }

        return 0;
}


As mentioned before, the importance of enumeration is that, it allows to create new data types that can take just restricted range of values &  those variables are stored as integers like the 'Concept of Array Index'.

#include<iostream>
using namespace std;

enum cards{spade=0,heart=3,club=1,diamond=2};

int main()
{
        cards c1,c2;

        c1 = spade;
        c2 = diamond;


        cout<<c1<<endl;
        cout<<c2<<endl;

        return 0;
}


In the above example all the default integer values of the variables are replaced with our own set of values. It makes Enumeration much more flexible to use. That's it about Structures & Enumeration ! Enjoy C++ !

Get to know io Manipulation of C++ ?

This post is for those who admire programming 'C++'.

Does anybody remember how we added some style & kind of a formatting to the out put of basic C++ programs? We called it, 'Manipulating' in books.

Today, mistakenly I hit back on the previous lessons. Which is kind of strange to know how far we've come through ?

'iomanip' is a Standard C++ Library Header File which you may need to include in your program in order to use them.'iomanip' consists some functions that I thought I should have a special note for.

following program includes 3 of the functions that this post will be explaining, namely:
  1. setw(n)
  2. setiosflags()
  3. resetiosflags()

#include<iostream>
#include<iomanip>
using namespace std;
void set(int num);void setFirstRow();

int main()
{
        setFirstRow();
        set(10);
        return 0;
}

void set(int num)
{
        while(num!=0)
        {
                cout<<setw(10)<<num;
                cout<<setw(10)<<oct<<setiosflags(ios_base::oct)<<num;
                cout<<resetiosflags(ios_base::oct)<<endl;
                num--;
        }
}

void setFirstRow()
{
        cout<<setw(10)<<"Value dec";
        cout<<setw(10)<<"Value oct"<<endl;
}                                                                                                                                            


Take a look at the : 

setw(n)

It causes the values to be printed in a stream which is n characters wide.

setiosflags(ios_base::oct) 

causes the number format to be changed into Octal & 

resetiosflags(ios_base::oct) 


reverses that.

   4.  setprecision(n) - causes the output to format decimal numbers to limit the decimal places. 'n'  signifies the total amount of character of the decimal number without '.' value.


#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
        double a= 32.33321;

        cout<<setprecision(5)<<a<<endl;

        return 0;
}                 

The output is 32.333 as the precision number is set to 5.


That's it for this post, Enjoy C++!

Type Casting with C++ Language ?

In this post, I wanted to note down one of the most important fundamentals of any programming language, which is ' Type Casting '.

Type Casting? Why is this important? 

Whenever we program, we'll have to store data. In order to do that there're :

Variables - "Physical location of Memory that allows to store data as sequence of bits & tells the compiler how to translate them into meaningful values"

But, sometimes you may end up having multiple types of operands to be operated with operators.

There are 2 basic Type Conversions.
  • Implicit Type Conversion
  • Explicit Type Conversion

Look at the following C++ Example. This is what we call Implicit (Automatic/Widening) Type Conversion where, you store int inside double. This is similar to : Ant inside Elephant.



#include<iostream>
using namespace std;
int main()
{
        double count = 7;
        cout<<" output "<<count<<endl;
        return 0;
}

But, can we perform the other way around. Elephant inside Ant.


#include<iostream>
using namespace std;
int main()
{
        int count = 7.98;
        cout<<" output "<<count<<endl;
        return 0;
}

According to C++ variable types,

Storing value of  7.98 a double value inside int may look like stupid. But, Automatic Type Conversion of C++ allows us to do this & the program compiles & runs without any problem at all. But, we lose precision & unsafe results are possible.

To avoid this happening We can use C++ Explicit Type Casting (Narrowing).

        double d=22.321;
        int i = (int)d; 

OR
        double d=22.321;
        int i = int(d);

Otherwise, we can try using static_cast of C++.

        double d = 23.321;
        int i = static_cast<int>(d);