Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Wednesday, November 23, 2011

How to check which key is pressed in keyboard using c program ???


void main()
{
char ch;
clrscr();
printf("Enter any character");
scanf("%c",&ch);

if(ch>=65 && ch<=90)
printf("%c Upper case alphabet pressed", ch);
else if(ch>=97 && ch<=122)
printf("%c Small case alphabet pressed", ch);
else if(ch>=48 && ch<=57)
printf("%c digit pressed",ch);
else
printf("%c  symbol pressed ", ch);
getch();
}

How to find biggest of three numbers using c program ???


void main()
{
int s1, s2, s3;
clrscr();
printf("Enter any three numbers ");
scanf("%d%d%d", &s1, &s2, &s3);

if(s1>s2 && s1>s3)
printf("First No is big");
else if(s2>s1 && s2>s3)
printf("Second No is big");
else
printf("Third No is big");

getch();
}

How to enter the data into a file and then copy into another file ????


Here i am posting a program which writes the data which you have entered into ganesh through console and copies that data particular data into another file .



#include<stdio.h>
void main()
{
FILE *f1, *f2;
char ch;
f1 = fopen("Ganesh.txt","w+");
f2 = fopen("Simple.txt","w");
printf("Enter data into ganesh file (ctrl+z to stop) : ");
while((ch=getchar())!=EOF)
putc(ch, f1);
rewind(f1);
while((ch=getc(f1))!=EOF)
putc(ch, f2);
printf("\n\t\tData copied from ganesh to simple file");
fclose(f1);
fclose(f2);
getch();
}

C and C++ Examples ( Employee salary example)


void main()
{
int eno, bs;
char ename[15];
float da, hra, lic, pf, netsal;
clrscr();
printf("Enter emp no, name and basic ");
scanf("%d%s%d", &eno, &ename, &bs);

if(bs>5000 && bs<10000)
{
da = bs*0.15;
hra = bs*0.06;
lic = bs*0.05;
pf = bs*0.08;
}
else if(bs>=10000 && bs<20000)
{
da = bs*0.20;
hra = bs*0.10;
lic = bs*0.07;
pf = bs*0.09;
}
else if(bs>=20000 && bs<30000)
{
da = bs*0.25;
hra = bs*0.15;
lic = bs*0.09;
pf = bs*0.11;
}
else if(bs>=30000)
{
da = bs*0.30;
hra = bs*0.20;
lic = bs*0.15;
pf = bs*0.18;
}
netsal = bs+da+hra-lic-pf;
printf("DA = %f\tHRA = %f", da, hra);
printf("\nLIC = %f\tPF = %f", lic, pf);
printf("\nNet Salary %f", netsal);
getch();
}





C and C++ Examples ( graphics.h example )


/* ==============  Program Description  ============= */
/*   program name : ch24_25.c                         */
/*   getpixel() application.                          */
/* ================================================== */
#include  <graphics.h>

void main()
{
    int     driver = DETECT,mode;
    int     i;

    initgraph(&driver,&mode,"c:\\borlandc\\bgi");
    line(100,100,500,100);
    for ( i = 20; i < 300; i++ )
if ( getpixel(300,i) == WHITE )
{
  setcolor(BLUE);
  circle(300,i,5);
}
else
  putpixel(300,i,WHITE);
    getch();
    closegraph();
}

C and C++ Examples (GREP FILTER)


/*
   EXAMPLE SOURCE CODE FOR GREP FILTER

   Grep2Msg.C
   Copyright (c) 1990, 1991 Borland International, Inc.
   All rights reserved.

   Grep2Msg - Message filter from Turbo Grep to Turbo C++ IDE message window

   This filter accepts input through the standard input stream, converts
   it and outputs it to the standard output stream.  The streams are linked
   through pipes, such that the input stream is the output from GREP, and
   the output stream is connected to the message window of the Turbo C++ IDE.
   This filter is invoked through the Turbo C++ IDE transfer mechanism as

            grep <commands> | grep2msg | TC IDE

    Compile using Turbo C++ in the LARGE memory model

    tcc -ml grep2msg
*/

