Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

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

Friday, March 13, 2015

Operator Overloading In C++

C++ allows us to specify more than one definition for a function or an operator this property is known as function overloading and operator overloading.

Operator overloading lets us define the meaning of an operator when applied to operand(s) of a class type. Well use of operator overloading can make our
programs easier to write and easier to read.

By operator overloading we can't define a new operator i.e.. we can't use ** and define it to find power. 

Here is a program in which some arithmetic operators are overloaded for Complex Number class.

#include <iostream>
using namespace std;

class Complex
{
    float real, imag;
    
    public:
        Complex(float r = 0, float i = 0) : real(r), imag(i) {}
        
        friend ostream& operator<<(ostream&, const Complex&);
        friend istream& operator>>(istream&, Complex&);

        friend Complex operator+(const Complex&, const Complex&);
        Complex operator+(const Complex&);
        
        friend Complex operator-(const Complex&, const Complex&);
        Complex operator-(const Complex&);

        friend Complex operator*(const Complex&, const Complex&);
        Complex operator*(const Complex&);

        friend Complex operator/(const Complex&, const Complex&);
        Complex operator/(const Complex&);

        class DivideByZero {};
};

Complex operator*(const Complex& lhs, const Complex& rhs)
{   
    Complex result;
    cout << "Friend * Function Is Called." << endl;
    result.real = (lhs.real * rhs.real) - (lhs.imag * rhs.imag);
    result.imag = (lhs.real * rhs.imag) + (lhs.imag * rhs.real);

    return result;
}

Complex Complex::operator*(const Complex& rhs)
{
   Complex result;
   cout << "Member * Function Is Called." << endl;
   result.real = (real * rhs.real) - (imag * rhs.imag);
   result.imag = (real * rhs.imag) + (imag * rhs.real);

   return result;
}

Complex operator/(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend / Function Is Called." << endl;
    float tmp = (lhs.imag * lhs.imag) + (rhs.real * rhs.real);
    
    if (tmp == 0.0) {
        throw Complex::DivideByZero();
    }

    result.real = ((lhs.real * rhs.real) + (lhs.imag * rhs.imag)) / tmp;
    result.imag = ((lhs.imag * rhs.real) - (lhs.real * rhs.imag)) / tmp;    
 
    return result;
}

Complex Complex::operator/(const Complex& rhs)
{
    Complex result;
    cout << "Member / Function Is Called." << endl;
    float tmp = (imag * imag) + (rhs.real * rhs.real);
    
    if (tmp == 0.0) {
        throw Complex::DivideByZero();
    }

    result.real = ((real * rhs.real) + (imag * rhs.imag)) / tmp;
    result.imag = ((imag * rhs.real) - (real * rhs.imag)) / tmp;    
 
    return result;
}

Complex operator+(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend + Function Is Called." << endl;
    result.real = lhs.real + rhs.real;
    result.imag = lhs.imag + rhs.imag;

    return result;
}

Complex Complex::operator+(const Complex& rhs)
{
    Complex result;
    cout << "Member + Function Is Called." << endl;   
    result.real = real + rhs.real;
    result.imag = imag + rhs.imag;
    
    return result;
}

Complex operator-(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend - Function Is Called." << endl;
    result.real = lhs.real - rhs.real;
    result.imag = lhs.imag - rhs.imag;

    return result;
}

Complex Complex::operator-(const Complex& rhs)
{
    Complex result;
    cout << "Member - Function Is Called." << endl;   
    result.real = real - rhs.real;
    result.imag = imag - rhs.imag;
    
    return result;
}

ostream& operator<<(ostream& out, const Complex& rhs)
{
    out << "(" <>(istream& in, Complex& rhs)
{
    in >> rhs.real >> rhs.imag;
    return in;
}

int main()
{
    float r, i;

    cout << "---Arithmetic Operations---" << endl;

    cout << "Enter The First Complex Number: " << endl;
    cout << "Enter Real Part: " << endl; 
    cin >> r;
    cout << "Enter Imaginary Part: " << endl;
    cin >> i;
    Complex c1(r, i);

    cout << "Enter The Second Complex Number: " << endl;
    cout << "Enter Real Part: " << endl;
    cin >> r;
    cout << "Enter Imaginary Part: " << endl;
    cin >> i;
    Complex c2(r, i);

    cout << "The Result Is Of c1 + c2: " << c1 + c2 << endl;
    cout << "The Result Is Of c1 - c2: " << c1 - c2 << endl;
    cout << "The Result Is Of c1 * c2: " << c1 * c2 << endl;
    
    try {
        cout << "The Result Is Of c1 + c2:" << c1 / c2 << endl;
    }
    catch (Complex::DivideByZero) {
        cout << "Exception: Can't Divide By Zero." << endl;
        return -1;
    }
    
    cout << "---Automatic Type Conversion Testing---" << endl;
    
    Complex c3(2,5);
    cout << "Addition Of c3 + 2: " << c3 + 2 << endl;
    cout << "Multiplication Of c3 * 0: " << c3 * 0.0 << endl;

    return 0;
}


---Arithmetic Operations---
Enter The First Complex Number:
Enter Real Part:
2
Enter Imaginary Part:
3
Enter The Second Complex Number:
Enter Real Part:
4
Enter Imaginary Part:
5
Member + Function Is Called.
The Result Is Of c1 + c2: (6) + (8i)
Member - Function Is Called.
The Result Is Of c1 - c2: (-2) + (-2i)
Member * Function Is Called.
The Result Is Of c1 * c2: (-7) + (22i)
Member / Function Is Called.
The Result Is Of c1 + c2:(0.92) + (0.08i)
---Automatic Type Conversion Testing---
Member + Function Is Called.
Addition Of c3 + 2: (4) + (5i)
Member * Function Is Called.
Multiplication Of c3 * 0: (0) + (0i)

--------------------------------

Tuesday, March 3, 2015

C++ Linked List Implementation Using Template

Templates in C++ is a tool for generic programming. In general we want to make program that is independent of input type (integer, real, strings etc.).

Here we want to create a List class that in generic in nature and works or all sort of input type like strings , integers, float, double, chars etc.

#include <iostream>
#include <string>
using namespace std;

template <class T> class List;

template <class T>
class Node
{
    friend class List<T>;
    T val;
    Node<T> *link; 
    public:
        Node() {}
        Node(T v) : val(v), link(NULL) {}
        Node(T v, Node<T> *p) : val(v), link(p) {}
};

template <class T>
class List
{
    int size;
    Node<T> *head;
    public:
        List() : size(0) {
            head = new Node<T>();
        }
        void append(T);
        void prepend(T);
        void insertAt(T, int);
        void show() const;
        inline int len() { return size; }
};

template <class T>
void List<T>::append(T item)
{
    Node<T> *pivot = new Node<T>(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node<T> *temp = head;
        while (temp->link != NULL) {
            temp = temp->link; 
        }
        temp->link = pivot;
    }
    size++;
}

template <class T>
void List<T>::insertAt(T item, int pos)
{
    Node<T> *pivot = new Node<T>(item);

    if (pos <= size+1 && pos > 0) {
        int i = 0;
        Node<T> *temp = head, *prev;
        while (i != pos) {
            ++i;
            prev = temp;
            temp = temp->link;
        }
        pivot->link = temp;
        prev->link = pivot;
        size++;
    }
    else {
        cerr << "Invalid Position '" << pos << "' Sprecified." << endl;
    }
}

template <class T>
void List<T>::prepend(T item)
{
    Node<T> *pivot = new Node<T>(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node<T> *temp = head->link;
        head->link = pivot;
        pivot->link = temp;
    }
    size++;
}

template <class T>
void List<T>::show() const
{
    Node<T> *tmp = head->link;
    cout << "[";
    while (tmp != NULL) {
        cout << tmp->val << "," << ends;
        tmp = tmp->link;
    }
    cout << "\b\b]" << endl;
}

int main()
{
    List<int> a;
    
    a.append(2);
    a.append(3);
    a.prepend(1);
    a.append(5);
    a.show();
    a.insertAt(-1, 0);
    a.insertAt(4, 4);
    a.insertAt(6, 6);
    a.show();
    cout << "Length Of The List Of Integers: " << a.len() << endl;
    
    List<string> b;
    
    b.append("Cat");
    b.append("Dog");
    b.append("Mouse");
    b.append("Bird");
    b.show();
    cout << "Length Of The List Of Strings: "<< b.len() << endl;
    
    return 0;   
}


[1, 2, 3, 5]
Invalid Position '0' Sprecified.
[1, 2, 3, 4, 5, 6]
Length Of The List Of Integers: 6
[Cat, Dog, Mouse, Bird]
Length Of The List Of Strings: 4

--------------------------------

Sunday, March 1, 2015

Linked List Implementation In C++ Using Friend Class

Linked List is one of the most common data structures available. In C++ we already have List in STL but in this program we will implement out own link list class using friend class.



#include <iostream>
using namespace std;

class Node
{
    friend class List;
    int val;
    Node *link; 
    public:
        Node() {
            val = 0;
            link = NULL;
        }
        Node(int v) {
            val = v;
            link = NULL;
        }
        Node(int v, Node *p) {
            val = v;
            link = p;
        }
};

class List
{
    int size;
    Node *head;
    public:
        List() {
            head = new Node();
            size = 0;
        }
        void append(int);
        void show() const;
        inline int len() {
            return size;
        }
};

void List::append(int item)
{
    Node *pivot = new Node(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node *temp = head;
        while (temp->link != NULL) {
            temp = temp->link; 
        }
        temp->link = pivot;
    }
    size++;
}

void List::show() const
{
    Node *tmp = head->link;
    cout << "[";
    while (tmp != NULL) {
        cout << tmp->val << "," << ends;
        tmp = tmp->link;
    }
    cout << "\b\b]" << endl;
}

int main()
{
    List a;
    
    a.append(1);
    a.append(2);
    a.append(3);
    a.append(4);
    a.show();
    
    a.append(5);
    a.append(6);
    a.append(7);
    a.show();
    
    cout << "Length Of The List: "<< a.len() << endl;
    
    return 0;   
}
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
Length Of The List: 7

--------------------------------
Process exited after 0.3124 seconds with return value 0
Press any key to continue . . .



Friday, February 20, 2015

C++ Stack Implementation Using Template And Exceptions

#include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <string>
using namespace std;

template <class T>
class Stack
{
    private:
        T *stk;
        int size, tos, maxsize;
    public:
        Stack(int);
        ~Stack() {delete [] stk;} 
        T top() const;
        void pop();
        void push(T);
        template <class sT> friend ostream& operator<<(ostream &, const Stack<sT> &);   
        bool isempty() const {
            return (size == 0);
        }   
};

template <class T>
Stack<T>::Stack(int s)
{
    size = 0;
    maxsize = s;
    tos = -1;
    if (s <= 0) {
        throw out_of_range("stack(): size cant be zero or nagative.");
    }
    else {
        stk = new T[maxsize];
    }
}

template <class sT>
ostream& operator<<(ostream &out, const Stack<sT> &s)
{
    int i;
    cout << '[';
    for (i = 0; i < s.size; i++) {
        out << s.stk[i] << "," << ends;
    }
    cout << "\b\b";
    cout << ']';
    return out;
}

template <class T>
T Stack<T>::top() const 
{
    if (isempty()) {
        throw out_of_range("top() error: stack is empty.");
    }
    else {
        return stk[tos];
    }
}

template <class T>
void Stack<T>::push(T elem)
{
    if(size == maxsize) {
        throw out_of_range("push error: Stack is full.");
    }
    else {
        stk[++tos] = elem;
        ++size;
    }
}

template <class T>
void Stack<T>::pop()
{
    if(isempty()) {
        throw out_of_range("pop() error: Stack is full.");
    }
    else {
        size--;
        tos--;
    }
}


int main()
{
    try {
        cout << "<For Integers>" << endl;
        Stack<int> s(5);
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        cout << "Stack:" << s << endl;
        
        cout << "\n<For Strings>" << endl;
        Stack<string> g(4);
        g.push("Superman");
        g.push("Batman");
        g.push("Flash");
        g.push("Spiderman");
        cout << "Stack:[";
        while(!g.isempty()) {
            cout << g.top() << "," << ends;
            g.pop();
        }
        cout << "\b\b]" << endl;
        
        cout << "\n<Exception>" << endl;
        Stack<int> j(0);
    }
    catch(exception &e) {
        cerr << e.what() << endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}


<For Integers>
Stack:[1, 2, 3, 4]
<For Strings>
Stack:[Spiderman, Flash, Batman, Superman]
<Exception>
stack(): size cant be zero or nagative.

--------------------------------
Process exited after 0.3268 seconds with return value 1
Press any key to continue . . .

Wednesday, February 4, 2015

Fully Parenthesized Infix Expression From Postfix Expression

The problem is that you are given a post fix expression and you need to convert it to a fully parenthesize infix expression.

Exmple:
  • Input: ab+
  • Output: (a+b)
The approach used in this program is to print the parenthesis durin infix traversal of the expression tree built from the postfix expression.
#include <iostream>
#include <stack>

using namespace std;

typedef struct Node
{
    char data;
    Node *lChild, *rChild;
}Node;

class ExpressionTree
{
    private:
        Node *root;
    public:
        ExpressionTree() { root = NULL; }
        ExpressionTree(char[]);
        Node* getRoot() { return root; }
        Node* createNode(char , Node*, Node*);
        friend bool isOperator(char);
        friend void inOrder();
};

bool isOperator(char opp)
{
    switch(opp)
    {
        case '+':
        case '*':
        case '/':
        case '^':
        case '-':
            return true;
        default:
            return false;
    }
}

Node* ExpressionTree::createNode(char ch, Node *l, Node *r)
{
    Node *tmp = new Node();
    tmp->data = ch;
    tmp->lChild = l;
    tmp->rChild = r;
    return tmp;
}

ExpressionTree::ExpressionTree(char arr[])
{
    stack<Node*> s;
    Node *ptr, *l, *r;
    int i = 0;
    while(arr[i])
    {
        if(isOperator(arr[i]))
        {
            l = s.top();
            s.pop();
            r = s.top();
            s.pop();
            ptr = createNode(arr[i], r , l);
        }
        else
        {
            ptr = createNode(arr[i], NULL, NULL);
        }
        s.push(ptr);
        i++;
    }
    root = s.top();
}


void inOrder(Node* T)
{
    if(T != NULL)
    {
        if(isOperator(T->data)) cout << "(";

        inOrder(T->lChild);
        cout << T->data;
        inOrder(T->rChild);

        if(isOperator(T->data)) cout << ")";
    }
}

int main()
{
    char exp[50];
    
    cout << "Enter A Postfix Expression:" << ends;
    cin >> exp;
    
    ExpressionTree t(exp);
    
    cout << "Given Postfix Expression:" << ends;
    cout << exp << endl;
    
    cout << "In-order Form: " << ends;
    inOrder(t.getRoot());
    
    return 0;
}
Enter A Postfix Expression: ab+c*
Given Postfix Expression: ab+c*
In-order Form:  ((a+b)*c)
--------------------------------
Process exited after 6.555 seconds with return value 0
Press any key to continue . . .

Thursday, January 29, 2015

Constructors

Constructor

In class based object oriented programming constructor is a special member function (or an subroutine) that is called to create object of a particular class. It prepares the object for use.

Properties

> A constructor will have same name as the class (exceptions: python, php, ruby ...)
> It does not have any explicit return type at all not even void. (as they always return the object of the existing class.).
> The constructor is called each time the object declaration is encountered.
> Like other functions constructor also have parameter list, and a (possibly empty) body.
> A class can have multiple constructor.
>Unlike other member function constructor must not declare as const.

Constructors Types
Constructor Types

Default Constructor

Default constructor (or synthesized default constructor) is a constructor generated automatically by the C++ compiler in the absence of any programmers defined constructor. A use defined no argument constructor is also called default. A parametrized constructor with all its arguments as default arguments is also called a default constructor.