Thursday, 11 June 2015

Program that are completely portable across different operating systems

Code for Program that are completely portable across different operating systems in C++ Programming

 # include <iostream.h>
 # include <fstream.h>
 # include <string.h>
 # include <stdlib.h>
 # include <conio.h>

 int main( )
    {
       clrscr( );

       fstream File("CP-25.txt",ios::in|ios::nocreate);

       if(!File)
      {
         cout<<"\n Unable to open the input file."<<endl;
         cout<<"\n Press any key to exit.";

         getch( );
         exit(EXIT_FAILURE);
      }

       char Data[100]={NULL};

       do
      {
         strset(Data,NULL);

         File.getline(Data,100);

         if(strcmp(Data,NULL)==0)
        break;

         long number=atol(Data);

         long byte_1=0;
         long byte_2=0;
         long byte_3=0;
         long byte_4=0;

         byte_1=(number&0x000000FF);

         number>>=8;

         byte_2=(number&0x000000FF);

         number>>=8;

         byte_3=(number&0x000000FF);

         number>>=8;

         byte_4=(number&0x000000FF);

         number=byte_1;

         number<<=8;

         number=(number|byte_2);

         number<<=8;

         number=(number|byte_3);

         number<<=8;

         number=(number|byte_4);

         cout<<Data<<" converts to "<<number<<endl;
      }
       while(1);

       File.close( );

       getch( );
       return 0;
    }

Program to illustrate printing data on the printer


Code for Program to illustrate printing data on the printer in C++ Programming

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

 main(int argc,char *argv[])
    {
       clrscr();

       if(argc!=2)
      {
         cout<<"\n Format : File - Print File Name "<<endl;
         exit(0);
      }

       char ch='\0';

       ifstream input_file;
       ofstream output_file;

       input_file.open(argv[1]);
       output_file.open("PRN");   // or LPT1while(input_file.get(ch)!=0);

       output_file.put(ch);

       getch();
       return 0;
    }

Program that uses this DFA and validates whether an entered string is valid float or not

Code for Program that uses this DFA and validates whether an entered string is valid float or not in C++ Programming

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

int main()
{
    int flag = 0;
    char ch = NULL;
    char state = '0';
    char token[20] = {NULL};
    char stt[5][3] = {NULL, '4', '5',
            '0', '1', '2',
            '1', '1', '2',
            '2', '3', NULL,
            '3', '3', NULL};

    cout<<"Input float data : ";
    cin>>token;

    for(int i=0; token[i] != NULL; i++)
    {
        if(isdigit(token[i]))
        {
            ch = '4';
        }
        elseif (token[i] == '.')
        {
            ch = '5';
        }
        else
        {
            flag=1;
            printf("Invalide value");
            break;
        }

        for(int j=1; j<3 && ch != stt[0][j]; j++);
        for(int k=1; k<5 && state != stt[k][0]; k++);
        state =stt[k][j];
        if(state==NULL)
        {
            flag=1;
            printf("Invalide value");
            break;
        }
    }
    if(flag==0)
    {
        printf("Valide value");
    }
    getch();
    return 0;
}

Comment line in c

Code for Comment line in c in C++ Programming

#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <process.h>
#include <string.h>

int main()
{
    char stt[8][4] = {NULL, '7','8','9',
                        '0', '1', NULL, NULL,
                        '1', '2', '4', NULL,
                        '2', '3', '3', '3',
                        '3', NULL, NULL, '3',
                        '4', '4', '5', '4',
                        '5', '6', '5', '4',
                        '6', NULL, NULL, NULL};
    char ch, state = '0';
    char variable[40];
    int flag=0;

    cout<<"Input c Comment line : ";
    cin>>variable;

    for(int i=0; i<40 && variable[i] != NULL; i++)
    {
        if(variable[i] == '/')
        {
            ch = '7';
            flag=flag+1;
        }
        elseif(variable[i] == '*')
        {
            ch ='8';            
        }
        else
        {
            ch ='9';
        }

        for(int j=1; stt[0][j] != ch; j++);
        for(int k=1; stt[k][0] != state; k++);

        state = stt[k][j];
        if (state == NULL)
        {
            printf("Invalide comment line");
            getchar();
            exit(0);
        }
    }
    if (flag == 1)
    {    
        printf("Invalide comment line");
        getchar();
        exit(0);
    }
    else
    {
        printf("Valide Comment line");
    }
    getchar();
    return 0;
}

Identifer recognisition Integer Unsigned real number with optional integer part

Code for Identifer recognisition Integer Unsigned real number with optional integer part in C++ Programming

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<ctype.h>
int main()
{
    clrscr();
    int flag=0;
    char state = '0';
    char ch = NULL;
    char token[10]={NULL};
    char stt[6][4] = {    NULL,'7','8','9',
                '0','1','2','3',
                '1','1','1',NULL,
                '2',NULL,'2','3',
                '3',NULL,'4',NULL,
                '4',NULL,'4',NULL    };

    cout << "Enter Identifier, Integer or Real Number : ";
    cin >> token;
    for(int i=0; i < strlen(token); i++)
    {
        if (isalpha(token[i]))
            ch='7';
        elseif (isdigit(token[i]))
            ch = '8';
        elseif (token[i] == '.')
            ch = '9';
        for(int j=1; j<=3 && ch != stt[0][j]; j++);
        for(int k=1;k<=5 && state != stt[k][0];k++);
        state = stt[k][j];
            if(state == NULL)
            {
                cout << endl << "Invalid ....";
                flag=1;
                break;
            }
    }
    if (flag==0)
        cout<<"valide string";
    getch();
    return 0;
}

Tuesday, 9 June 2015

Program to illustrate the functions returning pointers


Code for Program to illustrate the functions returning pointers in C++ Programming



 



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

 int *function();

 main()
    {
       clrscr();

       int *p;

       p=function();

       cout<<"\n Value return by the function returning pointer :"<<endl;
       cout<<"\t value of *p = "<<*p<<endl;

       getch();
       return 0;
    }


 /*************************************************************************///---------------------------  function( )  -----------------------------///*************************************************************************/int *function()
    {
       int i=10;
       int *j;

       j=&i;

       return j;
    }



 

Program to convert an Infix Expression into a Postfix Expression using Linked List as a Stack


Code for Program to convert an Infix Expression into a Postfix Expression using Linked List as a Stack in C++ Programming



 



 



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

 struct node
 {
    char data;

    node *next;
 };

 node *top=NULL;
 node *bottom=NULL;
 node *entry;
 node *last_entry;
 node *second_last_entry;

 void push(constchar);
 constchar pop( );

 void infix_to_postfix(constchar *);


 int main( )
    {
       clrscr( );

       char Infix_expression[100]={NULL};

       cout<<"\n\n Enter the Infix Expression : ";
       cin>>Infix_expression;

       infix_to_postfix(Infix_expression);

       getch( );
       return 0;
    }

 /*************************************************************************//*************************************************************************///------------------------  Function Definitions  -----------------------///*************************************************************************//*************************************************************************//*************************************************************************///-----------------------------  push(const char)  ----------------------///*************************************************************************/void push(constchar Symbol)
    {
       entry=new node;

       if(bottom==NULL)
      {
         entry->data=Symbol;
         entry->next=NULL;
         bottom=entry;
         top=entry;
      }

       else
      {
         entry->data=Symbol;
         entry->next=NULL;
         top->next=entry;
         top=entry;
      }
    }

 /*************************************************************************///--------------------------------  pop( )  -----------------------------///*************************************************************************/constchar pop( )
    {
       char Symbol=NULL;

       if(bottom==NULL)
      cout<<"\n\n\n\t ***  Error : Stack is empty. \n"<<endl;

       else
      {
         for(last_entry=bottom;last_entry->next!=NULL;
                         last_entry=last_entry->next)
        second_last_entry=last_entry;

         if(top==bottom)
        bottom=NULL;

         Symbol=top->data;

         delete top;

         top=second_last_entry;
         top->next=NULL;
      }

       return Symbol;
    }

 /*************************************************************************///---------------------  infix_to_postfix(const char *)  ----------------///*************************************************************************/void infix_to_postfix(constchar *Infix)
    {
       char Infix_expression[100]={NULL};
       char Postfix_expression[100]={NULL};

       strcpy(Infix_expression,"(");
       strcat(Infix_expression,Infix);
       strcat(Infix_expression,")");

       char Symbol[5]={NULL};
       char Temp[5]={NULL};

       for(int count=0;count<strlen(Infix_expression);count++)
      {
         Symbol[0]=Infix_expression[count];

         if(Symbol[0]=='(')
        push(Symbol[0]);

         elseif(Symbol[0]==')')
        {
           Symbol[0]=pop( );

           while(Symbol[0]!='(')
              {
             strcat(Postfix_expression,Symbol);

             Symbol[0]=pop( );
              }
        }

         elseif(Symbol[0]=='^' || Symbol[0]=='*' || Symbol[0]=='/'
                    || Symbol[0]=='+' || Symbol[0]=='-')
        {
           if(Symbol[0]=='*' || Symbol[0]=='/')
              {
             Temp[0]=pop( );

             while(Temp[0]=='^' || Temp[0]=='*' || Temp[0]=='/')
                {
                   strcat(Postfix_expression,Temp);

                   Temp[0]=pop( );
                }

             push(Temp[0]);
              }

           elseif(Symbol[0]=='+' || Symbol[0]=='-')
              {
             Temp[0]=pop( );

             while(Temp[0]!='(')
                {
                   strcat(Postfix_expression,Temp);

                   Temp[0]=pop( );
                }

             push(Temp[0]);
              }

           push(Symbol[0]);
        }

         else
        strcat(Postfix_expression,Symbol);
      }

       cout<<"\n\n Postfix Expression : "<<Postfix_expression;
    }

Program to illustrate unary operator (increment operator) overloading without return type



Code for Program to illustrate unary operator (increment operator) overloading without return type in C++ Programming



 



 



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

 /*************************************************************************///------------------------------  counter  ------------------------------///*************************************************************************/class counter
    {
       private:
        int count;

       public:
        counter()  { count=0; }
        counter(intvalue)  { count=value; }
        voidoperator++()  { ++count; }
        voidoperator++(int)  { count++; }
        void showdata()  { cout<<count<<endl; }
     };

 main( )
    {
       clrscr();

       counter obj1(2);
       counter obj2(6);
       counter obj3(9);

       cout<<"\n ********* Before Increment *********"<<endl;

       cout<<"\n Data of obj1 is = ";
       obj1.showdata();

       cout<<"\n Data of obj2 is = ";
       obj2.showdata();

       cout<<"\n Data of obj3 is = ";
       obj3.showdata();

       ++obj1;
       obj2++;
       obj3++;

       cout<<"\n ********* After Increment *********"<<endl;

       cout<<"\n Data of obj1 is = ";
       obj1.showdata();

       cout<<"\n Data of obj2 is = ";
       obj2.showdata();

       cout<<"\n Data of obj3 is = ";
       obj3.showdata();

       getch();
       return 0;
    }

Program that prints first 20 integers in reverse order (using while loop )



Code for Program that prints first 20 integers in reverse order (using while loop ) in C++ Programming



 



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

 /*************************************************************************//*************************************************************************///-----------------------------  Main( )  -------------------------------///*************************************************************************//*************************************************************************/

 main()
    {
       clrscr();

       cout<<"\n The first twenty integers in reverse order are as follows :"<<endl;

       int count=20;

       while(count>=1)
      {
         cout<<"  "<<count;
         count--;
      }

       getch();
       return 0;
    }

Program to illustrate the operations that can be performed on pointers


Code for Program to illustrate the operations that can be performed on pointers in C++ Programming



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


 main()
    {
       clrscr();

       int i=5;
       int *j;

       j=&i;

       float f=10.5;
       float *g;

       g=&f;

       char c='q';
       char *d;

       d=&c;

       cout<<"\n --------- values of variables ---------\n"<<endl;
       cout<<"value of i = "<<i<<endl;
       cout<<"value of f = "<<f<<endl;
       cout<<"value of c = "<<c<<endl;

       getch();

       cout<<"\n --------- addresses of variables --------\n"<<endl;
       cout<<"address of i = "<<&i<<endl;
       cout<<"address of f = "<<&f<<endl;
       cout<<"address of c = "<<&c<<endl;

       getch();

       cout<<"\n ---------- values of pointers ----------\n"<<endl;
       cout<<"value of j = "<<j<<endl;
       cout<<"value of g = "<<g<<endl;
       cout<<"value of d = "<<d<<endl;

       getch();

       j++;
       g++;
       d++;

       cout<<"\n ---------- values of pointers after modification --------\n"<<endl;

       cout<<" j++"<<endl;
       cout<<"value of j = "<<j<<endl;
       cout<<" g++"<<endl;
       cout<<"values of g = "<<g<<endl;
       cout<<" d++"<<endl;
       cout<<"values of d = "<<d<<endl;

       cout<<"\n --------- values contained by pointers --------\n"<<endl;
       cout<<"value of *j = "<<*j<<endl;
       cout<<"value of *g = "<<*g<<endl;
       cout<<"value of *d = "<<*d<<endl;

       getch();
       return 0;
    }



 



 

Program that displays the size, address of the variables of type int , float and char.