#include <dir.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <alloc.h>
#include <io.h>
#include <dos.h>
#include "filter.h"

#define TRUE  1
#define FALSE 0

char     NewFileText[] = "File ";
unsigned BufSize,CurBufLen;
char     *InBuffer,
         *OutBuffer,
         *CurInPtr,
         *CurOutPtr,
         *LinePtr;
char     Line[133];
long int InOff;
char     EndMark;
int      NoLines;

/************************************************************************
Function  : NextChar
Parameters: None
Returns   : next character in input buffer or 0 for end of file

Input from the standard input stream is buffered in a global buffer InBuffer
which is allocated in function main.  NextChar function will return
the next character in the buffer, reading from the input stream when the
buffer becomes empty.
************************************************************************/
char NextChar(void)
{
   if (CurInPtr < InBuffer+CurBufLen)   /* if buffer is not empty */
   {
      return *(CurInPtr++);             /* return next information */
   }
   else
   {
      CurInPtr = InBuffer;              /* reset pointer to front of buffer */
      lseek(0,InOff,0);                 /* seek to the next section for read */
      InOff += BufSize;                 /* increment pointer to next block */
      if ((CurBufLen = read(0,InBuffer,BufSize)) !=0)
         return NextChar();             /* recursive call returns first
                                           character in buffer after read */
      return 0;                         /* return 0 on end of file */
   }
}

/*************************************************************************
Function  : flushOut
Parameters: Size   The number of characters to be written out
Returns   : nothing

Strings to be sent to the message window are placed in a buffer called
OutBuffer.  A call to this function will write Size bytes to the
standard output stream and reset the output buffer pointer to the
beginning of the buffer.  Any additional information in the buffer is
thus lost.
**************************************************************************/
void flushOut(unsigned Size)
{
  if (Size != 0)                 /* don't flush an empty buffer */
  {
    CurOutPtr = OutBuffer;       /* reset pointer to beginning of buffer */
    lseek(1,0,2);                /* seek output stream to end */
    write(1,OutBuffer,Size);     /* write out Size bytes */
  }
}

/**************************************************************************
Function  : Put
Parameters: S     pointer to a string of characters
            Len   length of the string of characters
Returns   : Nothing.

Put places bytes into OutBuffer so they may be later flushed out into the
standard output stream using flushOut.
*************************************************************************/
void Put(char *S,int Len)
{
  int i;

  for (i = 0; i < Len; i++)
  {
    *CurOutPtr++ = S[i];                     /* place byte in buffer */
    if (CurOutPtr >= OutBuffer+BufSize)      /* if buffer overflows */
      flushOut(BufSize);                     /* flush to the stream */
  }
}



Tuesday, November 22, 2011

C and C++ Examples ( Multiple inheritance )


      /* PROGRAM TO IMPLEMENT MULTIPLE INHERITANCE */
#include<iostream.h>
#include<conio.h>
class lang
{
protected:
int tel,hin,eng;
public:
void getlang()
{
cout<<"enter tel,hin,eng marks:";
cin>>tel>>hin>>eng;
}
void putlang()
{
cout<<"the tel,hin,eng marks are:"<<tel<<endl<<hin<<endl<<eng<<endl;
}
};
class group
{
protected:
int math,phy,che;
public:
void getgroup()
{
cout<<"enter math,phy,che marks:\n";
cin>>math>>phy>>che;
}
void putgroup()
{
cout<<"the math,phy,che are";
cout<<math<<" "<<phy<<" "<<che<<" ";
}
};
class tot : public lang,public group
{
private:
int tot;
public:
void gettot()
{
tot=tel+hin+eng+math+phy+che;
}
void puttot()
{
cout<<"the total is"<<endl;
cout<<tot;
}
};
void main()
{
tot t;
t.getlang();
t.putlang();
t.getgroup();
t.putgroup();
t.gettot();
t.puttot();
getch();
}


OUTPUT :

enter tel,hin,eng marks: 74
96
86

enter math,phy,che marks:
77
98
85
 the total is:  516


C and C++ Examples ( MultiLevel Inheritance )


   /* PROGRAM TO IMPLEMENT MULTILEVEL INHERITANCE */
#include<iostream.h>
class Cpolygon
 {
protected:
int width,height;
public:
void set_values(int a,int b)
{width=a;height=b;}
 };
class Coutput
 {
public:
void output(int i);
 };
void Coutput::output(int i)
 {
cout<<i<<endl;
 }
class Crectangle:public Cpolygon,public Coutput
 {
public:
int area()
{return(width*height);}
 };
class Ctriangle:public Cpolygon,public Coutput
 {
public:
int area()
{return(width*height/2);}
 };
int main()
 {
Crectangle rect;
Ctriangle trgl;
rect.set_values(4,5);
trgl.set_values(4,5);
rect.output(rect.area());
trgl.output(trgl.area());
return 0;
 }


Output :

20
10

C and C++ Examples ( Hydbrid Inheritance )


/*/PROGRAM TO IMPLEMENT HYBRID INHERITANCE/*/
#include<iostream.h>
#include<conio.h>
class student
 {
private:
int rn;
char na[20];
public:
void getdata()
{
cout<<"Enter name and rollno:";
cin>>na>>rn;
}
void putdata()
{
cout<<endl<<na<<"\t"<<rn<<"\t";
}
 };
class test:public student
 {
protected:
float m1,m2;
public:
void gettest()
{
cout<<endl<<"Enter ur marks in cp1 & cp2:";
cin>>m1>>m2;
}
void puttest()
{
cout<<m1<<"\t"<<m2<<"\t";
}
 };
class sports
 {
protected:
float score;
public:
void getscore()
{
cout<<endl<<"Enter ur score:";
cin>>score;
}
void putscore()
{
cout<<score<<"\t";
}
 };
class results:public test,public sports
 {
private:
float total;
public:
void putresult()
{
total=m1+m2+score;
cout<<total;
}
 };
void main()
 {
results s[2];
clrscr();
for(int i=0;i<2;i++)
{
s[i].getdata();
s[i].gettest();
s[i].getscore();
}
cout<<"________"<<endl;
cout<<endl<<"Name\tRollno\tcp1\tcp2\tscore\tTotal"<<endl;
cout<<"-----"<<endl;
for(i=0;i<2;i++)
{
s[i].putdata();
s[i].puttest();
s[i].putscore();
s[i].putresult();
}
cout<<endl<<"-----";
getch();
 }

Output :


Enter name and rollno:Hari
1214

Enter ur marks in cp1 & cp2: 89
91

Enter ur score: 180
Enter name and rollno: Raghu
1215

Enter ur marks in cp1 & cp2: 78
82

Enter ur score: 160
________

Name    Rollno  cp1     cp2     score   Total
-----

Hari    1214    89      91      180     360
Raghu   1215    78      82      160     320

C and C++ Examples ( Static Function )


  /* PROGARAM TO IMPLEMENT USING STATIC FUNCTION */
#include"iostream.h"
/*using namespace std;*/
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount(void)
{
cout<<"count";
cout<<count<<"\n";
}
};
int item::count ;
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(10);
b.getdata(20);
c.getdata(30);
cout<<"after reading data"<<"\n";
a.getcount();
b.getcount();
c.getcount();
return 0;
}

Output :

count0
count0
count0
after reading data
count3
count3
count3

Monday, November 21, 2011

C and C++ Examples(Figure ToolBox)


// Borland C++ - (C) Copyright 1991 by Borland International

// FIGDEMO.CPP -- Exercise in Getting Started

// demonstrates the Figures toolbox by extending it with
// a new type Arc.

// Link with FIGURES.OBJ and GRAPHICS.LIB

#include "figures.h"
#include <graphics.h>
#include <conio.h>

class Arc : public Circle {
   int StartAngle;
   int EndAngle;
public:
// constructor
   Arc(int InitX, int InitY, int InitRadius, int InitStartAngle, int
       InitEndAngle) : Circle (InitX, InitY, InitRadius) {
       StartAngle = InitStartAngle; EndAngle = InitEndAngle;}
   void Show();  // these functions are virtual in Point
   void Hide();
};

// Member functions for Arc

void Arc::Show()
{
   Visible = true;
   arc(X, Y, StartAngle, EndAngle, Radius);
}

void Arc::Hide()
{
   int TempColor;
   TempColor = getcolor();
   setcolor (getbkcolor());
   Visible = false;
   // draw arc in background color to hide it
   arc(X, Y, StartAngle, EndAngle, Radius);
   setcolor(TempColor);
}

int main()   // test the new Arc class
{
   int graphdriver = DETECT, graphmode;
   initgraph(&graphdriver, &graphmode, "..\\bgi");
   Circle ACircle(151, 82, 50);
   Arc AnArc(151, 82, 25, 0, 190);

   // you first drag an arc using arrow keys (5 pixels per key)
   // press Enter when tired of this!
   // Now drag a circle (10 pixels per arrow key)
   // Press Enter to end FIGDEMO.

   AnArc.Drag(5);   // drag increment is 5 pixels
   AnArc.Hide();
   ACircle.Drag(10); // now each drag is 10 pixels
   closegraph();
   return 0;
}

C and C++ Examples ( Hash Table)


/*------------------------------------------------------------------------*/
/*                                                                        */
/*  HASHTBL.CPP                                                           */
/*                                                                        */
/*  Copyright Borland International 1991                                  */
/*  All Rights Reserved                                                   */
/*                                                                        */
/*------------------------------------------------------------------------*/

#if !defined( __HASHTBL_H )
#include <HashTbl.h>
#endif  // __HASHTBL_H

#ifndef __IOSTREAM_H
#include <iostream.h>
#endif

HashTable::HashTable( sizeType aPrime ) :
    size( aPrime ),
    table( aPrime ),
    itemsInContainer(0)
{
}

void HashTable::add( Object& objectToAdd )
{
    hashValueType index = getHashValue( objectToAdd );
    if( table[ index ] == 0 )
        table[index] = new List;
    ((List *)table[ index ])->add( objectToAdd );
    itemsInContainer++;
}

void HashTable::detach( Object& objectToDetach, DeleteType dt )
{
    hashValueType index = getHashValue( objectToDetach );
    if( table[ index ] != 0 )
        {
        unsigned listSize = ((List *)table[ index ])->getItemsInContainer();
        ((List *)table[ index ])->detach( objectToDetach, delItem(dt) );
        if( ((List *)table[ index ])->getItemsInContainer() != listSize )
            itemsInContainer--;
        }
}

static void setOwner( Object& list, void *owns )
{
    ((List&)list).ownsElements( *(TShouldDelete::DeleteType *)owns );
}

void HashTable::flush( DeleteType dt )
{
    int shouldDel = delObj( dt );
    table.forEach( setOwner, &shouldDel );
    table.flush( 1 );
    itemsInContainer = 0;
}

Object& HashTable::findMember( Object& testObject ) const
{
    hashValueType index = getHashValue( testObject );
    if( index >= table.limit() || table[ index ] == 0 )
        {
        return NOOBJECT;
        }
    return ((List *)table[ index ])->findMember( testObject );
}

ContainerIterator& HashTable::initIterator() const
{
    return *( (ContainerIterator *)new HashTableIterator( *this ) );
}

HashTableIterator::HashTableIterator( const HashTable& toIterate ) :
                                beingIterated( toIterate ),
                                listIterator(0)
{
    arrayIterator = new BI_IVectorIteratorImp<Object>( toIterate.table );
    restart();
}

HashTableIterator::~HashTableIterator()
{
    delete arrayIterator;
    delete listIterator;
}

Object& HashTableIterator::operator ++ ( int )
{
    Object& res = (listIterator == 0) ? NOOBJECT : listIterator->current();
    scan();
    return res;
}

Object& HashTableIterator::operator ++ ()
{
    scan();
    return (listIterator == 0) ? NOOBJECT : listIterator->current();
}

HashTableIterator::operator int()
{
    return int(*arrayIterator);
}

Object& HashTableIterator::current()
{
    return (listIterator == 0) ? NOOBJECT : listIterator->current();
}

void HashTableIterator::restart()
{
    delete listIterator;

    arrayIterator->restart();
    while( *arrayIterator != 0 && arrayIterator->current() == 0 )
        (*arrayIterator)++;

    if( *arrayIterator != 0 )
        {
        Object *curList = arrayIterator->current();
        listIterator = &(((List *)curList)->initIterator());
        if( listIterator->current() == NOOBJECT )
            scan();
        }
    else
        listIterator = 0;
}

void HashTableIterator::scan()
{
    if( listIterator == 0 )
        return;

    (*listIterator)++;
    while( listIterator != 0 && listIterator->current() == NOOBJECT )
        {
        delete listIterator;

        (*arrayIterator)++;
        while( *arrayIterator != 0 && arrayIterator->current() == 0 )
            (*arrayIterator)++;

        if( arrayIterator->current() != 0 )
            {
            Object *cur = arrayIter

C and C++ Examples ( List Implementations )


// Borland C++ - (C) Copyright 1991 by Borland International

/* LISTDEMO.CPP--Example from Getting Started */

// LISTDEMO.CPP           Demonstrates dynamic objects

// Link with FIGURES.OBJ and GRAPHICS.LIB

#include <conio.h>          // for getch()
#include <alloc.h>          // for coreleft()
#include <stdlib.h>         // for itoa()
#include <string.h>         // for strcpy()
#include <graphics.h>
#include "figures.h"

class Arc : public Circle {
   int StartAngle, EndAngle;
public:
   // constructor
   Arc(int InitX, int InitY, int InitRadius, int InitStartAngle,
       int InitEndAngle);
   // virtual functions
   void Show();
   void Hide();
};

struct Node {     // the list item
   Point *Item;   // can be Point or any class derived from Point
   Node  *Next;   // point to next Node object
};

class List {      // the list of objects pointed to by nodes
   Node *Nodes;   // points to a node
public:
   // constructor
   List();
   // destructor
   ~List();
   // add an item to list
   void Add(Point *NewItem);
   // list the items
   void Report();
};

// definitions for standalone functions

void OutTextLn(char *TheText)
{
   outtext(TheText);
   moveto(0, gety() + 12);   // move to equivalent of next line
}

void MemStatus(char *StatusMessage)
{
   unsigned long MemLeft;  // to match type returned by
  // coreleft()
   char CharString[12];    // temp string to send to outtext()
   outtext(StatusMessage);
   MemLeft = long (coreleft());

   // convert result to string with ltoa then copy into
   // temporary string
   ltoa(MemLeft, CharString, 10);
   OutTextLn(CharString);
}

// member functions for Arc class

Arc::Arc(int InitX, int InitY, int InitRadius, int InitStartAngle,
         int InitEndAngle) : Circle (InitX, InitY,InitRadius)
                              // calls Circle
                              // constructor
{
   StartAngle = InitStartAngle;
   EndAngle = InitEndAngle;
}

void Arc::Show()
{
   Visible = true;
   arc(X, Y, StartAngle, EndAngle, Radius);
}

void Arc::Hide()
{
   unsigned TempColor;
   TempColor = getcolor();
   setcolor(getbkcolor());
   Visible = false;
   arc(X, Y, StartAngle, EndAngle, Radius);
   setcolor(TempColor);
}

// member functions for List class

List::List ()                // constructor
{
   Nodes = NULL;             // initialize Nodes data
}

List::~List()                // destructor
{
   while (Nodes != NULL) {   // until end of list
      Node *N = Nodes;       // get node pointed to
      delete(N->Item);       // delete item's memory
      Nodes = N->Next;       // point to next node
        delete N;            // delete pointer's memory
   };
}

void List::Add(Point *NewItem)
{
   Node *N;              // N is pointer to a node
   N = new Node;         // create a new node
   N->Item = NewItem;    // store pointer to object in node
   N->Next = Nodes;      // next item points to curent list pos
   Nodes = N;            // last item in list now points
                         // to this node
}

void List::Report()
{
   char TempString[12];
   Node *Current = Nodes;
   while (Current != NULL)
   {
      // get X value of item in current node and convert to string
      itoa(Current->Item->GetX(), TempString, 10);
      outtext("X = ");
      OutTextLn(TempString);
      // do the same thing for the Y value
      itoa(Current->Item->GetY(), TempString, 10);
      outtext("Y = ");
      OutTextLn(TempString);
      // point to the next node
      Current = Current->Next;
   };
}

void setlist(void);

// Main program
main()
{
   int graphdriver = DETECT, graphmode;
   initgraph(&graphdriver, &graphmode, "..\\bgi");

   MemStatus("Free memory before list is allocated: ");
   setlist();
   MemStatus("Free memory after List destructor: ");
   getch();
   closegraph();
}

void setlist() {

   // declare a list (calls List constructor)
   List AList;

   // create and add several figures to the list

How to copy data from one file to another file using C program


In this post i am posting a simple c program to copy the data from one file to another file .

#include<stdio.h>
void main()
{
FILE *f1, *f2;
char ch;
clrscr();
f1 = fopen("priya.txt","r");
f2 = fopen("jagan.txt", "w");

while((ch=getc(f1))!=EOF)
putc(ch, f2);

printf("\n\tData has been copied");

fclose(f1);
fclose(f2);

getch();
}

Saturday, November 19, 2011

C and C++ Examples ( Stack using Linked List)


#include<iostream.h>
#include<process.h>
#include<conio.h>
class node
 {
int d;
node *next;
friend class stack;
 };
class stack
 {
node *top;
public:
stack()
{
top=NULL;
}
void push();
int pop();
void print();
void peep();
void change();
int size();
};
void stack::push()
{
int num;
node *n;
cout<<"\nenter a number:";
cin>>num;
n=new node;
n->d=num;
n->next=top;
top=n;
cout<<num<<"is pushed into the stack\n";
}
int stack::pop()
{
if(top==NULL)
{
cout<<"\nstack underflow\n";
return 0;
}
int num=top->d;
node *d=top;
top=top->next;
delete d;
return num;
}
void stack::print()
{
node *a=top;
while(a!=NULL)
{
cout<<"\n"<<a->d;
a=a->next;
}
}
void stack::peep()
{
int pos,i,c=size();
cout<<"\nenter position:";
cin>>pos;
if(pos<1||pos>c)
cout<<"\nwrong position\n";
node *a=top;
for(i=0;i<pos-1;i++)
a=a->next;
cout<<pos<<"position element is"<<a->d;
}
void stack::change()
{
int pos,i,num,c=size();
node *a=top;
cout<<"\n enter the position:";
cin>>pos;
if(pos<1||pos>c)
cout<<"\n wrong position\n";
cout<<"\nenter a number:";
cin>>num;
for(i=0;i<pos-1;i++)
a=a->next;
a->d=num;
cout<<"\nnumber is changed\n";
}
int stack::size()
{
node *a=top;
int i=0;
while(a!=NULL)
{
i++;
a=a->next;
}
return i;
}
void main()
{
stack s;
int op,num;
while(1)
{
cout<<"\nstack elements are:\n";
s.print();
cout<<"\n1.push\n2.pop\n3.peep\n4.change\n5.size\n";
cout<<"\nenter your option\n";
cin>>op;
switch(op)
{
case 1:s.push();
break;
case 2:num=s.pop();
cout<<num<<"is popped element\n";
break;
case 3:s.peep();
break;
case 4:s.change();
break;
case 5:exit(0);
}
getch();
}
}

output  :


stack elements are:

1.push
2.pop
3.peep
4.change
5.size

enter your option
1

enter a number: 1212
1212is pushed into the stack

stack elements are:

1212
1.push
2.pop
3.peep
4.change
5.size

enter your option
3

enter position: 1
1position element is1212
stack elements are:

1212
1.push
2.pop
3.peep
4.change
5.size

enter your option
2
1212is popped element

C and C++ Examples (Stack )


#include<iostream.h>
#include<conio.h>
template<class p>
class stack
{
p s[10];
int i;
p element;
int top;
public:
stack()
{
top=-1;
}
void push()
{
if(top>10)
cout<<"stack is full";
else
{
cout<<"enter the element to push"<<endl;
cin>>element;
s[++top]=element;
cout<<"element\t"<<element<<"\tis pushed"<<endl;
}
}
void pop()
{
if(top<0)
{
cout<<"stack is empty"<<endl;
}
else
{
cout<<"element poped is"<<s[top--]<<endl;
}
}
void display()
{
if(top<0)
{
cout<<"stack is empty"<<endl;
}
else
{
cout<<"the elements are"<<endl;
for(i=0;i<=top;i++)
{
cout<<"\t"<<s[i];
}
}
}
};
void main()
{
stack<int> obj;
stack<float> obj1;
stack<char> obj2;
int ch;
clrscr();
while(1)
{
cout<<"enter\n1.int push\n2.float push\n3.char push"<<endl;
cout<<"\n4.int pop\n5.float pop\n6.char pop"<<endl;
cout<<"\n7.int display\n8.float display\n9.char display\n10.exit"<<endl;
cout<<"\nenter u r choice"<<endl;
cin>>ch;
if(ch==10)
{
break;
}
switch(ch)
{
case 1:obj.push();
getch();
clrscr();
break;
case 2:obj1.push();
getch();
clrscr();
break;
case 3:obj2.push();
getch();
clrscr();
break;
case 4:obj.pop();
getch();
clrscr();
break;
case 5:obj1.pop();
getch();
clrscr();
break;
case 6:obj2.pop();
getch();
clrscr();
break;
case 7:obj.display();
getch();
clrscr();
break;
case 8:obj1.display();
getch();
clrscr();
break;
case 9:obj2.display();
getch();
clrscr();
break;
}
}
}

C and C++ Examples ( Selection Sort)


#include<iostream.h>
void selectionsort(int a[],int n);
void main()
{
int a[10],n,i;
cout<<"ENTER THE NUMBER OF ELEMENT's IN THE LIST :";
cin>>n;
cout<<"ENTER LIST ELEMENT's";
for(i=0;i<n;i++)
cin>>a[i];
selectionsort(a,n);
}

void selectionsort(int a[],int n)
{
int i,j,t,min;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])

 min=j;
}
t=a[min];
a[min]=a[i];
a[i]=t;
}
  cout<<"sorted list is ";
  for(i=0;i<n;i++)
  cout<<a[i];
  return;
  }


C and C++ Examples (Queue using Arrays)


       /* PROGRAM TO IMPLEMENT QUEUE USING ARRAYS */
#include<iostream.h>
#include<process.h>
#include<conio.h>
class queue
{
 int *a,front,rear,n;
public:
queue()
 {
 clrscr();
 front=rear=-1;
 cout<<"\n enter the size of the queue:";
 cin>>n;
 a=new int[n];
 }
 void insertion();
 void deletion();
 void print();
};
void queue::insertion()
{
int num;
if(rear==n-1)
 {
 cout<<"\n queue overflow \n";
 return;
 }
 cout<<"\n enter a number:";
 cin>>num;
 if(front==-1)
 front=rear=0;
 else
 rear++;
 a[rear]=num;
 cout<<num<<"number is inserted into queue \n";
}
void queue::deletion()
{
if(front==-1)
{
 cout<<"\n queue underflow \n";
 return;
}
cout<<"\n deleted element is "<<a[front]<<"\n";
if(front==rear)
 front=rear=-1;
else
 front++;
 cout<<"\n number is deleted \n";
}
void queue::print()
{
if(front==-1)
 cout<<"QUEUE IS EMPTY:";
for(int i=front;i<=rear;i++)
 cout<<"\n"<<a[i]<<"\n";
}
void main()
{
queue q;
int op;
clrscr();
while(1)
 {
cout<<"\n QUEUE ELEMENTS ARE::\n";
q.print();
cout<<"\n 1.insertion\n2.deletion\n3.exit\n";
cout<<"\n enter your option \n";
cin>>op;
switch(op)
{
case 1:q.insertion();
break;
case 2:q.deletion();
break;
case 3:exit(0);
}
getch();
 }
}



ouput :


QUEUE ELEMENTS ARE::
QUEUE IS EMPTY:
0

1.insertion
2.deletion
3.exit

enter your option
1

enter a number:15
15
number is inserted into queue

QUEUE ELEMENTS ARE::

15

1.insertion
2.deletion
3.exit

enter your option
2

deleted element is 15

number is deleted

C and C++ Examples ( Queue operations using Linked List)


        /*program to perform Queue Operations using linked list*/
#include<iostream.h>
#include<process.h>
#include<conio.h>
class node
{
  int data;
  node *link;
  friend class queue;
};
class queue
{
node *front,*rear;
public:
queue()
{
front=rear=NULL;
}
void insertion();
void deletion();
void print();
};
void queue::insertion()
{
int num;
node *n;
cout<<"\n enter a number:";
cin>>num;
n=new node;
n->data=num;
n->link=NULL;
if(front==NULL)
{
front=rear=n;
cout<<"number is inserted";
return;
}
rear->link=n;
rear=n;
cout<<"number is inserted into queue \n";
}
void queue::deletion()
{
node *d;
if(front==NULL)
{
 cout<<"\n underflow \n";
 return;
}
if(front==rear)
 {
front=rear=NULL;
cout<<"\n number is deleted";
return;
 }
 d=front;
front=front->link;
cout<<d->data<<"is deleted \n";
delete d;
}
void queue::print()
{
node *a=front;
 while(a!=NULL)
{
cout<<"\n"<<a->data;
a=a->link;
}
}
void main()
{
queue q;
int op;
clrscr();
while(1)
{
cout<<"\n QUEUE ELEMENTS ARE::\n";
q.print();
cout<<"\n 1.insertion \n 2.deletion  \n 3.Exit      \n";
cout<<"enter your option \n";
cin>>op;
switch(op)
{
case 1:q.insertion();
break;
case 2:q.deletion();
break;
case 3:exit(0);
}
getch();
}
}

Output :

QUEUE ELEMENTS ARE ::

1.insertion
2.deletion
3.exit

enter your option:

1

enter a number : 25
number is inserted

QUEUE ELEMENTS ARE :: 25

1.insertion
2.deletion
3.exit

enter your option
2

number is deleted


C and C++ Examples ( Friend Function )


   /* PROGRAM TO IMPLEMENT FRIEND FUNCTION */
#include<iostream.h>
class distance
{
private:
int feet;
double inches;
public:
distance(void);
~distance(void);
distance(int f,double inhs);
void get_distance(void);
void set_distance(int f,double inhs);
void show_distance(void);
friend distance add_distance(distance d1,distance d2);
};
distance::distance(void)
{

}
distance::~distance(void)
{

}
distance::distance(int f,double inhs)
{
feet=f;
inches=inhs;
}
void distance::get_distance(void)
{
cout<<"enter feet";
cin>>feet;
cout<<"enter inches";
cin>>inches;
}
void distance::set_distance(int f,double inhs)
{
feet=f;
inches=inhs;
}
void distance::show_distance(void)
{
cout<<feet<<" "<<inches<<"\n";
}
distance add_distance(distance d1,distance d2)
{
distance d;
d.feet=0;
d.inches=d1.inches+d2.inches;
if(d.inches>=12.0)
{
d.inches=12.0;
d.feet++;
}
d.feet=d1.feet+d2.feet;
return(d);
}
void main(void)
{
distance d1,d2;
d1.set_distance(10,6.9);
cout<<"get data from the keyboard:\n";
d2.get_distance();
cout<<"\n";
cout<<"distance d1=";
d1.show_distance();
cout<<"distance d2=";
d2.show_distance();
distance d0;
d0=add_distance(d1,d2);
cout<<"distance d0";
d0.show_distance();
}


output :

get data from the keyboard:
enter feet45
enter inches12

distance d1=10 6.9
distance d2=45 12
distance d055 12






















Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Vamshi krishnam raju | Bloggerized by Vamshi krishnam raju - Vamshi krishnam raju | Vamshi krishnam raju