About Me

My photo
Posting here few basic programs. I prefer using C++. Trying to keep it error free. Feel free to point any of them. Thanks for visiting. You can copy paste code directly from here.

Friday 23 September 2011

/*Linked List


  Program to Create Linked List (node implementation) and do common operations in it.
Creation, Traversal, Deletion of nodes

 ****************************************************************************************************************************/



                                                            //preprocessor directives

#include<stdio.h>
#include<process.h>                        
#include<conio.h>
#include<iostream.h>

                                                                                   
                                                             //prototype declaration
                                                             //return type is void i.e. they do return any values
    void create();
    void travel();
    void nodeDelete();
       
                                                                                                 //variable declaration
    int nodeNumber, delInfo=0;

    struct node                                                                            //Structure of node defined
    {
        int data;
        node *ptr;
    } *start, *temp, *trvl;



int main( )
{
   
   
    int choice;
    do{
       clrscr();
                                                                                                //Menu
       cout<<"\n\tWelcome to Node Menu...";
       cout<<"\nPress 1 for node creation process..";
       cout<<"\nPress 2 for Traversal...";
       cout<<"\nPress 3 to delete a node...";
       cout<<"\nPress 4 to view value of last deleted node...";
       cout<<"\nPress 5 to exit\n\t";
       cout<<"\nEnter your choice...";
       cin>>choice;

       switch(choice)
       {
        case 1: create();
              break;
        case 2: travel();
              break;
        case 3: nodeDelete();
              break;
        case 4: cout<<"\nLast data part: "<<delInfo;
              break;  
        case 5:
              cout<<"\nPreparing to exit...";
              cout<<"\nPress Enter...";
              getch();
              exit(0);                                 //exit() is defined in process.h, 0 is usually way for exiting
              break;
        default: cout<<"\nWrong choice!!  Remember (1-5)";
              break;


    }
    }while(choice != 4);


    getch();

    return 0;
}



                                                                        //First two are required for list creation
 void create()
 {
    start = new node;                                       //First node


/* actually right after creation of every node, you should/can check whether it is actually created or not. i.e. did the system had sufficient memory to allocate resources

It can be done using a null check;  NULL is a state of a pointer if it doesn't points to some location.
NULL is defined in a lot of header files including our own "stdio.h" which as can be seen is included earlier. Next I'll show how to use NULL.


if (start == NULL)
{
     cout<<"\nInsufficient memory";
}

and maybe you can add exit(0) in the condition to quit the program. Because if the system fails to allocate memory then it's of no use*/

    cout<<"\nNew node created...!";
    cout<<"\nEnter data: ";
    cin>>start->data;

    temp = new node;                                      //Second node
    cout<<"\nSecond node....";
    cout<<"\nEnter data: ";
    cin>>temp->data;

    start->ptr = temp;


    cout<<"\nHow many more nodes you want...?";
    cin>>nodeNumber;

    int i=0;
    for(i=0; i<(nodeNumber); ++i)     //Further nodes created
    {
        trvl = new node;
        cout<<"\nEnter data in node number "<<i+3<<": ";
        cin>>trvl->data;
        temp->ptr = trvl;
        temp = temp->ptr;
    }


    cout<<"\nNodes created...";
   
   
  }




void travel()
{
    cout<<"\nTraversing";                                               //Traversal
    cout<<"\n    Node number \t   Data";
    trvl = start;

    for(int i=0; i<(nodeNumber+2); ++i)
    {
        cout<<endl<<"\t"<<i+1<<"\t\t"<<trvl->data;
        trvl = trvl->ptr;
    }
}






void nodeDelete()
{
     int del;
    // clrscr();
     travel();
     cout<<"\nWhich node you want to delete...?";
     cin>>del;
     if( del > nodeNumber+2)
     cout<<"\nSuch node doesn't exists..., try again";

     else
     {
       temp = trvl = start;



       for(int i=0; i<del ; ++i)
           trvl = trvl-> ptr;

           for( int j=0; j< (del-1) ; ++j)
           temp = temp-> ptr;

       temp->ptr = trvl->ptr;
       delInfo= trvl->data;
       nodeNumber--;
    }

    cout<<"\nNode deleted...";
    cout<<"\nYou can view data of last deleted node";
}
/*ASSIGNMENT - 2 DISCRETE STRUCTURES

Sorting


  program for sorting in C using M A and S functions

  M is used to find maximum amongst a list of numbers
  A is used to find greater of 2 numbers and put the bigger number to the Right Hand Side in the list
  S is the sorting function which is used recursively
********************************************************************************************************************/

                                           
                              

                                                                             /* pre-processor directives */ 
#include<stdio.h>
#include<conio.h>

#define size 50                                                 /* helps in changing array size */




