Friday 31 January 2014

Minor project: Cyber Management System using C

cyber_thumb[2] C.yber is a program which interconnects different computers which allows users to communicate over the computer network and provide security from unauthorized users by login system in client server.The project aims at managing the cyber cafe with multiple clients and give the clients access of services that the cyber is providing when it log in. The clients can log in as members or guests and use the services that the cyber is providing. The client can request services of cafe like tea, coffee or any others.
The above program uses file handling as database. The various features of C like Multithreading, Socket (Networking) are used. It is very useful for the student or beginner in the programming field. It also helps in building the other type of management software or projects like library management, student record, and many more.
Block Diagram:
basic operation_thumb[6]

DOWNLOAD CYBER MANAGEMENT PROJECT

Mini Project Student Record System in C

Mini project student record system is another project based on programming language C. It also uses files as database. This project is similar to another mini projects of this blog but every project in Programming Techniques has unique style of coding and presentation so that reader get clear about all aspects of programming. In this project, a console window is virtually splited into two parts, one is static which doesn’t change and another is dynamic which changes time to time. The text are written using various colors to make them static.
The program is not complete, reader can download the code and make improvement and also make it complete. There are many places for further enhancement. I think this project becomes milestone for your study of C programming and making project using C.
Student Record System

C Mini Project Ideas with a Sample Calculator Project

Do you want to build a simple application in C but you don’t know how and where to start? Or you know how to build a C application but don’t know any project ideas? then do not worry you are at the right place. If you finished learning  C and became familiar with its programming paradigm then I encourage you to build some applications (weather it is application software or system software) to actually sharpen your skills in C. If you do projects, then you will know how to apply those programming constructs accurately in building a projects. So here I will explain how to start a new C projects for completely beginner and give some projects ideas about what type of application you can build using C language
I have some suggestions for people who are about to write their first C application.

  1. Please do not try to build a big application. Start with a very very simple application, try to learn how it works and only then think about how to extend it to build relatively large application.
  2. Always start with console application, without including attractive graphics. To include graphics, you must learn about different graphics libraries. Just thing you are the beginner of C just trying to build some application, and if you include graphics then you must learn the graphics libraries more than C. This creates you confusion and you mind will be messed up. So please try to build some console application first.
  3. Try to include more programming constructs. Since building first application implies making you strong and confident in C, always try to include more and more programming constructs. This includes basics arithmetic operations, conditional statements (if, if else), loops ( while, do while, for), user defined functions, arrays, pointers, structure, dynamic memory allocation, file handling and if possible some low level operations. You just combine these techniques and try to build an application that includes most of them.
For the very beginner who have not done any project on C but know the programming, I have attached a compressed file please download and read this. It consists of two files one pdf file which is the simple documentation of the project and other a C file which contains some coding with lot of comments that help you to step through the project. The project is about building a simple Calculator that solve some mathematical operations like Matrix, Complex number, polynomial equations etc. Please read the documentation carefully. And also the C file consists of some pre written code. Run the code and see the sample output of some operations and I am sure you will get some idea about creating a simple project. If you faced any difficulties then free feel to ask as a comment.
You can download the file for here.
Now for those who want some project ideas. There are lot of projects that you can do in C. For example, consider a project that keeps record of your daily expenses. And at the end of the month shows you the record of total expenses you did over a month along with on which items you made the expense. Similarly think of a application that keeps record of the employees in an organization, you can register new employee, search the employee, edit the record of employee and perform other various operation. or you can make simple non-graphics game like hangman, tic-tac-toe etc. Other various projects ideas are presented below
  1. Library management system
  2. Calendar application
  3. Employee record system
  4. Quiz application
  5. Student record system
  6. Electricity billing system
  7. Supermarket billing system
  8. Contact manager
  9. Calculator
  10. Simple encryption algorithm
  11. Physics problem solver
  12. Sudoku solver (difficult)
  13. Generate different start patterns
  14. Hospital management system
  15. Random number generator
  16. Electric circuit solver etc.

Thursday 30 January 2014

Drawing a Circle with Mid – Point Circle Algorithm in C/C++

As in the previous line drawing algorithm, we sample at unit intervals and determine the closest pixel position to the specified circle path at each step. For a given radius r and screen center position (xc, yc), we can first set up our algorithm to calculate pixel positions around a circle path centered at the coordinate origin (0, 0). Then each calculated  position (x, y) is moved to its proper screen position by adding xc to x and yc to y. Along the circle section from x = 0 to x = y in the first quadrant, the slope of the curve varies from 0 to –1.  Therefore, we can take unit steps in the positive x direction over this octant and use a decision parameter to determine which of the two possible y positions is closer to the circle path at each step. Position in the other seven octants are then obtained by symmetry.

The following section implements Mid – Point Cicle  Algorithm in C/C++. The source code is complied using gcc Compiler and Code::Blocks IDE. To print a pixel, SetPixel() function of windows.h is used.
Note: to run this code in your machine with Code::blocks IDE, add a link library libgdi32.a (it is usually inside MinGW\lib )  in linker setting.
Souce Code
#include <windows.h>
#include <cmath>
#define ROUND(a) ((int) (a + 0.5))
/* set window handle */
static HWND sHwnd;
static COLORREF redColor=RGB(255,0,0);
static COLORREF blueColor=RGB(0,0,255);
static COLORREF greenColor=RGB(0,255,0);
void SetWindowHandle(HWND hwnd){
    sHwnd=hwnd;
}
/* SetPixel */
void setPixel(int x,int y,COLORREF& color=redColor){
    if(sHwnd==NULL){
        MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR);
        exit(0);
    }
    HDC hdc=GetDC(sHwnd);
    SetPixel(hdc,x,y,color);
    ReleaseDC(sHwnd,hdc);
    return;
}
void circlePoints(int xCenter, int yCenter, int x, int y){
    setPixel(xCenter + x, yCenter + y);
    setPixel(xCenter - x, yCenter + y);
    setPixel(xCenter + x, yCenter - y);
    setPixel(xCenter - x, yCenter - y);
    setPixel(xCenter + y, yCenter + x);
    setPixel(xCenter - y, yCenter + x);
    setPixel(xCenter + y, yCenter - x);
    setPixel(xCenter - y, yCenter - x);
}
void drawCircle(int xCenter, int yCenter, int radius){
    int x = 0;
    int y = radius;
    int p = 1 - radius;
    circlePoints(xCenter, yCenter, x, y);
    while(x < y){
        x++;
        if (p < 0){
            p += 2 * x + 1;
        }else{
            y--;
            p += 2 * (x - y) + 1;
        }
        circlePoints(xCenter, yCenter, x, y);
    }
}
/* Window Procedure WndProc */
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){
    switch(message){
        case WM_PAINT:
            SetWindowHandle(hwnd);
            drawCircle(200, 200, 100);
            break;
        case WM_CLOSE: // FAIL THROUGH to call DefWindowProc
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
        break; // FAIL to call DefWindowProc //
    }
    return DefWindowProc(hwnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow){
    static TCHAR szAppName[] = TEXT("Circle");
    WNDCLASS wndclass;
    wndclass.style         = CS_HREDRAW|CS_VREDRAW ;
    wndclass.lpfnWndProc   = WndProc ;
    wndclass.cbClsExtra    = 0 ;
    wndclass.cbWndExtra    = 0 ;
    wndclass.hInstance     = hInstance ;
    wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
    wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
    wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
    wndclass.lpszMenuName  = NULL ;
    wndclass.lpszClassName = szAppName ;
    // Register the window //
    if(!RegisterClass(&wndclass)){
        MessageBox(NULL,"Registering the class failled","Error",MB_OK|MB_ICONERROR);
        exit(0);
    }
    // CreateWindow //
    HWND hwnd=CreateWindow(szAppName,"Mid Point Circle Drawing - Programming Techniques",
                WS_OVERLAPPEDWINDOW,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 NULL,
                 NULL,
                 hInstance,
                 NULL);
    if(!hwnd){
        MessageBox(NULL,"Window Creation Failed!","Error",MB_OK);
        exit(0);
    }
    // ShowWindow and UpdateWindow //
    ShowWindow(hwnd,iCmdShow);
    UpdateWindow(hwnd);
    // Message Loop //
    MSG msg;
    while(GetMessage(&msg,NULL,0,0)){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    /* return no error to the operating system */
    return 0;
}
Output

MidPointCicleAlgorithm

Implementing Bresenham’s Line Drawing Algorithm in C/C++

Bresenham’s Line Drawing Algorithm is an accurate and efficient raster line-generating algorithm developed by Bresenham. In this algorithm, we first consider the scan – conversion process for lines with positive slope less than 1. Pixel positions along a line path are then determined by sampling at unit x intervals. Starting from the left end point (x0, y0) of a given line, we step to each successive column (x position) and plot the pixel whose scan – line y values is closet to the line path. Assuming we have determined that the pixel at (x(k), y(k)) is to be displayed, we next need to decide which pixel to plot in column x(k+1). Our choices are the pixels at positions (x(k) + 1, y(k)) and (x(k) + 1, y(k) + 1).

The following section implements Bresenham’s  Algorithm in C/C++. The source code is complied using gcc Compiler and Code::Blocks IDE. To print a pixel, SetPixel() function of windows.h is used.
#include <windows.h>
#include <cmath>
#define ROUND(a) ((int) (a + 0.5))
/* set window handle */
static HWND sHwnd;
static COLORREF redColor=RGB(255,0,0);
static COLORREF blueColor=RGB(0,0,255);
static COLORREF greenColor=RGB(0,255,0);
void SetWindowHandle(HWND hwnd){
    sHwnd=hwnd;
}
/* SetPixel */
void setPixel(int x,int y,COLORREF& color=redColor){
    if(sHwnd==NULL){
        MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR);
        exit(0);
    }
    HDC hdc=GetDC(sHwnd);
    SetPixel(hdc,x,y,color);
    ReleaseDC(sHwnd,hdc);
    return;
// NEVERREACH //
}
void drawLineBresenham(int xa, int ya, int xb, int yb){
    int dx = abs(xa - xb), dy = abs(ya - yb);
    int p = 2 * dy - dx;
    int twoDy = 2 * dy, twoDyDx = 2 * (dy - dx);
    int x, y, xEnd;
    if (xa > xb){
        x = xb;
        y = yb;
        xEnd = xa;
    }else{
        x = xa;
        y = ya;
        xEnd = xb;
    }
    setPixel(x, y);
    while(x < xEnd){
        x++;
        if(p < 0)
            p += twoDy;
        else{
            y++;
            p += twoDyDx;
        }
        setPixel(x, y);
    }
}
/* Window Procedure WndProc */
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){
    switch(message){
        case WM_PAINT:
            SetWindowHandle(hwnd);
            drawLineBresenham(10, 20, 250, 300);
            break;
        case WM_CLOSE: // FAIL THROUGH to call DefWindowProc
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
        break; // FAIL to call DefWindowProc //
    }
    return DefWindowProc(hwnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow){
    static TCHAR szAppName[] = TEXT("Straight Line");
    WNDCLASS wndclass;
    wndclass.style         = CS_HREDRAW|CS_VREDRAW ;
    wndclass.lpfnWndProc   = WndProc ;
    wndclass.cbClsExtra    = 0 ;
    wndclass.cbWndExtra    = 0 ;
    wndclass.hInstance     = hInstance ;
    wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
    wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
    wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
    wndclass.lpszMenuName  = NULL ;
    wndclass.lpszClassName = szAppName ;
    // Register the window //
    if(!RegisterClass(&wndclass)){
        MessageBox(NULL,"Registering the class failled","Error",MB_OK|MB_ICONERROR);
        exit(0);
    }
    // CreateWindow //
    HWND hwnd=CreateWindow(szAppName,"Bresenham's Algorithm - Programming Techniques",
                WS_OVERLAPPEDWINDOW,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 NULL,
                 NULL,
                 hInstance,
                 NULL);
    if(!hwnd){
        MessageBox(NULL,"Window Creation Failed!","Error",MB_OK);
        exit(0);
    }
    // ShowWindow and UpdateWindow //
    ShowWindow(hwnd,iCmdShow);
    UpdateWindow(hwnd);
    // Message Loop //
    MSG msg;
    while(GetMessage(&msg,NULL,0,0)){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    /* return no error to the operating system */
    return 0;
}

The output generated by above program is 

Bresenham

Drawing Straight Line using DDA Algorithm in C/C++

The digital differentia analyzer (DDA) is a scan-conversion line algorithm. In this algorithm, we sample the line at unit intervals in one coordinate and determine corresponding integer values nearest the line path of the other coordinate and plot those coordinate (pixel) in computer screen. Consider first a line with positive slope. If the slope is less than or equal to 1, we sample at unit x intervals (dx = 1) and computer each successive y value as y(k+1) = y(k) + m. Subscript k takes integer values starting from 1, for the first point, and increases by 1 until the final endpoint is reached. For lines with a positive slope greater than 1, we reverse the roles of x and y.That is, we sample at unit y intervals (dy = 1) and calculate each succeeding x value as x(k+1) = x(k) + (1/m)

The following section implements DDA Algorithm in C/C++. The source code is complied using gcc Compiler and Code::Blocks IDE. To print a pixel, SetPixel() function of windows.h is used.

Note

To run this code in your machine with Code::blocks IDE, add a link library libgdi32.a (it is usually inside MinGW\lib )  in linker setting and make the file extension .cpp but not .c. For C user, here is a link to download C file of this tutorial. Download

#include <windows.h>
#include <cmath>
#define ROUND(a) ((int) (a + 0.5))
/* set window handle */
static HWND sHwnd;
static COLORREF redColor=RGB(255,0,0);
static COLORREF blueColor=RGB(0,0,255);
static COLORREF greenColor=RGB(0,255,0);
void SetWindowHandle(HWND hwnd){
sHwnd=hwnd;
}
/* SetPixel */
void setPixel(int x,int y,COLORREF& color=redColor){
if(sHwnd==NULL){
MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR);
exit(0);
}
HDC hdc=GetDC(sHwnd);
SetPixel(hdc,x,y,color);
ReleaseDC(sHwnd,hdc);
return;
// NEVERREACH //
}
void drawLineDDA(int xa, int ya, int xb, int yb){
int dx = xb - xa, dy = yb - ya, steps, k;
float xIncrement, yIncrement, x = xa, y = ya;
if(abs(dx) > abs(dy)) steps = abs(dx);
else steps = abs(dy);
xIncrement = dx / (float) steps;
yIncrement = dy / (float) steps;
setPixel(ROUND(x), ROUND(y));
for(int k = 0; k < steps; k++){
x += xIncrement;
y += yIncrement;
setPixel(x, y);
}
}
/* Window Procedure WndProc */
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){
switch(message){
case WM_PAINT:
SetWindowHandle(hwnd);
drawLineDDA(10, 20, 250, 300);
break;
case WM_CLOSE: // FAIL THROUGH to call DefWindowProc
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
break; // FAIL to call DefWindowProc //
}
return DefWindowProc(hwnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow){
static TCHAR szAppName[] = TEXT("Straight Line");
WNDCLASS wndclass;
wndclass.style         = CS_HREDRAW|CS_VREDRAW ;
wndclass.lpfnWndProc   = WndProc ;
wndclass.cbClsExtra    = 0 ;
wndclass.cbWndExtra    = 0 ;
wndclass.hInstance     = hInstance ;
wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName  = NULL ;
wndclass.lpszClassName = szAppName ;
// Register the window //
if(!RegisterClass(&wndclass)){
MessageBox(NULL,"Registering the class failled","Error",MB_OK|MB_ICONERROR);
exit(0);
}
// CreateWindow //
HWND hwnd=CreateWindow(szAppName,"DDA - Programming Techniques",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
if(!hwnd){
MessageBox(NULL,"Window Creation Failed!","Error",MB_OK);
exit(0);
}
// ShowWindow and UpdateWindow //
ShowWindow(hwnd,iCmdShow);
UpdateWindow(hwnd);
// Message Loop //
MSG msg;
while(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
/* return no error to the operating system */
return 0;
}

The output of this program is looks like

DDADDA algorithm is faster than the direct use of equation y = mx + c however, the rounding operations and floating-point arithmetic makes it still time consuming. To overcome this limitation of DDA Algorithm, Bresenham discovered Bresenham’s Line Drawing Algorithm.

Wednesday 29 January 2014

Conversion of infix string to postfix and evaluation of postfix string to make a simple calculator application in C++.

(A) Algorithm for converting an infix expression into postfix operation
1. Add “(“ at the beginning and “)” at the end of an 
infix expression Q.
2. Scan Q from left to right and repeat 
step 3 to step 6.
3  If an operand is encountered, add it into postfix P.
4. If a left parenthesis is encountered, 
push it onto the stack S
5. If and operator op is encountered then,
(a) Repeatedly pop from stack S and add 
it to postfix each operator which has 
same precedence as or higher precedence than op.
(b) Add op to Stack S.
6. If a right parenthesis is encountered, then
(a) Repeatedly pop from stack S and add 
it to postfix each operator until left parenthesis is encountered on stacks.
(b) Remove the left parenthesis.



(B) Algorithm for evaluation of postfix string
1. Scan postfix P from left to right and repeat 
step 2 and 3 for each elements of P until the
 NULL character or other symbol is encountered.
2. If an operand is encountered then push it on to the stack.
3. If an operator op is encountered, then
(a) Remove the top elements of stack S where A is the
 top element and B is next top element
(b) Evaluate B op A
(c) Place the result back onto the stack S
(d) Return top of the stack which is required
 result for our calculation



Source code for both infix to postfix and postfix evaluation
/****************************************************************
Program: Conversion of Infix to Postfix String and Evaluation
Language: C/C++
by Bibek Subedi
June 13, 2011
Operators Used
1. '+' For addition
2. '-' For Subtraction
3. '*' For Multiplication
4. '/' For Division
5. '^' For Exponentiation
Program Limitations
* This program Only process single digit operations
* Can't handle unary operation
* Only process left to right associativity
***************************************************/
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<string>
#define MAX_SIZE 20
using namespace std;
template<class T>
class Stack{
private:
T item[MAX_SIZE];
int top;
public:
Stack(){
top = -1;
}
void push(T data){
if(!this->is_full())
item[++top] = data;
else{
cout<<"Stack Error"<<endl;
exit(10);
}
}
T pop(){
if(!this->is_empty())
return item[top--];
else{
cout<<"Stack is Empty"<<endl;
exit(11);
}
}
int size(){
return top+1;
}
bool is_empty(){
if(top==-1)
return true;
else
return false;
}
bool is_full(){
if(top==MAX_SIZE-1)
return true;
else
return false;
}
void display(){
for(int i=0; i<this->size(); i++){
cout<<item[i]<<" ";
}
cout<<endl;
}
T return_top(){
return item[top];
}
};
class Convert{
private:
bool num_flag;
bool two_digit_flag;
public:
Convert();
string return_with_bracket(string infix);
void to_Postfix(string infix,char postfix[]);
bool prcd(char op1, char op2);
int isOperand(char op);
int isOperator(char op);
bool return_flag(){
return num_flag;
}
};
Convert::Convert(){
this->num_flag = false;
this->two_digit_flag = false;
}
string Convert::return_with_bracket(string infix){
return("(" + infix + ")");
}
bool Convert::prcd(char op1, char op2){
if((op1=='+' || op1=='-' || op1=='*' || op1=='/') && op2=='('  )
return true;
if(op1=='+' && op2=='+')
return true;
if(op1=='-' && op2=='-')
return false;
if(op1=='-' && op2=='+')
return false;
if(op1=='+' && op2=='-')
return false;
if(op1=='/' && op2=='/')
return false;
if(op1=='/' && (op2=='-' || op2=='+'))
return true;
if(op1=='*' && (op2=='+' || op2=='-'))
return true;
if((op1 == '-' || op1 == '+') && (op2 =='*' || op2 == '/'))
return false;
if((op1 == '$' || op1 == '+') && (op2 =='*' || op2 == '/' || op2=='-'))
return true;
if((op1 == '-' || op1 == '+' || op1 =='*' || op1 == '/')&& op2=='^')
return false;
if(op1 == '^' && ( op2 == '+' || op2 =='*' || op2 == '/' || op2=='-'))
return false;
}
int Convert::isOperand(char op){
return(op>= '0' && op <= '9');
}
int Convert::isOperator(char op){
return(op=='+' || op=='-' || op == '/' || op=='*' || op=='^');
}
void Convert::to_Postfix(string infix, char postfix[]){
int position, outpos=0;
char c;
int count = 0;
char temp;
char stacktop ;
Stack<char> stack;
for(position = 0; (c = infix[position])!='\0'; position++){
if(this->isOperand(c)){
postfix[outpos++] = c;
this->num_flag = true;
count++;
if(count>=2){
this->two_digit_flag = true;
}
}else if(this->isOperator(c)){
count = 0;
if(isOperator(infix[position]) && isOperator(infix[position+1])){
cout<<"\aMissing argument in between "<<infix[position]<<" and "<<infix[position+1]
<<" in column "<< position+1<<endl;
exit(9);
}
if(this->prcd(c, stacktop)){
stacktop=stack.return_top();
stack.push(c);
stacktop = c;
}else{
while(true){
temp = stack.pop();
postfix[outpos++] =temp;
stacktop = stack.return_top();
if(prcd(c, stacktop) || stacktop=='(')
break;
}
stack.push(c);
stacktop = stack.return_top();
}
}
else if(c=='('){
count = 0;
stack.push(c);
stacktop = stack.return_top();
}else if(c==')'){
count = 0;
while(1){
if(stack.size()==0){
cout<<"Warning!! Number of ')' is greater than '('" <<endl;
exit(2);
}
temp = stack.pop();
if(temp!='('){
postfix[outpos++] = temp;
}else{
break;
}
}
stacktop =stack.return_top();
}
else{
cout<<"Invalid input";
exit(3);
}
if(infix[position]==')' && infix[position+1]=='('){
stack.push('*');
stacktop = stack.return_top();
}
}
if(stack.size()!=0){
cout<<"Warning!!Number of '(' is greater than ')'"<<endl;
// exit(6);
}
if(!this->return_flag()){
cout<<"You must Enter Numeric value for calculation"<<endl;
cout<<"This program cannot perform operations on variables";
exit(5);
}
if(this->two_digit_flag){
cout<<"Sory! Althoug u may  have entered right string"<<endl;
cout<<"this program is only for single digit operation"<<endl;
exit(8);
}
postfix[outpos] = '\0';
}
class Evaluate{
public:
double eval(char expr[], Convert &);
double oper(int symb, double op1, double op2);
};
double Evaluate::oper(int symb, double op1, double op2){
switch(symb){
case '+': return (op1 + op2);
case '-': return (op1 - op2);
case '*': return (op1 * op2);
case '/': return (op1 / op2);
case '^': return (pow(op1, op2));
}
}
double Evaluate::eval(char expr[],Convert &convert){
int c, position;
char temp1;
int count = 0;
double opnd1, opnd2, value;
Stack<double> stack;
for(position = 0; (c = expr[position])!='\0'; position++){
if(convert.isOperand(c)){
temp1 = double(c-'0');
stack.push(temp1);
}else{
opnd2 = stack.pop();
if(stack.size()==0){
cout<<"This program cannot process unary operation";
exit(1);
}
opnd1 = stack.pop();
value = oper(c, opnd1, opnd2);
stack.push(value);
}
}
if(stack.size()>=2){
cout<<"Sory! this program cannot calculate this"<<endl;
cout<<"Enter +, *, /, - or ^ between bracket"<<endl;
exit(4);
}
return (stack.pop());
}
int main(){
Convert convert;
Evaluate evaluate;
string bracketted_infix;
char infix[50], postfix[50];
char choice;
while(1){
cout<<"Enter string: ";
cin>>infix;
cout<<endl;
cout<<"Entered String: "<<infix<<endl;
bracketted_infix = convert.return_with_bracket(infix);
convert.to_Postfix(bracketted_infix, postfix);
cout<<"Equivalent Postfix string: "<<postfix<<endl;
cout<<"RESULT: ";
cout<<evaluate.eval(postfix, convert);
cout<<"\nCalculate another string?(y/n) ";
cin>>choice;
cout<<endl;
if(choice=='n')
break;
}
return 0;
}

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews