Archive for category C++ Examples

Program to generate a hash table.

#include <iostream>
using namespace std;

struct node {
int key;
node* next;
node() {
next=NULL;
}

};

typedef node* NODE;

int main() {
NODE hashtable[10];
//hashtable with 10 buckets
for(int i=0;i<10;i++) {
//initialize buckets to NULL
hashtable[i]=NULL;
}
int key;
while(1) {
cout<<"Enter key/bucket(only positive) (-1 to stop):";
cin>>key;

if(key==-1)
break;
NODE temp=new node;
temp->key=key;
//hashfunction:using the remainder hash function to find bucket
int bucket=key%10;
NODE head=hashtable[bucket];

temp->next=head;
hashtable[bucket]=temp;
}
while(1) {
cout<<"Enter key to search(-1 to stop):";
cin>>key;
if(key==-1)
break;
int bucket=key%10;
NODE head=hashtable[bucket];
bool found=false;
while(head!=NULL) {
if(head->key==key) {
found=true;
break;
}
head=head->next;
}
if(found)
cout<<"Key found, Bucket:"<<bucket<<endl;
else
cout<<"Not found"<<endl;
}
return 0;
}

,

No Comments

Program to generate a stack and basic operations of stack in C++.

#include<iostream>
#include<cstring>
using namespace std;
class Stack
{
int top;
string arr[3];
public:
Stack()
{
top=0;
cout<<"Stack is instantiated"<<endl;
}
bool isfull()
{
return(top>3);
}
bool isempty()
{
return (top==-1);
}
void push(string str)
{
if(isfull())
{
cout<<"stack is full";
return;
}
else
arr[top]=str;
top++;
}
void pop()
{
top--;
if(isempty())
{
cout<<"cannot be popped";
return;
}
else
cout<<arr[top];
}
};
main()
{
Stack S;
int a,i=0;
string str;
char b='y';
while(b=='y')
{
cout<<"1.Push the names"<<endl<<"2.Pop the names"<<endl;
cin>>a;
if(a==1)
{
cout<<"Enter the name:";
getline(cin,str);
cin>>str;
S.push(str);
}
if(a==2)
{
S.pop();
}
cout<<"continue?(y/n)";
cin>>b;
}
}

, , , ,

No Comments

Program to convert polar coordinates to cartesion coordinates and vice versa and finding distance between two points in C++.

This is working code to convert cartesion coordinates to polar coordinates and vice versa, also find the distance between two points.

#include<iostream>
#include<math.h>
using namespace std;
class Rectangular
{
 float x,y,r,theta,d;
 public:
 void getdata()
 {
 cout<<"enter the cartesian coordinates:";
 cin>>x>>y;
 }
 void recttopolar();
 void distanceofcartesian();
};/*definition of class for cartesian coordinates*/
class Polar
{
 float x,y,r,theta,d;
 public:
 void getdata()
 {
 cout<<"enter the polar coordinates:";
 cin>>r>>theta;
 }
 void polartorect();
 void operator-(Polar);
};/*definition of class for polar coordinates*/
void Rectangular::recttopolar()
{
 Rectangular R1;
 R1.getdata();
 r=sqrt(R1.x*R1.x+R1.y*R1.y);
 if((x>=0&y>=0)||(x>=0&y<=0))
 {
 theta=atan(R1.y/R1.x);
 }
 if(x<0&y>0)
 {
 theta=3.14-atan(y/(-x));
 }
 if(x<0&y<0)
 {
 theta=atan((-y)/(-x))-3.14;
 }
 cout<<endl;
 cout<<"Polar coordinates are:"<<r<<" "<<theta<<endl;
}/*function to convert cartesian coordinates to polar coordinates*/
void Polar::polartorect()
{
 Polar P1;
 P1.getdata();
 x=P1.r*cos(P1.theta);
 y=P1.r*sin(P1.theta);
 cout<<endl;
 cout<<"rectangular coordinates are:"<<x<<" "<<y<<endl;
}/*function to convert polar coordinates to cartesian coordinates*/
void Rectangular::distanceofcartesian()
{
 Rectangular R1,R2;
 R1.getdata();
 R2.getdata();
 d=sqrt((R1.x-R2.x)*(R1.x-R2.x)+(R1.y-R2.y)*(R1.y-R2.y));
cout<<"distance:"<<d<<endl;
}/*function to find distance between cartesian coordinates*/
void Polar::operator-(Polar P2)
{
 d=sqrt(r*r+P2.r*P2.r-2*r*P2.r*cos(theta-P2.theta));
 cout<<"distance:"<<d<<endl;
}/*function to find distance between polar coordinates using operator overloading&*/
main()
{
 int n;
 //Rectangular R1,R2;
 //Polar P1,P2;
 cout<<"what is the operation to be performed"<<endl;
 cout<<"1.rect to polar"<<endl<<"2.polar to rect"<<endl<<"3.distance of cartesian"<<endl<<"4.distance of polar"<<endl;
 cin>>n;
 if(n==2)
 {
 Polar P1;
 P1.polartorect();
 }
 if(n==1)
 {
 Rectangular R1;
 R1.recttopolar();
 }
 if(n==3)
 {
 Rectangular R1;
 R1.distanceofcartesian();
 }
 if(n==4)
 {
 Polar P1,P2;
 P1.getdata();
 P2.getdata();
 P1-P2;
 }
}

, , , ,

No Comments

program for pascal traingle in C++.

#include<iostream.h>
class PascalTriangle
{
int i,j,k,r,m,n,p;
int temp,x;
public:
void getinput();
void getpascaltriangle();
int factorial(int);
};
void PascalTriangle::getinput()
{
cout<<"enter no of lines";
cin>>n;
if(n<=0)
cout<<"not possible";
}
void PascalTriangle::getpascaltriangle()
{
for(i=n;i>=1;i--)
{
for(j=1;j<=(i-1);j++)
{
cout<<" ";
}
r=n-i;
for(k=0;k<=r;k++)
{
x=factorial(r)/(factorial(k)*factorial(r-k));
cout<<x;
if(r==k)
cout<<endl;
else
cout<<" ";
}
}
}
int PascalTriangle::factorial(int m)
{
if(m!=0)
{
return m* factorial(m-1);
}
if(m==0)
return 1;
}
main()
{
PascalTriangle P;
P.getinput();
P.getpascaltriangle();
}

, ,

No Comments

Program to implement time delay, pause and measure timings for a particular event in C++.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<iostream.h>

void sleep( clock_t  );

void main( void )
{
long    i = 600000L;
clock_t start, finish;
double  duration;
printf("%d\n",(int)CLOCKS_PER_SEC);

/* Delay for a specified time. */
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );

/* Measure the duration of an event. */
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
cout<<endl;
finish = clock();
duration = (float)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.5f seconds\n", duration );
}

/* Pauses for a specified number of milliseconds. */
void sleep( clock_t waitme )
{
clock_t goal;
goal = waitme + clock();
while( goal > clock() )
;
}

, , ,

13 Comments

Program for bubble sort in C++.

#include<iostream>
using namespace std;
#include<stdio.h>
#include<time.h>
#include<stdlib.h>

void bubblesort(long int*);

void main()
{
long int i=0,c;
long int a[30000];
FILE *fp;
fp=fopen("input3.txt","r");
while(fscanf(fp,"%ld",&c)!=EOF)
{
a[i]=c;
//    cout<<a[i];
i++;
}
fclose(fp);

bubblesort(a);

fp=fopen("output3.txt","w");
for(i=0;i<30000;i++)
{
fprintf(fp,"%ld ",a[i]);
}
fclose(fp);
}

void bubblesort(long int*h)
{
clock_t start, finish;
double  duration;

long int temp;
start = clock();

for(int i=30000;i>1;i--)
{
for(int j=0;j<i-1;j++)
{
if(h[j]>h[j+1])
{
temp=h[j];
h[j]=h[j+1];
h[j+1]=temp;
}
}
}
finish = clock();
duration = (float)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.3f seconds\n", duration );

}

,

7 Comments

GENERATING AN AVL TREE OF 10000 RANDOM NUMBERS AND REPORT ITS DEPTH IN C++.

#include <iostream.h>        //INCLUDING REQUIRED LIBRARIES
#include <stdio.h>
#include<stdlib.h>

struct node                    //DECLARATION OF THE NODES OF THE AVL TREE
{
int data;                    //TO STORE THE NUMBER
int leftdepth,rightdepth;    //TO KEEP TRACK OF THE LEFT AND RIGHT DEPTH
struct node *father;
struct node *left,*right;    //POINTER TO THE LEFT AND RIGHT CHILD OF THAT NODE
};
class tree                        //DECLARING THE CLASS TREE
{
private :
struct node * root;
public :
tree()                    //ZERO-ARGUMENT CONSTRUCTOR
{
root=NULL;                //MAKING ROOT NULL
}
void input ()
{
int  temp;
FILE * ifp=fopen("int.txt","r");        //OPENING THE FILE CONTAINING 10000 RANDOM INTEGERS
while(fscanf(ifp,"%d",&temp)!=EOF)        //TILL THE END OF FILE
{
add (temp);                        //CALLING FUNCTION TO ADD THE NUMBER TO THE AVL TREE
}
}
struct node * create (int y)            //FUNCTION TO CREATE A NODE CONTAINING THE NUMBER
{
struct node * temp=new node ;
temp->data=y;                        //PUTTING THE DATA IN THE NEW NODE
temp->father=NULL;                    //MAKING FATHER NULL
temp->left=temp->right=NULL;        //MAKING RIGHT AND LEFT CHILD NULL
temp->leftdepth=temp->rightdepth=0;    //MAKING LEFT AND RIGHT depth EQUAL TO ZERO
return temp;                        //RETURNING THE NODE
}
void add (int a)                        //FUNCTION TO PUT THE NO IN THE NODE AND
//THEN ATTACH IT TO THE AVL TREE AT THE PROPER PLACE
{
struct node * curr= search(a,root),*x,*y,*z;
//CURR IS A POINTER TO THE NODE WHERE THE NEW NODE WILL BE ATTACHED
x=y=z=NULL;
if (curr==NULL)  root=create (a);    //IF NO ELEMENT IN THE TREE
else if (curr->data!=a)
//CREATING A NODE IF THE NO IS NOT EQUAL TO THE NO PRESENT IN THE CURRENT NODE AND ATTACHING IT TO THE BINARY TREE AT APPROPRIATE PLACE
{
x=create(a);
if (curr->data>a) curr->left=x;
else    curr->right= x;
x->father=curr;                //MAKING CURRENT NODE TO BE FATHER OF NEW NODE
while(x!=NULL)
{
z=y;
y=x;
x=x->father;
if (x!=NULL )
{
updatedepth(x);
if (check(x))        //***CALLING FUNCTION TO SATISFY THE AVL BALANCING CONDITION
rearrange(x,y,z);
}
}
}
else cout<<a<<"\t";
}
int maxdepth(struct node * p)        //RETURNING THE MAXIMUM DEPTH AT EACH NODE
{
if (p==NULL)
return -1;
if (p->leftdepth > p->rightdepth)
return p->leftdepth;
return p->rightdepth;
}
int mod (int a,int b)            //TO ADJUDGE WHETHER A SINGLE OR DOUBLE ROTATION IS REQUIRED
{
if(a>b)
return a-b;
else
return b-a;
}
int check(node * a)            //***FUNCTION TO CHECK IF THE AVL BALANCING CONDITION IS SATISFIED
{
if(mod (a->leftdepth,a->rightdepth)<2)
return 0;
return 1;
}
void rearrange(struct node * a ,struct node * b,struct node * c)
//FUNCTION TO REARRANGE THE NODES TO MAINTAIN THE AVL BALANCE
{
if( ((a->data - b->data) * (b->data -c->data)) > 0 )
singlerotation (a,b);
else
doublerotation(a,b,c);
}
//FUNCTION TO GIVE NODES SINGLE ROTATION SO THAT THE BALANCING CONDITION OF THE AVL TREE IS SATISFIED
void singlerotation (struct node * a,struct node * b)
{                    //FUNCTION TO DO SINGLEROTATION AT THE NODES
if (a->data < b->data)
{
a->right=b->left;
if (b->left!=NULL) b->left->father=a;
b->left=a;
}
else
{
a->left=b->right;
if (b->right!=NULL)b->right->father=a;
b->right=a;
}
if ((b->father=a->father)!=NULL)
{
if( a->father->right==a)    a->father->right=b;
else                        a->father->left=b;
}
else root=b;
a->father=b;
updatedepth (a);
updatedepth (b);
}
//FUNCTION TO GIVE NODES DOUBLE ROTATION SO THAT THE BALANCING CONDITION OF THE AVL TREE IS SATISFIED
void doublerotation(struct node * a,struct node * b,struct node * c)
{        //FUNCTION TO DOUBLE ROTATION OF THE NODES
singlerotation(b,c);
singlerotation(a,c);
updatedepth(a);
updatedepth(b);
updatedepth(c);
}
void updatedepth(struct node * p)                //UPDATING THE DEPTH OF EACH NODE WHEN ANOTHER NODE IS ADDED TO IT
{
p->leftdepth=maxdepth(p->left)+1;
p->rightdepth=maxdepth(p->right)+1;
}
struct node * search (int x,struct node * r)    //SEARCHING THE TREE FOR THE APPROPRIATE PLACE TO ATTACH
{                                                //THE INCOMING NODE CONTAINING A NEW NUMBER
while (1)
{
if (r==NULL)                            //IF EMPTY TREE
return NULL;
else
{
if (x==r->data)                        //IF NEW NO. IS SAME AS NUMBER IN THE ROOT
break;
else if(x>r->data)                    //IF NEW NO. IS GREATER THAN THE NO. IN THE CURRENT NODE
{
if(r->right==NULL) break ;
else return search (x,r->right);//RECURSIVE CALLS TO FUNCTION SEARCH
}
else                                //IF NEW NO IS LESS THAT THE THE NO. IN THE CURRENT NODE
{
if (r->left==NULL)      break;
else return search(x,r->left);    //RECURSIVE CALLS TO FUNCTION SEARCH
}
}
}
return r;                //RETURNING THE POINTER TO THE REQUIRED NODE WHERE THE NEW NODE IS TO BE ATTACHED
}
void output()        //FUNCTION TO DISPLAY THE DEPTH
{
cout<<"\n\t**********************************************************";
cout<<"\n\t\tDEPTH OF AVL TREE FORMED IS\t "<<maxdepth(root)<<endl;
}
};
void  main ()                    //MAIN FUNCTION
{
tree t;                        //CREATING AN OBJECT OF TYPE TREE
int i;
FILE *ifp;
ifp=fopen("int.txt","w");    //OPENING FILE TO WRITE 10000 INTEGERS
srand(17);                    //SETS THE RANDOM NUMBER SEED FOR THE RAND FUNCTION

for(i=0;i<10000;i++)        //LOOP TO GENERATE 10000 INTEGERS  AND WRITE INTO THE TEXT FILE
{
fprintf(ifp,"%d\n",rand());        //WRITING RANDOM NUMBERS TO THE FILE
};
cout<<"\t***THE FOLLOWING NUMBERS ARE REPEATED IN THE AVL TREE***\n\n";
t.input();                    //CALLING FUNCTION TO READ RANDON NOS.,GENERATE AVL TREE AND KEEP TRACK OF ITS DEPTH
t.output();                    //CALLING FUNCTION TO DISPLAY THE DEPTH OF THE AVL TREE
}//END OF PROGRAM

, , ,

No Comments

Program for binary search tree in C++.

#include<iostream.h>            //INCLUDING LIBRARIES
#include<fstream.h>

struct node                        //DECLARING NODE DATA STRUCTURE
{
int data;
node *left, *right;
}*root, *cur ,*temp;

void pretrav (node *);            //FUNCTION PROTOTYPE FOR PRETRAVERSAL OF BINARY TREE
void intrav (node *);            //FUNCTION PROTOTYPE FOR INORDER TRAVERSAL OF BINARY TREE
void posttrav (node *);            //FUNCTION PROTOTYPE FOR POSTTRAVERSAL OF BINARY TREE

void main()                        //START OF MAIN
{
cout<<"\t\t\t  BINARY SEARCH TREE\n\n";
cout<<"\n\nDuplicates in the tree : ";
char ch,sign;
int num,count=0,countdup=0;;
ifstream fin;
fin.open("integer.txt");    //OPENING TEXT FILE CONTAINING INTEGERS AND STORING THE RETURNED PTR IN FIN

while(fin)                    //EXECUTE THE LOOP TILL THE END OF FILE
{

fin.get(ch);            //READ A CHARACTER FROM THE FILE

if (ch==' ')            //IF SPACE CONTINUE
continue;

if (ch=='+'||ch=='-')    //STORING THE SIGN OF NUMBER
sign=ch;

if (ch>='0'&&ch<='9')    //IF DIGIT ENCOUNTERED
{
fin.seekg(-1,ios::cur);
fin>>num;                //READING NUMBER IF DIGIT ENCOUNTERED
count++;                //INCREMENTING THE COUNTER
if (sign=='-')            //MAKING THE NUMBER NEGATIVE AND STORING IN NUM
num=0-num;
sign='+';                //MAKING SIGH POSITIVE ...DEFAULT
temp=new node;            //CREATING NEW NODE
temp->data=num;            //STORING THE NUM IN NEW NODE
temp->left=temp->right=NULL;        //MAKING LEFT & RIGHT PTRS OF TEMP NULL

cur=root;                //POINTING CUR PTR TO THE ROOT
if (count==1)            //IF ITS FIRST NODE MAKE IT ROOT
root=temp;
else
{
while(1)
{
if (cur->data<temp->data)
{
if (cur->right!=NULL)
cur=cur->right;        //MOVING CUR POINTER
else
{
cur->right=temp;
break;                //EXIT OUT OF WHILE LOOP
}
}

if (cur->data>temp->data)
{
if (cur->left!=NULL)
cur=cur->left;        //MOVING CUR POINTER
else
{
cur->left=temp;
break;                //EXIT OUT OF WHILE LOOP
}
}

if (cur->data==temp->data)
{
cout<<num<<"  ";        //PRINTING DUPLICATES
countdup++;
break;
}

}
}
}
}
if (countdup==0)
cout<<" None";

cout<<"\n\nPreorder Traversal of the Tree : ";
pretrav(root);                                    //CALLING FUNCTION FOR PREORDER TRAVERSAL OF TREE PASSING ROOT
cout<<endl<<endl;
cout<<"Inorder Traversal  of the Tree : ";
intrav (root);                                    //CALLING FUNCTION FOR INORDER TRAVERSAL OF TREE PASSING ROOT
cout<<endl<<endl;
cout<<"Postorder Traversal of the Tree: ";
posttrav(root);                                    //CALLING FUNCTION FOR POSTORDER TRAVERSAL OF TREE PASSING ROOT
cout<<endl<<endl;

}

void pretrav (node * point)                //DECLARING FUNCTION FOR PRETRAVERSAL OF THE TREE
{
cout<<" "<<point->data<<" ";
if (point->left!=NULL)
pretrav (point->left);

if (point->right!=NULL)
pretrav (point->right);
}

void intrav (node * point)                //DECLARING FUNCTION FOR INORDER TRAVERSAL OF THE TREE
{
if (point->left!=NULL)
intrav (point->left);
cout<<" " <<point->data<<" ";
if (point->right!=NULL)
intrav (point->right);

}

void posttrav (node *point)                //DECLARING FUNCTION FOR POSTORDER TRAVERSAL OF THE TREE
{
if (point->left!=NULL)
intrav (point->left);
if (point->right!=NULL)
intrav (point->right);
cout<<" " <<point->data<<" ";
}
       //END OF PROGRAM//

,

1 Comment

Program to add two polynomials in C++.

#include<stdio.h>                //INCLUDING DIFFERENT LIBRARIES
#include<stdlib.h>
#include<iostream.h>

//DECLARING FUNCTION PROTOTYPES
void convertpoly();
int check_int(char ch);            //CHECKS IF THE VALUES TAKEN IN IS AN INTEGER
int check_char(char ch);        //CHECKS IF THE VALUE TAKEN IN IS A CHARACTER
void display();                    //DISPLAYS THE RESULTS ON THE SCREEN
void a1();                        //POINTS P AND Q TO THE  FIRST NODE
void a2();                        //CHECKS FOR EQUALITY OF POWERS OF DIFFERENT TERMS OF P AND Q
void a3();                        //DOES TERM ADDITION AND SUBTRACTION AND RESULT INSERTION
void a4();                        //DELETES A RESULT IF ITS COEFFICIENT IS ZERO
void a5();                        //INSERTS UNOPERATED TERM OF P IN Q
int priority(struct node *);    //CHECKS THE ORDER OF THE TERMS OF P AND Q

struct node                        //DECLARING THE STRUCTURE FOR STORING THE TERMS OF THE POLYNOMIAL
{
float coeff;
char sign;
int A,B,C;
struct node *next;
}*pn,*p,*qn,*q,*q1,*q2;

void main()                            //MAIN FUNCTION
{
cout<<"\t\t******** WELCOME TO THE POLYNOMIAL ADDER ********\n"<<endl;
convertpoly();                    //CALLING FUNCTION TO CONVERT THE POLYNOMIALS TO THE NODAL FORM
p=p->next;                        //POINTING TO THE LAST TERM OF P
q=q->next;                      //POINTING TO THE LAST TERM OF Q
a1();
a2();
display();
}//END OF MAIN

int check_int(char ch)                //FUNCTION TO CHECK IF OBTD CHAR IS AN INTEGER/DECIMAL POINT
{
if((ch>47&&ch<58)||(ch==46))
return 1;
else
return 0;
}

int check_char(char ch)                //FUNCTION TO CHECK IF OBTD CHAR IS A VARIABLE
{
if((ch=='x'||ch=='X')||(ch=='y'||ch=='Y')||(ch=='z'||ch=='Z'))
return 1;
else
return 0;
}

void convertpoly()                    //READING POLYNOMIAL TERMS FROM THE TEXT FILE AND CONVERTING THEM INTO NODAL
//FORM TO FORM CIRCULAR LINKED LISTS
{
FILE *fp;
char ch;
p=new struct node;                    //CREATING A DUMMY NODE AT THE BEGINNING OF A POLYNOMIAL
p->sign='-';
p->A=-1;
p->B=-1;
p->C=-1;
p->next=p;
fp=fopen("poly.txt","r");            //OPENING FILE IN READ ONLY MODE
ch=fgetc(fp);                        //READING CHAR FROM FILE
char ch1='+';                        //INITIALISING CHAR TO +
while(ch!='$')                        //READING TILL END OF POLY
{
if(ch=='-'||ch=='+')
{
ch1=ch;
ch=getc(fp);
}

float num;

if(check_char(ch))            //IF COEFFICIENT IS 1
num=1;
else
{
num=0.0;
while(check_int(ch))        //IF COEFFICIENT IS OTHER THAN 1
{
num=num*10+(ch-'0');
ch=fgetc(fp);
}

}

if(ch1=='-')
num=num*(-1);
int a=0,b=0,c=0;
if(ch=='x'||ch=='X')
a=fgetc(fp)-'0';
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch=fgetc(fp);
if(ch=='-'||ch=='+'||ch=='$')            //IF ONLY ONE VARIABLE PRESENT(OUT OF X,Y AND Z)
{
ch1=ch;
pn=new struct node;                    //CREATING A NEW NODE FOR STORING THE CURRENT TERM
pn->coeff=num;
pn->sign='+';                            //WRITING TO THE NODE
pn->A=a;
pn->B=b;
pn->C=c;
pn->next=p->next;                        //CREATING CIRCULAR LINKED LIST
p->next=pn;
p=pn;
continue;
}
else
{
if(ch=='x'||ch=='X')
a=fgetc(fp)-'0';
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch=fgetc(fp);
if(ch=='-'||ch=='+'||ch=='$')            //IF END OF TERM OR END OF POLYNOMIAL
{
ch1=ch;
pn=new struct node;                //PUTTING THE PRESENT TERM IN A NEW NODE
pn->coeff=num;
pn->sign='+';
pn->A=a;
pn->B=b;
pn->C=c;
pn->next=p->next;                //INSERTING THE NEW NODE IN THE LINKED LIST
p->next=pn;
p=pn;
continue;
}
else
{
if(ch=='x'||ch=='X')
a=fgetc(fp)-'0';
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch1=ch=fgetc(fp);
}
}

pn=new struct node;                    //END OF POLYNOMIAL
pn->coeff=num;                        //WRITING THE TERM TO A NEW NODE
pn->sign='+';
pn->A=a;
pn->B=b;
pn->C=c;
pn->next=p->next;
p->next=pn;
p=pn;
}

q=new struct node;                    //START OF THE SECOND POLYNOMIAL Q
q->sign='-';                        //PUTTING A DUMMY NODE AT THE BEGINNING OF THE POLYNOMIAL
q->A=-1;
q->C=-1;
q->B=-1;
q->next=q;
ch=fgetc(fp);
ch1='+';
while(ch!='$')                        //READING TILL THE END OF THE POLYNOMIAL
{
if(ch=='-'||ch=='+')
{
ch1=ch;
ch=getc(fp);
}
float num;
if(check_char(ch))            //IF COEFFICIENT IS 1
num=1;
else
{
num=0.0;
while(check_int(ch))        //CONVERTING THE COEFFICIENT INTO NUM DIGIT BY DIGIT
{
num=num*10+(ch-'0');
ch=fgetc(fp);
}

}
if(ch1=='-')                //IF COEFF IS NEGATIVE
num*=-1;
int a=0,b=0,c=0;
if(ch=='x'||ch=='X')        //READING THE POWERS OF VARIABLES
a=fgetc(fp)-'0';        //STORING THE POWERS IN TEMP VARIABLES
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch=fgetc(fp);
if(ch=='-'||ch=='+'||ch=='$')        //IF END OF TERM OR END OF POLYNOMIAL
{
ch1=ch;
qn=new struct node;
qn->coeff=num;
qn->sign='+';
qn->A=a;
qn->B=b;
qn->C=c;
qn->next=q->next;
q->next=qn;
q=qn;
continue;                    //GOING TO THE BEGINNING OF THE LOOP
}
else
{
if(ch=='x'||ch=='X')        //READING POWER OF NEXT VARIABLE
a=fgetc(fp)-'0';
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch=fgetc(fp);
if(ch=='-'||ch=='+'||ch=='$')        //WRTING IN THE NODE IF END OF TERM OR POLYNOMIAL
{
ch1=ch;
qn=new struct node;
qn->coeff=num;
qn->sign='+';
qn->A=a;
qn->B=b;
qn->C=c;
qn->next=q->next;
q->next=qn;
q=qn;
continue;
}
else
{if(ch=='x'||ch=='X')
a=fgetc(fp)-'0';
if(ch=='y'||ch=='Y')
b=fgetc(fp)-'0';
if(ch=='z'||ch=='Z')
c=fgetc(fp)-'0';
ch1=ch=fgetc(fp);
}
}

qn=new struct node;
qn->coeff=num;
qn->sign='+';
qn->A=a;
qn->B=b;
qn->C=c;
qn->next=q->next;
q->next=qn;
q=qn;
}
fclose(fp);
}

int priority(struct node *p)
{
int a,b,c;
a=p->A;
b=p->B;
c=p->C;
return (100*a+10*b+c);
}

void a1()
{
p=p->next;                        //POINTING TO THE FIRST NODE
q1=q;                            //Q1 POINTING TO THE LAST NODE
q=q->next;
}

void a2()
{
while(priority(p)<priority(q))
{
q1=q;
q=q->next;
}
if(priority(p)==priority(q))        //IN CASE OF IDENTICAL POWERS
a3();
else
a5();
}

void a3()
{
if(priority(p)<0)
return;
else
q->coeff+=p->coeff;                //ADDING THE COEFFICIENTS FOR SAME POWERS
if(q->coeff==0)                        //IF COEFF OF RESULT IS ZERO
a4();
else                                //RESULT INSERTION IN Q
{
q1=q;
p=p->next;
q=q->next;
a2();
}
}

void a4()                                //DELETING THE NODE WHICH HAS COEFF ZERO
{
q2=q;
q=q->next;
q1->next=q;
delete(q2);
p=p->next;
a2();
}

void a5()
{
q2=new struct node;
q2->coeff=p->coeff;                    //INSERTING UNOPERATED TERM OF P IN Q
q2->A=p->A;
q2->B=p->B;
q2->C=p->C;
q2->sign=p->sign;
q2->next=q;
q1->next=q2;
q1=q2;ADDING TWO POLYNOMIALS
p=p->next;
a2();
}

void display()                                //FUNCTION TO DISPLAY THE RESULT.
{
q=q->next;

cout<<"REQUIRED SUM \n\nP + Q =";
while(!(q->sign=='-'))
{
if (q->coeff>0)
cout<<" + ";
cout<<q->coeff;
if(!(q->A==0))
cout<<"X"<<q->A;
if(!(q->B==0))
cout<<"Y"<<q->B;
if(!(q->C==0))
cout<<"Z"<<q->C;
q=q->next;
}
cout<<endl<<endl;
}//END OF PROGRAM

, , ,

No Comments

Program for FIBONACCI SERIES in C++.

#include<iostream.h>        //Including header files

int fibnac(int n);            //function prototype for fibnac series

void main()
{
int n,i;
char ch;

do
{
//Taking the no. of terms to be found out

cout<<"How many terms of Fibonacci Series do you wanna calculate\n";
cin>>n;

for(i=1;i<=n;i++)        //Calculating the terms one-by-one and writing to the VDU
{
int p=fibnac(i);
cout<<p<<"   ";
}

cout<<endl;
cout<<"Do you wanna continue?(Y/N)\t";
cin>>ch;
cout<<endl;
}while(ch=='y'||ch=='Y');

}

int fibnac(int p)            //Function to calculate a particular fibonacci term
{
if (p==1)  return(1);
if (p==2)  return(2);
if(p>2)    return(fibnac(p-1)+fibnac(p-2));
}

,

No Comments