C++ Program for String Calculator [DEVCPP/GCC]

PROGRAM

// C++ Program for String Calculator

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

class Program
{
private:

    string expression;
    int indexOfPreviousOperator;
    int indexOfNextOperator;

public:

Program(string ex)
    {
        expression = ex;
    }

    void Evaluate()
    {
        int result = 0;

        if ((expression.find('+') == string::npos && expression.find('-') == string::npos && expression.find('*') == string::npos && expression.find('/') == string::npos))
{
                cout<<stoi(expression);
        }
     
        for (int i = 0; i < expression.size(); i++)
{
            if (expression[i] == '/')
{
                result = getFirstOperand(i) / getSecondOperand(i);
                expression.erase(indexOfPreviousOperator, indexOfNextOperator - indexOfPreviousOperator);
                expression.insert(indexOfPreviousOperator, to_string(result));
                Evaluate();
            }
            else if (expression[i] == '*')
{
                result = getFirstOperand(i) * getSecondOperand(i);
                expression.erase(indexOfPreviousOperator, indexOfNextOperator - indexOfPreviousOperator);
                expression.insert(indexOfPreviousOperator, to_string(result));
                Evaluate();
            }
            else if (expression[i] == '+' && expression.find('/') == string::npos && expression.find('*') == string::npos)
{
                result = getFirstOperand(i) + getSecondOperand(i);
                expression.erase(indexOfPreviousOperator, (indexOfNextOperator - indexOfPreviousOperator));
expression.insert(indexOfPreviousOperator, to_string(result));
                Evaluate();
            }
            else if (expression[i] == '-' && expression.find('/') == string::npos && expression.find('*') == string::npos)
{
                result = getFirstOperand(i) - getSecondOperand(i);
                expression.erase(indexOfPreviousOperator, indexOfNextOperator - indexOfPreviousOperator);
                expression.insert(indexOfPreviousOperator, to_string(result));
                Evaluate();
            }
        }
    }

    int getFirstOperand(int index)
    {
        string operand = "";
        indexOfPreviousOperator = 0;
     
        for (int i = (index - 1); i >= 0; i--)
{
            if (!isdigit(expression[i]))
{
                indexOfPreviousOperator = i;
                break;
            }
        }
        operand = expression.substr(indexOfPreviousOperator, (index - indexOfPreviousOperator));
        return stoi(operand);
    }

    int getSecondOperand(int index)
    {
        string operand = "";
        indexOfNextOperator = expression.size();
     
        for (int i = (index + 1); i < expression.size(); i++)
{
            if (!isdigit(expression[i]))
            {
                indexOfNextOperator = i;
                break;
            }
        }
        operand = expression.substr((index + 1), (indexOfNextOperator - index - 1));
        return stoi(operand);
    }
};

int main()
{
string inputExpression;

cout<<"ENTER EXPRESSION TO BE EVALUATED: ";
      cin>>inputExpression;
 
      Program obj(inputExpression);
obj.Evaluate();

      return 0;
}

OUTPUT



C++ Program to check given number is Pernicious or not [DEVCPP/GCC]

PERNICIOUS NUMBER

pernicious number is a positive integer which has prime number of ones in its binary representation.

PROGRAM

// C++ Program to check given number is Pernicious or not

#include <iostream>
#include <bitset>
#include <cassert>

using namespace std;

bool isPrime(int num)
{
    if(num == 1)
        return false;
   
    for(int j=2 ; j<=(num/2) ; j++)
    {
        if(num % j == 0)
            return false;
    }
   
    return true;
}

int main()
{
    long num, count = 0;
   
    cout << "ENTER A NUMBER : ";
    cin>>num;
 
    assert(num > 0);
 
    string binary = bitset<8>(num).to_string();
   
    for(int i=0 ; i < binary.length(); i++)
    {
        if(binary[i] == '1')
            count++;
    }
   
    if(isPrime(count))
        cout<<endl<<num<<" IS A PERNICIOUS NUMBER";
    else
        cout<<endl<<num<<" IS NOT A PERNICIOUS NUMBER";
 
   return 0;
}

OUTPUT


C++ Program to demonstrate overloading of pre-increment operator [DEVCPP/GCC]

PROGRAM

//Program to demonstrate overloading of pre-increment operator

# include <iostream>

using namespace std;

class complex
{
int real,imag;

     public:

     complex()
{
real=0;imag=0;
}

     complex(int x,int y)
{
real=x;imag=y;
}

void show()
{
cout<<"Complex number is:"<<real<<"+"<<imag<<"i";
}

      complex operator++()      //operator overloading code
{                                    
complex temp;
temp.real= ++real;      
temp.imag= ++imag;
return temp;
}
};

int main()
{
complex c1(1,2),c3;
c3=++c1;     //c1.operator++()
c3.show();
return 0;
}

OUTPUT


C++ Program to demonstrate binary operator overloading [DEVCPP/GCC]

We have already discussed about Operator Overloading in C++ in our previous post: http://techcpp.blogspot.com/2017/07/operator-overloading.html. Here is a simple program on it.

PROGRAM

//Program to demonstrate operator (Binary +) overloading 

# include <iostream>
using namespace std;

class complex
{
int real,imag;

public:

complex()
{
real=0;
          imag=0;
}
complex( int x,int y )
{
real=x;
          imag=y;
}

    complex operator + (complex c)  
{                                                   
complex temp;
temp.real= real+c.real;    
temp.imag= imag+c.imag;
return temp;
}

void show()
{
cout<<"Complex number is:"<<real<<"+"<<imag<<"i";
}
};

int main()
{
complex c1(1,2),c2(2,3),c3;
c3=c1+c2;                                          //c1.operator+(c2)
c3.show();
return 0;
}

OUTPUT


C++ Functions

FUNCTIONS
Functions allow to structure programs in segments of code to perform individual tasks. Functions are used to provide modularity to a program. There are two types of functions in programming Languages i.e. Standard Library Functions and User Defined Functions.
Standard Library Functions
These are built-in functions that are defined in the libraries of programming language. These are used to perform basic operations like input(scanf() ,gets()), output(printf(),puts()), mathematical operations(sqrt()), string related operations etc.
These functions are limited and thus can not be used to perform user specific tasks.
User Defined Functions
As the name implies, these are block of code defined by user as per his/her requirements. These are basically modules which facilitate programming. For instance, if you wish to make a program for mini calculator, you can have various user defined functions as add(), subtract(), multiply(), divide() etc. and call those any number of times you want.

PARTS OF A FUNCTION

The general syntax of a function in C++ is

return_type function_name (Argument_List)
{
        //Body of function

FUNCTION DECLARATION/PROTOTYPE

In C++, identifiers can only be used in expressions if they have been declared before. Thus, functions cannot be called before they are declared. If a user wants to call the function before the body of function is defined, the user needs to declare the prototype of function containing necessary details of function.

Declaring a function is important as compiler does not know about the user defined function in advance. A Function declaration does not contain body of function. The general syntax of Function Declaration is

return_type function_name (Argument_List);

FUNCTION CALL

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.


C++ Operator Overloading

OPERATOR OVERLOADING

When an operator is overloaded with multiple jobs it is known as Operator Overloading. It is one of the methods to implement compile time polymorphism.

Operators are overloaded so that they can perform special operations relative to the classes. When an operator is overloaded, none of its original meaning is lost, instead, the types of object it can be applied to is expanded. By overloading operators, we can use objects of classes in expressions in the same way as we use C++ built in data types.

RULES

Any symbol can be used as a function name.
  • If it is a valid operator in C language.
  • If it is preceded by 'operator' keyword.

Operators that can't be overloaded are 'sizeof' and '?:

TYPES

There are two types of Operator Overloading.
  • Unary Operator Overloading.
  • Binary Operator Overloading.

WHY OPERATOR OVERLOADING
  •  It makes the code readable.
  •  Extention of language to include user defined types i.e classes.
  • Makes operator sensitive to context.
  • Generalization of function overloading.

SYNTAX




C++ Program to illustrate classes and objects

We have already discussed the concept of classes and objects: https://techcpp.blogspot.in/2017/07/c-classes-and-objects.html.

Lets understand a simple program implementing that concept. The program below contains a class Box which can be used to create multiple boxes. The properties of Box are its Length, Width and Height. The member functions used are setDimensions() used to set length, width and height of the box and getVolume() used to obtain volume of the box. 

Two objects of this class is created in the main function and respective volumes are obtained by setting their dimensions.

PROGRAM

//Program to illustrate Object and classes

#include <iostream>

using namespace std;

class Box
{
        // Data Members

        float length;
        float width;
        float height;

        // Member Functions

        public:

        void setDimensions(float l, float w, float h)
        {
                length = l;
                width = w;
                height = h;
        }

        float getVolume()
        {
                return (length * width * height);
        }

};

int main()
{
        Box b1, b2;

        b1.setDimensions(10,20,30);
        cout<<"\nVOLUME OF BOX 1: "<<b1.getVolume();

        b2.setDimensions(5,25,15);
        cout<<"\nVOLUME OF BOX 2: "<<b2.getVolume();

        return 0;
}

OUTPUT

C++ Program to illustrate classes and objects


C++ Classes and Objects

C++ supports object oriented programming. Object-oriented programming is based on the concept of classes and objects. The use of classes and objects makes it easier to build and design applications and shows close resemblance to the real world.

WHAT IS CLASS?
  • It is a user defined data type which serves as a blueprint for an object. 
  • It is a logical entity i.e. no storage is assigned when we define a class.
  • A single class can be used to create multiple objects.
  • A class describes the contents of the objects that belong to it.

WHAT IS OBJECT?
  • An object is an instance of a class.
  • An object is the actual component of program i.e. storage is assigned when we create an object.
  • It is an entity having some characteristics and behavior.
  • An object’s properties are what it knows and its methods are what it can do. 
  • Objects are the fundamental building blocks of applications from an object-oriented perspective.

EXAMPLE

The concept of classes and objects can be understood by the following example:

Human Beings have certain properties and behavior. Each person differs from the other on the basis of one or more properties like name, age, gender, height, weight etc. Thus, we all share certain properties and are distinguished based on them.

Let us define a class named HumanBeing

class HumanBeing
{
          string name;
          int age;
          char gender;
          float height;
          float weight;
};

All Human Beings share common behavior such as breathing, eating, drinking etc. Though Human Beings can be distinguished by their set of properties; but all of them breathe, drink and eat. Thus, all the objects of the same class have the same behavior.

Lets redefine our class adding some behavior,

class HumanBeing
{
          //Properties or Data Members

          string name;
          int age;
          char gender;
          float height;
          float weight;

          // Behavior or Member Functions

          Breathe();
          Eat();
          Drink();
};

Once we have defined a class, we can define as many objects as required. Each object will possess some properties and behavior. The properties of objects may be same or different depending upon the context.

HumanBeing Alice, Bob, Steve;

Here Alice, Bob and Steve are objects of HumanBeing class. Each of them possess a set of properties and common behavior or methods.


C++ Program to solve Tower of Hanoi

TOWER OF HANOI

Tower of Hanoi is a famous mathematical puzzle. It was proposed by Edouard Lucas in 1883. The objective of this puzzle is to move stack of n disks from one rod to another considering the following rules:

1) Only one disk can be moved at a time.
2) A bigger disk can not be placed on the top of a smaller disk.
3) Only the topmost disk can be moved from the stack.

The Tower of Hanoi problem takes minimum (2^n)-1 moves to solve.

TOWER OF HANOI WITH ONE DISK



TOWER OF HANOI WITH TWO DISKS





TOWER OF HANOI WITH THREE DISKS









PROGRAM

//Program to solve Tower of Hanoi Problem

#include <iostream>

using namespace std;

void toh(int n, char from, char to, char aux)
{
        if(n==1)
        {
                 cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to; 
        }
        else
        {
                toh(n-1,from,aux,to);
                cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to;
                toh(n-1,aux,to,from);
        }
}

int main()
{
        int n;
        cout<<"ENTER NUMBER OF DISKS: ";
        cin>>n;
        toh(n,'A','C','B');
        return 0;
}

OUTPUT




C++ Program to convert octal number to its decimal equivalent [DEVCPP/GCC]

PROGRAM

//Program to covert octal to decimal equivalent.

# include <iostream>
# include <cmath>

using namespace std;

int main()
{
int octaltodecimal(int);
int num;
cout<<"ENTER A NUMBER(OCTAL):"<<endl;
cin>>num;

cout<<"DECIMAL EQUIVALENT IS:"<<octaltodecimal(num);
}

int octaltodecimal(int num)
{
int count=0,i,n,l,m,sum=0;
n=num;
while(num)
{
num=num/10;
count++;
}
m=count;
while(n)
{
l=n%10;
sum=sum+(l*pow(8,count-m));
m--;
n=n/10;
}
return sum;
}

OUTPUT






FIND US ON FACEBOOK!