Code for Program that displays the size, address of the variables of type int , float and char. in C++ Programming



 



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

 main( )
    {
       clrscr( );

       int i=5;

       float f=3.3;

       char c='M';

       cout<<"\n *********  Values stored in the  Variables  ********"<<endl;
       cout<<"\t Value of i = "<<i<<endl;
       cout<<"\t Value of f = "<<f<<endl;
       cout<<"\t Value of c = "<<c<<endl;

       cout<<"\n *********  Sizes of the Variables  ********"<<endl;
       cout<<"\t Size of i = "<<sizeof(i)<<endl;
       cout<<"\t Size of f = "<<sizeof(f)<<endl;
       cout<<"\t Size of c = "<<sizeof(c)<<endl;

       cout<<"\n *********  Addresses of the Variables  ********"<<endl;
       cout<<"\t Address of i = "<<&i<<endl;
       cout<<"\t Address of f = "<<&f<<endl;
       cout<<"\t Address of c = "<<&c<<endl;

       cout<<"\n *********  Sizes of the Data types  ********"<<endl;
       cout<<"\t Size of int = "<<sizeof(int)<<endl;
       cout<<"\t Size of float = "<<sizeof(float)<<endl;
       cout<<"\t Size of char = "<<sizeof(char)<<endl;

       getch( );
       return 0;
    }

Program to illustrate the 2D array of int using pointers


Code for Program to illustrate the 2D array of int using pointers in C++ Programming



 



 



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


 main( )
    {
       clrscr();

       constint r=3;
       constint c=3;

       int array[r][c],i,j;

       cout<<"\n Enter the contents of the 2D array row by row are :\n"<<endl;
       for(i=0;i<r;i++)
      {
         for(j=0;j<c;j++)
        cin>>*(*(array+i)+j);

         cout<<endl;
      }

       clrscr();

       cout<<"\n The content of the 2D array row by row are :\n"<<endl;
       for(i=0;i<r;i++)
      {
         for(j=0;j<c;j++)
        cout<<"  array element ["<<i<<"]["<<j<<"]  =  "<<
                              *(*(array+i)+j)<<endl;

         cout<<endl;
      }

       getch();
       return 0;

Tic-Tac-Toe game



Code for Tic-Tac-Toe game in C++ Programming



 



 



 



 
#include<iostream.h>
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<dos.h>

// MACROS USED#define full 1
#define empty 0
#define radius 15
#define OutOfRange 1
#define OccupiedCell 2

// CONSTANTS ... x,y coordinates and labels for circlesconstint midx[9]={50,100,150,50,100,150,50,100,150};
constint midy[9]={150,150,150,200,200,200,250,250,250};
constchar label[9][2]={"1","2","3","4","5","6","7","8","9"};

// ENUMERATED DATATYPESenum turn { human1, human2};
enumbool { false, true};

// FUNCTIONS USEDvoid IllegalMove(int type);        // validates the entered cell no.void DeclareWinner(turn player);    // declare the winnervoid IllegalMove(int type)
{
   int x;
   x=getmaxx();
   setcolor(BLACK);

   settextjustify(CENTER_TEXT, CENTER_TEXT);
   settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);

   outtextxy(x/2-10,375,"Illegal Move !!! Enter Again ...");
   if(type==OutOfRange)
      outtextxy(x/2-10,400,"Invalid Cell Number");
   else
      outtextxy(x/2-10,400,"Cell Is Pre-occupied");
   while(!kbhit())
   {
      setcolor(BROWN);
      outtextxy(x/2-10,375,"Illegal Move !!! Enter Again ...");
      if(type==OutOfRange)
     outtextxy(x/2-10,400,"Invalid Cell Number");
      else
     outtextxy(x/2-10,400,"Cell Is Pre-occupied");
      sound(2000);    delay(20);     nosound();
   }
   setcolor(BLACK);
   outtextxy(getmaxx()/2-10,375,"Illegal Move !!! Enter Again ...");
   if(type==OutOfRange)
      outtextxy(x/2-10,400,"Invalid Cell Number");
   else
      outtextxy(x/2-10,400,"Cell Is Pre-occupied");
}// end IllegalMove()void DeclareWinner(turn player)
{
   setcolor(WHITE);

   settextjustify(CENTER_TEXT, CENTER_TEXT);
   settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);

   if(player==human1)
      outtextxy(getmaxx()/2-10,375,"P L A Y E R - 1  is the  W I N N E R !!!");
   else
      outtextxy(getmaxx()/2-10,375,"P L A Y E R - 2  is the  W I N N E R !!!");
   sound(5000); sleep(2); nosound();
}// end DeclareWinner()//**************************************************************************// CLASS Board//**************************************************************************class Board{
   private:
      int p1[9];        // cells marked with player1 movesint p2[9];        // cells marked with player2 moves
      turn player;        // human1 / human2 / machine to play nextint p1_turns;        // number of turns p1 hadint p2_turns;        // number of turns p2 hadpublic:
      Board();            // constructorbool IsWin(void);        // is there a win in this position?bool IsLegal(int pos);    // is the move legal?void MakeMove(int pos);    // make a movevoid SetPlayer(turn p);    // swap player1 and player2
      turn WhoPlays(void);    // returns the player currently playingint GetTurn(void);    // get the turn player is takingvoid plot_board(void);    // displays the boardvoid fill_cell(constint pos, constint player); // displays boards statusvoid ResetAll(void);       // resets everything
};// end class Board

Board::Board()
{
   for(int i=0; i<9; i++)
   {
      p1[i]=empty;          // reset all cells to empty
      p2[i]=empty;
   }

   player=human1;        // set 1st player as human1// set initial turns of p1 and p2 to 0 (zero)
   p1_turns=0;
   p2_turns=0;
}// end Board()bool Board::IsWin()
{
   int *ptr;

   if(player==human1)
      ptr=p1;                // point to appropriate arrayelse
      ptr=p2;

   // check for 3 in a Row or 3 in a Columnif( (ptr[0] && ptr[1] && ptr[2]) ||    // horizontal
       (ptr[3] && ptr[4] && ptr[5]) ||
       (ptr[6] && ptr[7] && ptr[8]) ||
       (ptr[0] && ptr[3] && ptr[6]) ||    // vertical
       (ptr[1] && ptr[4] && ptr[7]) ||
       (ptr[2] && ptr[5] && ptr[8]) ||
       (ptr[0] && ptr[4] && ptr[8]) ||    // diagonal
       (ptr[2] && ptr[4] && ptr[6]) )
   {
      setcolor(BLACK);
      setlinestyle(SOLID_LINE,1,THICK_WIDTH);

      if(ptr[0] && ptr[1] && ptr[2])
     line(midx[0],midy[0],midx[2],midy[2]);
      if(ptr[3] && ptr[4] && ptr[5])
     line(midx[3],midy[3],midx[5],midy[5]);
      if(ptr[6] && ptr[7] && ptr[8])
     line(midx[6],midy[6],midx[8],midy[8]);

      if(ptr[0] && ptr[3] && ptr[6])
     line(midx[0],midy[0],midx[6],midy[6]);
      if(ptr[1] && ptr[4] && ptr[7])
     line(midx[1],midy[1],midx[7],midy[7]);
      if(ptr[2] && ptr[5] && ptr[8])
     line(midx[2],midy[2],midx[8],midy[8]);

      if(ptr[0] && ptr[4] && ptr[8])
     line(midx[0],midy[0],midx[8],midy[8]);
      if(ptr[2] && ptr[4] && ptr[6])
     line(midx[2],midy[2],midx[6],midy[6]);

      returntrue;
   }
   returnfalse;
}// end IsWin()bool Board::IsLegal(int pos)
{
   if(p1[pos-1]==empty && p2[pos-1]==empty)
      returntrue;
   returnfalse;
}// end IsLegal()void Board::MakeMove(int pos)
{
   if(player==human1)
   {
      p1[pos-1]=full;
      p1_turns++;
      fill_cell(pos-1,human1);
   }
   else
   {
      p2[pos-1]=full;
      p2_turns++;
      fill_cell(pos-1,2);
   }
}// end MakeMove()void Board::SetPlayer(turn p)
{
   player=p;
}// end SetPlayer()

turn Board::WhoPlays(void)
{
   return player;
}// end WhoPlays()int Board::GetTurn()
{
   if(player==human1)
      return p1_turns;
   return p2_turns;
}// end GetTurnvoid Board::plot_board()
{
   int maxx,maxy;
   setcolor(BLUE);

   // draw the border
   setlinestyle(SOLID_LINE,1,NORM_WIDTH);
   rectangle(15,115,185,285);
   setfillstyle(SOLID_FILL,BROWN);
   floodfill(30,130,BLUE);

   setlinestyle(SOLID_LINE,1,NORM_WIDTH);
   rectangle(20,120,180,280);
   setfillstyle(SOLID_FILL,YELLOW);
   floodfill(30,130,BLUE);

   setlinestyle(SOLID_LINE,1,THICK_WIDTH);
   rectangle(25,125,175,275);
   setfillstyle(SOLID_FILL,MAGENTA);
   floodfill(30,130,BLUE);

   setlinestyle(SOLID_LINE,1,NORM_WIDTH);

   // draw 9 circlefor(int i=0,j=0; i<9,j<9; i++,j++)
      circle(midx[i],midy[i],radius);

   // fill the circles with black colourfor(i=0,j=0; i<9,j<9; i++,j++)
   {
      setfillstyle(SOLID_FILL,WHITE);
      floodfill(midx[i],midy[i],BLUE);
   }// end for// label each circlefor(i=0,j=0; i<9,j<9; i++,j++)
   {
      setcolor(BLUE);
      settextjustify(CENTER_TEXT, CENTER_TEXT);
      settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
      outtextxy(midx[i],midy[i],label[i]);
   }// end for// cursor positions where moves will be made
   {
      int px,p1y,p2y;
      maxx=getmaxx();
      maxy=getmaxy();
      setcolor(YELLOW);
      settextjustify(CENTER_TEXT, CENTER_TEXT);
      settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 1);
      outtextxy(maxx/2-10, maxy/2-100, "M O V E S . . .");
      setcolor(RED);
      outtextxy(maxx/2+80, maxy/2-40, "Player1 : |");

      px=maxx/2+135; p1y=maxy/2-40;
      for(i=1; i<=5; i++)
      {
     outtextxy(px, p1y, "_|");
     px += 23;
      }// end for

      setcolor(GREEN);
      outtextxy(maxx/2+80, maxy/2+9, "Player2 : |");

      px=maxx/2+135; p2y=maxy/2+9;
      for(i=1; i<=5; i++)
      {
     outtextxy(px, p2y, "_|");
     px += 23;
      }// end for
   }
}// end plot_board()void Board::fill_cell(constint pos, constint player)
{
   int i=pos;
   if(i==3 || i==5 || i==7 || i==8)
   {
      setfillstyle(SOLID_FILL,BLUE);
      floodfill(midx[i]+10,midy[i]+10,BLUE);

      setfillstyle(SOLID_FILL,WHITE);
      floodfill(midx[i]+10,midy[i]+10,MAGENTA);

      setlinestyle(SOLID_LINE,1,NORM_WIDTH);
      setcolor(BLUE);
      circle(midx[i],midy[i],radius);

      if(player==human1)
     setfillstyle(SOLID_FILL,RED);
      else
     setfillstyle(SOLID_FILL,GREEN);

      floodfill(midx[i]+10,midy[i]+10,BLUE);

      settextjustify(CENTER_TEXT, CENTER_TEXT);
      settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
      outtextxy(midx[i],midy[i],label[i]);
   }
   else
   {
      if(player==human1)
     setfillstyle(SOLID_FILL,RED);
      elseif(player==2)
     setfillstyle(SOLID_FILL,GREEN);
      floodfill(midx[i]+10,midy[i]+10,BLUE);
   }
}// end fill_cell()void Board::ResetAll(void)
{
   for(int i=0; i<9; i++)
   {
      p1[i]=empty;          // reset all cells to empty
      p2[i]=empty;
   }

   player=human1;        // set 1st player as human1// set initial turns of p1 and p2 to 0 (zero)
   p1_turns=0;
   p2_turns=0;
}// end ResetAll()//**************************************************************************// FUNCTION main()//**************************************************************************void main(void)
{
   void main_menu(void);

   Board Board1;    // object of class Board
   turn  Turn;        // whos turn is it (human1, human2)char ans='y';    // users choice .. continue play or notint count;        // counts total number of movesconst xcoord[5]={57,60,63,66,69};  // coordinates where player is gonnaconst ycoord[2]={13,16};          // enter the cell no.int p_turn;        // no. of turns player hadint cell_no=0;    // cell no. entered by userint x,y;

   // request auto detectionint gmode,gdriver=DETECT,errorcode;

   // initialize graphics and local variables
   initgraph(&gdriver,&gmode,"\\tc\\BGI");

   // read result of initialization
   errorcode = graphresult();
   if (errorcode != grOk)      // an error occurred
   {
      cout<<"Graphics error: %s\n"<< grapherrormsg(errorcode);
      cout<<"Press any key to exit:";
      getch();
      exit(1);             // terminate with an error code
   }

   while(tolower(ans)!='n')
   {
      // clear the device (screen)
      cleardevice();

      setcolor(YELLOW);
      settextstyle(DEFAULT_FONT,HORIZ_DIR,1);
      outtextxy(getmaxx()/2-90,4,"TIC - TAC - TOE");
      outtextxy(getmaxx()/2-90,16,"***************");

      Board1.plot_board();
      count=1;

      while(count<=9)
      {
     Turn=Board1.WhoPlays();
     p_turn=Board1.GetTurn();

     if(Turn==human1)
     {
        setcolor(BLACK);
        settextjustify(CENTER_TEXT, CENTER_TEXT);
        settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
        outtextxy(getmaxx()/2-12,350," Player 2's Turn . . .");
        setcolor(YELLOW);
        outtextxy(getmaxx()/2-12,350," Player 1's Turn . . .");
        sound(500); delay(50); nosound();
     }
     else
     {
        setcolor(BLACK);
        settextjustify(CENTER_TEXT, CENTER_TEXT);
        settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
        outtextxy(getmaxx()/2-12,350," Player 1's Turn . . .");
        setcolor(YELLOW);
        outtextxy(getmaxx()/2-12,350," Player 2's Turn . . .");
        sound(1000); delay(50); nosound();
     }

     // get cell number from the player
     gotoxy(xcoord[p_turn],ycoord[Turn]);
     cell_no=getch()-'0';

     // check if valid cell no. is entered if not keep on askingwhile(cell_no<1 || cell_no>9)
     {
        IllegalMove(OutOfRange);
        gotoxy(xcoord[p_turn],ycoord[Turn]);
        cell_no=getch()-'0';
     }

     // check if the entered cell_no is legal (is not pre-occupied)while(Board1.IsLegal(cell_no) == false)
     {
        IllegalMove(OccupiedCell);
        gotoxy(xcoord[p_turn],ycoord[Turn]);
        cell_no=getch()-'0';
     }

     // display the cell no at proper position
     gotoxy(xcoord[p_turn],ycoord[Turn]);
     cout<<cell_no;

     // if not fill the cell
     Board1.MakeMove(cell_no);

     // if number of turns of a player exceeds 2 then check if this move// made him win or not as atleast 3 moves are required for a player// to win this gameif(p_turn>=2)
        if(Board1.IsWin())
        {
           DeclareWinner(Turn);
           count=10;
        }

     // swap playersif(Turn==human1)
        Board1.SetPlayer(human2);
     else
        Board1.SetPlayer(human1);

     // increment count
     count++;
      }// end while(count<=9)// count = 10 means there is no winner ... game is a drawif(count==10)
      {
     setcolor(WHITE);
     outtextxy(getmaxx()/2-10,375,"I T  I S  A   D R A W !!!");
     sound(5000); sleep(2); nosound();
      }// end if// clear the device (screen)
      cleardevice();

      // ask the user if he wnts to continue
      setcolor(YELLOW);
      settextjustify(CENTER_TEXT, CENTER_TEXT);
      settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
      outtextxy(getmaxx()/2,getmaxy()/2-7,"DO YOU WANT TO PLAY MORE : (y / n) : ");
      gotoxy(60,15);
      ans=getch();

      while(tolower(ans)!='y' && tolower(ans)!='n')
      {
     setcolor(BLACK);
     settextjustify(CENTER_TEXT, CENTER_TEXT);
     settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
     outtextxy(getmaxx()/2,getmaxy()/2-7,"DO YOU WANT TO PLAY MORE : (y / n) :   ");
     setcolor(YELLOW);
     outtextxy(getmaxx()/2,getmaxy()/2-7,"DO YOU WANT TO PLAY MORE : (y / n) : ");
     gotoxy(60,15);
     ans=getch();
      }

      gotoxy(60,15);
      cout<<ans;
      getch();

      if(tolower(ans)=='y')
     Board1.ResetAll();
      else
      {
     y=350;
     int bk=getbkcolor();
     for(int i=640;;i--)
     {
        setcolor(BROWN);
        outtextxy(i,y,"THANK YOU ... HAVE NICE TIME");
        delay(5);
        if(i==330)
           break;
        else
        {
           setcolor(bk);
           outtextxy(i,y,"THANK YOU ... HAVE NICE TIME");
        }
     }// end for
      }// end if(ans=='y')
   }// end while(tolower(ans)!='n')// get user end key stroke
   getch();

   // clean up ... close the graph
   closegraph();
}// end main()

Program to find a Book in the list of Books


Code for Program to find a Book in the list of Books in C++ Programming



 



 



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

 main( )
    {
       clrscr();

       constint no_of_books=10;

       int flag=0;

       char libarary[no_of_books][40]=
               {"Physics","Math","English","Urdu","Biology","Biology",
            "Calculus","Data Base","Automata","Mathematics" };
       char book_name[10];

       cout<<"\n Enter the name of the book you want to find : ";
       gets(book_name);

       for(int count=0;count<no_of_books;count++)
      {
         if(strcmpi(&libarary[count][0],book_name)==0)
        {
           flag=1;
           break;
        }
      }

       if(flag==1)
      {
         cout<<"\n The given book is found and its library number is ";
         cout<<count<<endl;
      }

       else
      cout<<"\n The given book is not found "<<endl;

       getch();
       return 0;
    }

Program to illustrate the use of the continue statement

Code for Program to illustrate the use of the continue statement in C++ Programming

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

 /*************************************************************************//*************************************************************************///-----------------------------  Main( )  -------------------------------///*************************************************************************//*************************************************************************/

 main()
    {
       clrscr();

       cout<<"\n ********  Continue Statement  *********"<<endl;

       int flag;

       for(int count=1;count<=10;count++)
      {
         if(count==5)
        {
           flag=count;
           continue;
        }

         cout<<" "<<count;
      }

       cout<<"\n\n Countinue occured at flag = "<<flag<<endl;

       getch();
       return 0;
    }

Program to print a diamond

Code for Program to print a diamond in C++ Programming




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

 main()
    {
       clrscr();

       cout<<"\n ********* Diamond  *********\n"<<endl;

       int x_1=19;
       int y_1=5;

       for(int count_1=1;count_1<=5;count_1++)
      {
         gotoxy(x_1,y_1);

         for(int count_2=1;count_2<=count_1;count_2++)
        cout<<"* ";

         x_1--;
         y_1++;

         cout<<endl;
      }


       int x_2=16;
       int y_2=10;

       for(int count_3=5;count_3>1;count_3--)
      {
         gotoxy(x_2,y_2);

         for(int count_4=count_3;count_4>1;count_4--)
        cout<<"* ";

         x_2++;
         y_2++;

         cout<<endl;
      }
       getch();
       return 0;
    }

Program to swap two variables using header file "swap.h"


Code for Program to swap two variables using header file "swap.h" in C++ Programming



 



 
#include<iostream.h>
 #include<conio.h>
 #include<iomanip.h>
 #include"swap.h"// Attached in source code zip


 main()
    {
       clrscr();

       int int_1=2;
       int int_2=3;

       char char_1='A';
       char char_2='B';

       float float_1=2.5;
       float float_2=3.0;

       cout<<"\n ******** Integers ********"<<endl;

       cout<<"Before swap :"<<endl;
       cout<<setw(15)<<"int_1 = "<<int_1<<endl;
       cout<<setw(15)<<"int_2 = "<<int_2<<endl;

       swap(&int_1,&int_2);

       cout<<"After swap :"<<endl;
       cout<<setw(15)<<"int_1 = "<<int_1<<endl;
       cout<<setw(15)<<"int_2 = "<<int_2<<endl;

       cout<<"******* Characters *******"<<endl;

       cout<<"Before swap :"<<endl;
       cout<<setw(15)<<"char_1 = "<<char_1<<endl;
       cout<<setw(15)<<"char_2 = "<<char_2<<endl;

       swap(&char_1,&char_2);

       cout<<"After swap :"<<endl;
       cout<<setw(15)<<"char_1 = "<<char_1<<endl;
       cout<<setw(15)<<"char_2 = "<<char_2<<endl;

       cout<<"********* Floats *********"<<endl;

       cout<<"Before swap :"<<endl;
       cout<<setw(15)<<"float_1 = "<<float_1<<endl;
       cout<<setw(15)<<"float_2 = "<<float_2<<endl;

       swap(&float_1,&float_2);

       cout<<"After swap :"<<endl;
       cout<<setw(15)<<"float_1 = "<<float_1<<endl;
       cout<<setw(15)<<"float_2 = "<<float_2<<endl;

       getch();
       return 0;
    }

Program to read all words from a file and remove all words which are palindromes


Code for Program to read all words from a file and remove all words which are palindromes in C++ Programming



 



 



 
 # include <iostream.h>
 # include <fstream.h>
 # include <string.h>
 # include <stdlib.h>
 # include <conio.h>

 int main( )
    {
       clrscr( );

       fstream file("CP-03.txt",ios::in|ios::nocreate);

       if(!file)
      {
         cout<<"\n Unable to open the input file."<<endl;
         cout<<"\n Press any key to exit.";

         getch( );
         exit(EXIT_FAILURE);
      }

       char Text_line[90]={NULL};

       file.getline(Text_line,80);

       int number_of_text_lines=atoi(Text_line);

       for(int counter=0;counter<number_of_text_lines;counter++)
      {
         strset(Text_line,NULL);

         file.getline(Text_line,80);

         int i=0;
         int j=0;

         char Word[80]={NULL};
         char Reverse_word[80]={NULL};

         do
        {
           strset(Word,NULL);
           strset(Reverse_word,NULL);

           j=0;

           do
              {
             Word[j]=Text_line[i];
             Reverse_word[j]=Text_line[i];

             i++;
             j++;
              }
           while(Text_line[i]!=' ' && Text_line[i]!=NULL);

           strrev(Reverse_word);

           if(strcmp(Word,Reverse_word)!=0)
              cout<<Word;

           if(Text_line[i]!=NULL)
              cout<<" ";

           i++;
        }
         while(Text_line[i]!=NULL);

         cout<<endl;
      }

       file.close( );

       getch( );
       return 0;
    }

Program to illustrate the declaration , initialization and printing a constant variable



Code for Program to illustrate the declaration , initialization and printing a constant variable in C++ Programming



 



 



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


 main()
    {
       clrscr();

       constfloat pi=3.1472;

       cout<<"\n Value of pi = "<<pi<<endl;

       getch();
       return 0;
    }

Program to draw a spiral rotating clockwise at the center of the screen


Code for Program to draw a spiral rotating clockwise at the center of the screen in C++ Programming



 



 



 
 # include <iostream.h>
 # include <fstream.h>
 # include <stdlib.h>
 # include <string.h>
 # include <conio.h>

 # define LEFT  0
 # define UP    1
 # define RIGHT 2
 # define DOWN  3

 constchar get_digit(constchar);


 int main( )
    {
       clrscr( );

       fstream File("CP-06.txt",ios::in|ios::nocreate);

       if(!File)
      {
         cout<<"\n Unable to open the input file."<<endl;
         cout<<"\n Press any key to exit.";

         getch( );
         exit(EXIT_FAILURE);
      }

       char Last_digit='0';
       char Input[85]={NULL};
       char Screen[25][80]={NULL};

       int direction=0;
       int length_of_spiral=0;

       File.getline(Input,80);

       direction=atoi(Input);

       strset(Input,NULL);

       File.getline(Input,80);

       length_of_spiral=atoi(Input);

       int i=0;
       int j=0;
       int k=1;
       int x=12;
       int y=39;
       int number_of_digits_in_a_direction=1;

       for(i=0;i<25;i++)
      {
         for(j=0;j<80;j++)
        Screen[i][j]='.';
      }

       Screen[x][y]=Last_digit;

       switch(direction)
      {
         case LEFT  : y-=2;
              break;

         case UP    : x-=2;
              break;

         case RIGHT : y+=2;
              break;

         case DOWN  : x+=2;
              break;
      }

       do
      {
         for(i=0;i<4;i++)
        {
           for(j=0;j<number_of_digits_in_a_direction;j++)
              {
             Screen[x][y]=get_digit(Last_digit);
             Last_digit=Screen[x][y];
             k++;

             if(j==(number_of_digits_in_a_direction-1))
                {
                   direction++;

                   if(direction==4)
                  direction=0;
                }

             if(k==length_of_spiral)
                break;

             switch(direction)
                {
                   case LEFT  : y-=2;
                        break;

                   case UP    : x-=2;
                        break;

                   case RIGHT : y+=2;
                        break;

                   case DOWN  : x+=2;
                        break;
                }
              }

           if(k==length_of_spiral)
              break;

           if(i==1)
              number_of_digits_in_a_direction++;
        }

         if(k==length_of_spiral)
        break;

         number_of_digits_in_a_direction++;
      }
       while(1);

       window(40,13,41,14);
       textbackground(BLUE);
       textcolor(WHITE);
       cprintf("0");

       window(1,1,1,1);

       for(i=0;i<25;i++)
      {
         for(j=0;j<80;j++)
        cout<<Screen[i][j];
      }

       getch( );
       return 0;
    }

 /*************************************************************************///------------------------  get_digit(const char)  ----------------------///*************************************************************************/constchar get_digit(constchar Last_digit)
    {
       char Next_digit=NULL;

       switch(Last_digit)
      {
         case'0' : Next_digit='1';
            break;

         case'1' : Next_digit='2';
            break;

         case'2' : Next_digit='3';
            break;

         case'3' : Next_digit='4';
            break;

         case'4' : Next_digit='5';
            break;

         case'5' : Next_digit='6';
            break;

         case'6' : Next_digit='7';
            break;

         case'7' : Next_digit='8';
            break;

         case'8' : Next_digit='9';
            break;

         case'9' : Next_digit='0';
            break;
      }

       return Next_digit;
    }

Program to illustrate an example of containership


Code for Program to illustrate an example of containership in C++ Programming



 



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

 constint length=50;

 /*************************************************************************///------------------------------  student  ------------------------------///*************************************************************************/class student
    {
       private:
        char school[length];
        char degree[length];

       public:
        void get_education();
        void show_education();
    };


 /*************************************************************************///------------------------------  employee  -----------------------------///*************************************************************************/class employee
    {
       private:
        char name[length];
        char id_number[length];

       public:
        void get_identification();
        void show_identification();
    };

 /*************************************************************************///------------------------------  manager  ------------------------------///*************************************************************************/class manager
    {
       private:
        char title[length];
        double club_dues;

        student stu;
        employee emp;

       public:
        void get_data();
        void show_data();
    };

 /*************************************************************************///------------------------------  scientist  ----------------------------///*************************************************************************/class scientist
    {
       private:
        int publications;

        student stu;
        employee emp;

       public:
        void get_data();
        void show_data();
    };

 /*************************************************************************///------------------------------  labour  -------------------------------///*************************************************************************/class labour
    {
       private:
        employee emp;

       public:
        void get_data();
        void show_data();
    };


 /*************************************************************************///-----------------------  get_education( )  ----------------------------///*************************************************************************/void student::get_education()
    {
       cout<<"\t Enter the School Name : ";
       gets(school);

       cout<<"\t Enter the highest Degree earned : ";
       gets(degree);
    }

 /*************************************************************************///-----------------------  show_education( )  ---------------------------///*************************************************************************/void student::show_education()
    {
       cout<<"\t School Name : "<<school<<endl;
       cout<<"\t Highest Degree earned : "<<degree<<endl;
    }

 /*************************************************************************//*************************************************************************///---------------------------  employee  --------------------------------///*************************************************************************//*************************************************************************//*************************************************************************///----------------------  get_identification( )  ------------------------///*************************************************************************/void employee::get_identification()
    {
       cout<<"\t Enter the Name : ";
       gets(name);

       cout<<"\t Enter the ID Number : ";
       gets(id_number);
    }

 /*************************************************************************///----------------------  show_identification( )  -----------------------///*************************************************************************/void employee::show_identification()
    {
       cout<<"\t Name : "<<name<<endl;
       cout<<"\t ID Number : "<<id_number<<endl;
    }

 /*************************************************************************//*************************************************************************///----------------------------  manager  --------------------------------///*************************************************************************//*************************************************************************//*************************************************************************///----------------------------  get_data( )  ----------------------------///*************************************************************************/void manager::get_data()
    {
       emp.get_identification();

       cout<<"\t Enter the Title : ";
       gets(title);

       cout<<"\t Enter the Club Dues : ";
       cin>>club_dues;

       stu.get_education();
    }

 /*************************************************************************///----------------------------  show_data( )  ---------------------------///*************************************************************************/void manager::show_data()
    {
       emp.show_identification();

       cout<<"\t Title : "<<title<<endl;
       cout<<"\t Club Dues : "<<club_dues<<endl;

       stu.show_education();
    }

 /*************************************************************************//*************************************************************************///----------------------------  scientist  ------------------------------///*************************************************************************//*************************************************************************//*************************************************************************///----------------------------  get_data( )  ----------------------------///*************************************************************************/void scientist::get_data()
    {
       emp.get_identification();

       cout<<"\t Enter the Number of Publications : ";
       cin>>publications;

       stu.get_education();
    }

 /*************************************************************************///---------------------------  show_data( )  ----------------------------///*************************************************************************/void scientist::show_data()
    {
       emp.show_identification();

       cout<<"\t Number of Publications : "<<publications<<endl;

       stu.show_education();
    }

 /*************************************************************************//*************************************************************************///-----------------------------  labour  --------------------------------///*************************************************************************//*************************************************************************//*************************************************************************///----------------------------  get_data( )  ----------------------------///*************************************************************************/void labour::get_data()
    {
       emp.get_identification();
    }

 /*************************************************************************///---------------------------  show_data( )  ----------------------------///*************************************************************************/void labour::show_data()
    {
       emp.show_identification();
    }


 main()
    {
       clrscr();

       manager m;
       scientist s;
       labour l;

       cout<<"\n *********  Manager  *********"<<endl;
       m.get_data();

       cout<<"\n *********  Scientist  ********"<<endl;
       s.get_data();

       cout<<"\n *********  Labour  ********"<<endl;
       l.get_data();

       getch();
       clrscr();

       cout<<"\n *********  Manager  *********"<<endl;
       m.show_data();

       cout<<"\n *********  Scientist  ********"<<endl;
       s.show_data();

       cout<<"\n *********  Labour  ********"<<endl;
       l.show_data();

       getch();
       return 0;
    }

Program to illustrate the use of call-by-refrence method using pointers



Code for Program to illustrate the use of call-by-refrence method using pointers in C++ Programming



 



 



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

 void swap(int *,int *);


 main()
    {
       clrscr();


       int value_1;
       int value_2;

       cout<<"\n Enter the value_1 =  ";
       cin>>value_1;

       cout<<"\n Enter the value_2 =  ";
       cin>>value_2;

       cout<<"\n *********  Before Swap()  ********"<<endl;

       cout<<"\n\t Value_1 =  "<<value_1<<endl;
       cout<<"\t Value_2 =  "<<value_2<<endl;

       cout<<"\n *********  After Swap()  ********"<<endl;

       swap(&value_1,&value_2);

       cout<<"\n\t Value_1 =  "<<value_1<<endl;
       cout<<"\t Value_2 =  "<<value_2<<endl;


       getch();
       return 0;
    }


 /*************************************************************************///-------------------------  swap(int *,int *)  -------------------------///*************************************************************************/void swap(int *x,int *y)
    {
       int temp;

       temp=*x;
       *x=*y;
       *y=temp;
    }

Program to illustrate unary operator increment operator overloading with return type


Code for Program to illustrate unary operator increment operator overloading with return type in C++ Programming



 



 



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

 /*************************************************************************///-----------------------------  counter  -------------------------------///*************************************************************************/class counter
    {
       private:
        int count;

       public:
        counter()  { count=0; }
        counter operator++();
        counter operator++(int);
        void showdata()  { cout<<count<<endl; }
     };


 /*************************************************************************///---------------------------  operator++( )  ---------------------------///*************************************************************************/

 counter counter::operator++()
    {
       ++count;

       counter temp;

       temp.count=count;

       return temp;
    }

 /*************************************************************************///---------------------------  operator++(int)  -------------------------///*************************************************************************/

 counter counter::operator++(int)
    {
       count++;

       counter temp;

       temp.count=count;

       return temp;
    }

 /*************************************************************************//*************************************************************************///-----------------------------  Main( )  -------------------------------///*************************************************************************//*************************************************************************/

 main( )
    {
       clrscr();

       counter obj1;

       cout<<"\n ********* Before Increment ******* "<<endl;
       cout<<"Data of obj1 is = ";
       obj1.showdata();

       obj1=++obj1;

       cout<<"\n ********* After Increment ******* "<<endl;
       cout<<"Data of obj1 is = ";
       obj1.showdata();

      obj1=obj1++;

       cout<<"\n ********* After Increment ******* "<<endl;
      cout<<"Data of obj1 is = ";
      obj1.showdata();

      getch();
      return 0;
    }

Program that reads a number ,coumputes and displays its factorial using do-while loop



Code for Program that reads a number ,coumputes and displays its factorial using do-while loop in C++ Programming



 



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

 /*************************************************************************//*************************************************************************///-----------------------------  Main( )  -------------------------------///*************************************************************************//*************************************************************************/

 main()
    {
       clrscr();

       int count=1;
       int number;
       long factorial=1;

       cout<<"\n Enter the number = ";
       cin>>number;

       if(number==0)
      factorial=1;

       else
      {
         do
        {
           factorial=factorial*count;
           count++;
        }
         while(count<=number);
      }

       cout<<"\n factorial ("<<number<<") = "<<factorial<<endl;

       getch();
       return 0;
    }

Program which shows content of a given 2D array


Code for Program which shows content of a given 2D array in C++ Programming



 



 



 
# include <iostream.h>
 # include <fstream.h>
 # include <string.h>
 # include <stdlib.h>
 # include <conio.h>

 int main( )
    {
       clrscr( );

       fstream File("CP-13.txt",ios::in|ios::nocreate);

       if(!File)
      {
         cout<<"Unable to open the input file."<<endl;
         cout<<"Press any key to exit."<<endl;

         getch( );
         exit(EXIT_FAILURE);
      }

       char Data[100]={NULL};

       do
      {
         strset(Data,NULL);

         File.getline(Data,80,'\n');

         if(strcmpi(Data,"0")==0)
        break;

         char *Ptr=NULL;

         int rows=0;
         int columns=0;

         Ptr=strtok(Data," ");
         rows=atoi(Ptr);

         Ptr=NULL;
         Ptr=strtok(NULL,"\n");
         columns=atoi(Ptr);

         char Array2d[50][50]={NULL};

         for(int count_1=0;count_1<rows;count_1++)
        File.getline(Array2d[count_1],80);

         int direction=0;

         do
        {
           char Temp[50][50]={NULL};

           if(direction==0)
              {
             cout<<Array2d[0];

             for(int count_2=1;count_2<rows;count_2++)
                strcpy(Temp[(count_2-1)],Array2d[count_2]);

             rows--;
              }

           elseif(direction==1)
              {
             for(int count_3=0;count_3<rows;count_3++)
                {
                   cout<<Array2d[count_3][(columns-1)];

                   Array2d[count_3][(columns-1)]=NULL;
                }

             for(int count_4=0;count_4<rows;count_4++)
                strcpy(Temp[count_4],Array2d[count_4]);

             columns--;
              }

           elseif(direction==2)
              {
             cout<<strrev(Array2d[(rows-1)]);

             for(int count_5=0;count_5<(rows-1);count_5++)
                strcpy(Temp[count_5],Array2d[count_5]);

             rows--;
              }

           elseif(direction==3)
              {
             for(int count_6=(rows-1);count_6>=0;count_6--)
                cout<<Array2d[count_6][0];

             for(int count_7=0;count_7<rows;count_7++)
                {
                   for(int count_8=1;count_8<columns;count_8++)
                  Temp[count_7][(count_8-1)]=Array2d[count_7][count_8];
                }

             columns--;
              }

           direction++;

           if(direction==4)
              direction=0;

           for(int count_9=0;count_9<50;count_9++)
              {
             strset(Array2d[count_9],NULL);
             strcpy(Array2d[count_9],Temp[count_9]);
              }

           if(rows==0)
              break;
        }
         while(1);

         cout<<endl;
      }
       while(1);

       File.close( );

       getch( );
       return 0;
    }

Program that defines template of vector class that provides modify and multiplication facility


Code for Program that defines template of vector class that provides modify and multiplication facility in C++ Programming



 



 



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

template <class T>
class vector
{
    T *arr;
    int size;

    public:

    vector() {
       arr=NULL;
       size=0;
    }

    vector(int m);
    vector(T *a,int n);
    void modify(T value,int index);
    void multiply(int scalarvalue);
    void display();
};

template <class T>
vector<T> :: vector(int m)
{
   size=m;
   arr = new T[size];
   for(int i=0;i<size;i++)
       arr[i]=0;
}

template <class T>
vector<T> :: vector(T *a,int n)
{
   size=n;
   arr = new T[size];
   for(int i=0;i<size;i++)
       arr[i]=a[i];
}


template <class T>
void vector<T> :: modify(T value,int index)
{
    arr[index]=value;
}


template <class T>
void vector<T> :: multiply(int scalarvalue)
{
    for(int i=0;i<size;i++)
       arr[i] = arr[i] * scalarvalue;
}

template <class T>
void vector<T> :: display()
{
    cout<<"(";
    for(int i=0;i<size;i++)
    {
        cout<<arr[i];
        if(i!=size-1)
           cout<<", ";
    }
    cout<<")";
}


void main()
{
    clrscr();


    //Creating Integer Vector.int iarr[]={1,2,3,4,5};
    cout << "Integer Values \n";
    for(int i=0; i < 5; i++)
    {
        cout << "Enter integer value "  << i+1 << " : ";
        cin >> iarr[i];
    }
    vector <int> v1(iarr,5); //Integer array with 5 elements.
    cout<<"\nInteger Vector : ";
    v1.display();
    cout<<"\n\nModify index 3 with value 15\n";
    v1.modify(15,3); //modifying index 3 with value 15.
    cout<<"After Modification : ";
    v1.display();
    cout<<"\n\nMultiply with scalar value : 10\n";
    v1.multiply(10); //Multiply with scalar value 10.
    cout<<"After Multiplying : ";
    v1.display();
    cout<<"\n\n";


    //Creating double Vector.double darr[]={1.1,2.2,3.3,4.4,5.5};
    vector <double> v2(darr,5); //Double array with 5 elements.
    cout<<"\nDouble Vector : ";
    v2.display();
    cout<<"\n\nModify index 0 with value 9.9 \n";
    v2.modify(9.9,0); //modifying index 0 with value 9.9.
    cout<<"After Modification : ";
    v2.display();
    cout<<"\n\nMultiply with scalar value : 10\n";
    v2.multiply(10); //Multiply with scalar value 10.
    cout<<"After Multiplying : ";
    v2.display();
    cout<<"\n\n";

    getch();



}