int array[size], numberOfValues = 0, temp = 0, n=0, j=0;
                                                               /* variable declaration , these are defined Globally*/

void a()
{
             if(array[j] > array[j+1])               /* here swapping the smaller with bigger number and moving it right*/
             {
                          temp = array[j];
                          array[j] = array [j+1];
                          array[j+1] = temp;
             }
}


void m()                                                      /* m() calls a() */
{
     for(j = 0; j< (n-1); ++j)
     a();
}



void s()                                                             /* and here s calls m() */
{
    if(n != 0)
    {
       
        m();
        n--;
        s();                                                          /* see here s() is called recursively i.e. s() calls s()*/
    }
}




int main()
{
   
    clrscr();
    printf("\n\tNumber of elements...: ");
    scanf("%d", &numberOfValues);
   
    int i;                                                                        
                                                                                                       /* inputs */
   
    for(i = 0; i < numberOfValues; ++i)
    {
            printf("Element no. %3d : ", i+1);
            scanf("%d", &array[i]);
    }
   
    n = numberOfValues;
    s();
   
   
    printf{"\nOUTPUT");
    for(i = 0; i < numberOfValues; ++i)                                              /*output*/
    {
            printf("%d  ", array[i]);
    }
   
   
    getch();
   
    return 0;
}








Sample Output:




   

Thursday 22 September 2011

/* Struct vs Class

Program to show there aren't many differences between a structure and a class

COMMENTS are shown in bold and italics*/


#include<iostream.h>
#include<conio.h>



class Demo2                                      //class
{
    public:                                              //public label
        void print()
        {
            cout<<"\n\n For the class\n\n Enter a, b and c : ";
            cin>>a>>b>>c;
            cout<<"\n a= "<<a<<" b = "<<b<<" c= "<<c;
        }
       

    private:
        int a;
        int b;

    protected:
        int c;
};
Demo2 a2;                              // object created for the class



struct Demo1                        
                                       

{
    public:                                             //see this has labels as a class
        void print()                                  // has functions
        {
            cout<<"\n\nFor the structure\nEnter x, y and p : ";
            cin>>x>>y>>p;
            cout<<"\nx= "<<x<<" y = "<<y<<" p= "<<p;
        }
        Demo1();

                             /* even has constructors & destructors although i have shown a constructor only . A constructor is a special function having same name of the class */

    private:
        int x;
        int y;

    protected:
        int p;
};
Demo1 a1;                   

//object of structure defined in the same way as for a class                




Demo1::Demo1()             /*constructor declaration outside structure as can be done for a class*/
{
    x = y = p = 0;
    cout<<"\nThis shows constructor working for struct\n"<<"\n x= "<< x <<" y = "<< y <<" p= "<< p;
}



int main()
{
    a1.print();                                //calling structure object
    a2.print();                                //calling class object         
    getch();
    return 0;
}

Sample Output:





// Stack through array


Program to implement Pop and Push operations in Stack (stack is implemented using Array)

#include<iostream.h>
#include<conio.h>
#include<process.h>                          // to use exit() function

# define size 20                                 //for array size

int stack[size], top=-1, data;

void push()
{
     if(top < size-1)
     {
        cout<<"\n Enter data for push operation... : ";
        cin>>data;
        top+=1;                                   //same as top = top + 1
        stack[top] = data;
     }
     else
     cout<<"\n\tStack full....\n\tTry emptying values from stack...";
}

void pop()
{
    if(top = = -1)
    cout<<"\n\t Stack underflow...\n\t Try pushing elements...";
    else
    {
    data = stack[top];
    cout<<"\n\t Popped data : "<<data;
    top-=1;
    }
}

void display()
{
     for(int i=0; i<= top; ++i)
     cout<<stack[i]<<" --> ";
    
     cout<<"\n\n   Press enter to continue";
     getch();
}

int main()
{

    int choice;

    do
    {
    clrscr();
    cout<<"\n\n\n\t Welcome to Stack menu";
    cout<<"\n  Press 1 to push elements in stack";
    cout<<"\n  Press 2 to pop elements from stack";
    cout<<"\n  Press 3 to exit";
    cout<<"\n    Stack current status...: "<<top+1<<" elements present\n\n";
    cout<<"\n\n  Enter your choice (1-3)  : ";
    cin>>choice;

    switch(choice)
    {
                       case 1:
                            push();
                            display();
                          break;
                         
                       case 2:
                            pop();
                            display();
                          break;
                          
                       case 3:
                             cout<<"\n   Preparing to exit...";
                             cout<<"\n   Press enter...";
                             getch();
                             exit(0);
                          break; 
                         
                       default:
                             cout<<"\n\t Wrong selection!!! Remember (1-3)";
                          break;   
        }
     }while(choice != 3);
     getch();
    
     return 0;

}





Sample Output of the program: