You are on page 1of 3

Section B (2x10= 20)

(Answer any TWO questions)


17. Explain about operator overloading in detail. 
 In C++, we can make operators to work for user defined classes. This means C+
+ has the ability to provide the operators with a special meaning for a data type,
this ability is known as operator overloading.For example, we can overload an
operator ‘+’ in a class like String so that we can concatenate two strings by just
using +.
Other example classes where arithmetic operators may be overloaded are
Complex Number, Fractional Number, Big Integer, etc.
Complex operator + (Complex const &obj)
{
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
 }
17. Write a C++ program to convert infix expression to postfix expression
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define size 50
char stack[size];
inttos=0,ele;
void push(int);
char pop();
char infix[30],output[30];
intprec(char);
int main()
{
inti=0,j=0,length;
char temp;
clrscr();
cout<<"\nEnter an infix expression: ";
cin>>infix;
length=strlen(infix);
for(i=0;i<length;i++)
{
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/'
&&infix[i]!='^' && infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
}
else
{
if(tos==0)
{
push(infix[i]);
}
else
{
if(infix[i]!=')' && infix[i]!='(')
{
if(prec(infix[i]) <= prec(stack[tos-1]) )
{
temp=pop();
output[j++]=temp;
push(infix[i]);
}
else
{
push(infix[i]);
}
}
else
{
if(infix[i]=='(')
{
push(infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{
output[j++]=temp;
temp=pop();}
}
}}
}}
while(tos!=0)
{
output[j++]=pop();
}
cout<<"The Postfix expression is: "<<output;
getch();
return 0;
}
void push(intele)
{
stack[tos]=ele;
tos++;
}
char pop()
{
tos--;
return(stack[tos]);
}
intprec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
}
OUTPUT:
INFIX TO POSTFIX
Enter an infix Expersion: ((a-b)/(d-c)^(f*g))
The postfix Expression is: ab-dc-fg*^/

You might also like