## C++ || Multi Digit, Decimal & Negative Number Infix To Postfix Conversion & Evaluation The following is sample code which demonstrates the implementation of a multi digit, decimal, and negative number infix to postfix converter and evaluator using a Finite State Machine

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```How To Convert Infix To Postfix How To Evaluate A Postfix Expression What Is A Finite State Machine? ```

Using a Finite State Machine, the program demonstrated on this page has the ability to convert and evaluate a single digit, multi digit, decimal number, and/or negative number infix equation. So for example, if the the infix equation of (19.87 * ~2) was entered into the program, the converted postfix expression of 19.87 ~2* would display to the screen, as well as the final evaluated answer of -39.74.

NOTE: In this program, negative numbers are represented by the “~” symbol.

This program has the following flow of control:

```• Get an infix expression from the user • Convert the infix expression to postfix • Use a Finite State Machine to isolate all of the math operators, multi digit, decimal, negative and single digit numbers that are found in the postfix expression • Evaluate the postfix expression using the tokens found from the above step • Display the evaluated answer to the screen ```

The above steps are implemented below.

``` Multi Digit Infix To Postfix Conversion & Evaluation C++ // ============================================================================ // Author: K Perkins // Taken From: http://programmingnotes.org/ // Date: Jan 31, 2014 // File: InToPostEval.cpp // Description: The following demonstrates the implementation of an infix to // postfix converter and evaluator. Using a Finite State Machine, this // program has the ability to convert and evaluate multi digit, decimal, // negative and positive values. // ============================================================================ #include <iostream> #include <cstdlib> #include <cmath> #include <cctype> #include <string> #include <vector> #include <stack> using namespace std; /* This holds the transition states for our Finite State Machine -- They are placed in numerical order for easy understanding within the FSM array, which is located below */ enum FSM_TRANSITIONS { REJECT = 0, INTEGER, REAL, NEGATIVE, OPERATOR, UNKNOWN, SPACE }; /* This is the Finite State Machine -- The zero represents a place holder, so the row in the array starts on row 1 instead of 0 integer, real, negative, operator, unknown, space */ int stateTable[] = {{0, INTEGER, REAL, NEGATIVE, OPERATOR, UNKNOWN, SPACE}, /* STATE 1 */ {INTEGER, INTEGER, REAL, REJECT, REJECT, REJECT, REJECT}, /* STATE 2 */ {REAL, REAL, REJECT, REJECT, REJECT, REJECT, REJECT}, /* STATE 3 */ {NEGATIVE, INTEGER, REAL, REJECT, REJECT, REJECT, REJECT}, /* STATE 4 */ {OPERATOR, REJECT, REJECT, REJECT, REJECT, REJECT, REJECT}, /* STATE 5 */ {UNKNOWN, REJECT, REJECT, REJECT, REJECT, UNKNOWN, REJECT}, /* STATE 6 */ {SPACE, REJECT, REJECT, REJECT, REJECT, REJECT, REJECT}}; // function prototypes void DisplayDirections(); string ConvertInfixToPostfix(string infix); bool IsMathOperator(char token); int OrderOfOperations(char token); vector<string> Lexer(string postfix); int Get_FSM_Col(char& currentChar); double EvaluatePostfix(const vector<string>& postfix); double Calculate(char token, double op1, double op2); int main() { // declare variables string infix = ""; string postfix = ""; double answer = 0; vector<string> tokens; // display directions to user DisplayDirections(); // get data from user cout<<"\nPlease enter an Infix expression: "; getline(cin, infix); postfix = ConvertInfixToPostfix(infix); // use the "Lexer" function to isolate multi digit, negative and decimal // numbers, aswell as single digit numbers and math operators tokens = Lexer(postfix); // display the found tokens to the screen // for(unsigned x = 0; x < tokens.size(); ++x) // { // cout<<tokens.at(x)<<endl; // } cout <<"\nThe Infix expression = "<<infix; cout <<"\nThe Postfix expression = "<<postfix<<endl; answer = EvaluatePostfix(tokens); cout<<"\nFinal answer = "<<answer<<endl; return 0; }// end of main void DisplayDirections() {// this function displays instructions to the screen cout << "\n==== Infix To Postfix Conversion & Evaluation ====\n" <<"\nMath Operators:\n" <<"+ || Addition\n" <<"- || Subtraction\n" <<"* || Multiplication\n" <<"/ || Division\n" <<"% || Modulus\n" <<"^ || Power\n" <<"\$ || Square Root\n" <<"s || Sine\n" <<"c || Cosine\n" <<"t || Tangent\n" <<"~ || Negative Number\n" <<"Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))\n"; // ((sin(-4^5)*1.4)/(sqrt(23+2)--2.8))*(cos(1%2)/(7.28*.1987)^(tan(23))) }// end of DisplayDirections string ConvertInfixToPostfix(string infix) {// this function converts an infix expression to postfix // declare function variables string postfix; stack<char> charStack; // loop thru array until there is no more data for(unsigned x = 0; x < infix.length(); ++x) { // place numbers (standard, decimal, & negative) // numbers onto the 'postfix' string if((isdigit(infix[x])) || (infix[x] == '.') || (infix[x] == '~')) { postfix += infix[x]; } else if(isspace(infix[x])) { continue; } else if(IsMathOperator(infix[x])) { postfix += " "; // use the 'OrderOfOperations' function to check equality // of the math operator at the top of the stack compared to // the current math operator in the infix string while((!charStack.empty()) && (OrderOfOperations(charStack.top()) >= OrderOfOperations(infix[x]))) { // place the math operator from the top of the // stack onto the postfix string and continue the // process until complete postfix += charStack.top(); charStack.pop(); } // push the remaining math operator onto the stack charStack.push(infix[x]); } // push outer parentheses onto stack else if(infix[x] == '(') { charStack.push(infix[x]); } else if(infix[x] == ')') { // pop the current math operator from the stack while((!charStack.empty()) && (charStack.top() != '(')) { // place the math operator onto the postfix string postfix += charStack.top(); // pop the next operator from the stack and // continue the process until complete charStack.pop(); } if(!charStack.empty()) // pop '(' symbol off the stack { charStack.pop(); } else // no matching '(' { cout<<"\nPARENTHESES MISMATCH #1\n"; exit(1); } } else { cout<<"\nINVALID INPUT #1\n"; exit(1); } } // place any remaining math operators from the stack onto // the postfix array while(!charStack.empty()) { postfix += charStack.top(); charStack.pop(); } return postfix; }// end of ConvertInfixToPostfix bool IsMathOperator(char token) {// this function checks if operand is a math operator switch(tolower(token)) { case '+': case '-': case '*': case '/': case '%': case '^': case '\$': case 'c': case 's': case 't': return true; break; default: return false; break; } }// end of IsMathOperator int OrderOfOperations(char token) {// this function returns the priority of each math operator int priority = 0; switch(tolower(token)) { case 'c': case 's': case 't': priority = 5; break; case '^': case '\$': priority = 4; break; case '*': case '/': case '%': priority = 3; break; case '-': priority = 2; break; case '+': priority = 1; break; } return priority; }// end of OrderOfOperations vector<string> Lexer(string postfix) {// this function parses a postfix string using an FSM to generate // each individual token in the expression vector<string> tokens; char currentChar = ' '; int col = REJECT; int currentState = REJECT; string currentToken = ""; // use an FSM to parse multidigit and decimal numbers // also does error check for invalid input of decimals for(unsigned x = 0; x < postfix.length();) { currentChar = postfix[x]; // get the column number for the current character col = Get_FSM_Col(currentChar); // exit if the real number has multiple periods "." // in the expression (i.e: 19.3427.23) if((currentState == REAL) && (col == REAL)) { cerr<<"\nINVALID INPUT #2\n"; exit(1); } /* ======================================================== THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE USING THE "col" VARIABLE FROM ABOVE ^ ========================================================= */ // get the current state of our machine currentState = stateTable[currentState][col]; /* =================================================== THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE - If the current state in our machine == REJECT (the starting state), then we have sucessfully parsed a token, which is returned to its caller - ELSE we continue trying to find a sucessful token =================================================== */ if(currentState == REJECT) { if(currentToken != " ") // we dont care about whitespace { tokens.push_back(currentToken); } currentToken = ""; } else { currentToken += currentChar; ++x; } } // this ensures the last token gets saved when // we reach the end of the postfix string buffer if(currentToken != " ") // we dont care about whitespace { tokens.push_back(currentToken); } return tokens; }// end of Lexer int Get_FSM_Col(char& currentChar) {// this function determines the state of the type of character being examined // check for whitespace if(isspace(currentChar)) { return SPACE; } // check for integer numbers else if(isdigit(currentChar)) { return INTEGER; } // check for real numbers else if(currentChar == '.') { return REAL; } // check for negative numbers else if(currentChar == '~') { currentChar = '-'; return NEGATIVE; } // check for math operators else if(IsMathOperator(currentChar)) { return OPERATOR; } return UNKNOWN; }// end of Get_FSM_Col double EvaluatePostfix(const vector<string>& postfix) {// this function evaluates a postfix expression // declare function variables double op1 = 0; double op2 = 0; double answer = 0; stack<double> doubleStack; cout<<"\nCalculations:\n"; // loop thru array until there is no more data for(unsigned x = 0; x < postfix.size(); ++x) { // push numbers onto the stack if((isdigit(postfix[x])) || (postfix[x] == '.')) { doubleStack.push(atof(postfix[x].c_str())); } // push negative numbers onto the stack else if((postfix[x].length() > 1) && ((postfix[x] == '-') && (isdigit(postfix[x]) || (postfix[x] == '.')))) { doubleStack.push(atof(postfix[x].c_str())); } // if expression is a math operator, pop numbers from stack // & send the popped numbers to the 'Calculate' function else if(IsMathOperator(postfix[x]) && (!doubleStack.empty())) { char token = tolower(postfix[x]); // if expression is square root, sin, cos, // or tan operation only pop stack once if(token == '\$' || token == 's' || token == 'c' || token == 't') { op2 = 0; op1 = doubleStack.top(); doubleStack.pop(); answer = Calculate(token, op1, op2); doubleStack.push(answer); } else if(doubleStack.size() > 1) { op2 = doubleStack.top(); doubleStack.pop(); op1 = doubleStack.top(); doubleStack.pop(); answer = Calculate(token, op1, op2); doubleStack.push(answer); } } else // this should never execute, & if it does, something went really wrong { cout<<"\nINVALID INPUT #3\n"; exit(1); } } // pop the final answer from the stack, and return to main if(!doubleStack.empty()) { answer = doubleStack.top(); } return answer; }// end of EvaluatePostfix double Calculate(char token, double op1, double op2) {// this function carries out the actual math process double ans = 0; switch(tolower(token)) { case '+': cout<<op1<<token<<op2<<" = "; ans = op1 + op2; break; case '-': cout<<op1<<token<<op2<<" = "; ans = op1 - op2; break; case '*': cout<<op1<<token<<op2<<" = "; ans = op1 * op2; break; case '/': cout<<op1<<token<<op2<<" = "; ans = op1 / op2; break; case '%': cout<<op1<<token<<op2<<" = "; ans = ((int)op1%(int)op2)+modf(op1 , &op2); break; case '^': cout<<op1<<token<<op2<<" = "; ans = pow(op1, op2); break; case '\$': cout<<char(251)<<op1<<" = "; ans = sqrt(op1); break; case 'c': cout<<"cos("<<op1<<") = "; ans = cos(op1); break; case 's': cout<<"sin("<<op1<<") = "; ans = sin(op1); break; case 't': cout<<"tan("<<op1<<") = "; ans = tan(op1); break; default: ans = 0; break; } cout<<ans<<endl; return ans; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454 // ============================================================================//   Author:  K Perkins//   Taken From: http://programmingnotes.org///   Date:  Jan 31, 2014//   File: InToPostEval.cpp//   Description: The following demonstrates the implementation of an infix to//     postfix converter and evaluator. Using a Finite State Machine, this//     program has the ability to convert and evaluate multi digit, decimal,//     negative and positive values.// ============================================================================#include <iostream>#include <cstdlib>#include <cmath>#include <cctype>#include <string>#include <vector>#include <stack>using namespace std; /* This holds the transition states for our Finite State Machine    -- They are placed in numerical order for easy understanding within     the FSM array, which is located below */ enum FSM_TRANSITIONS{    REJECT = 0,    INTEGER,    REAL,    NEGATIVE,    OPERATOR,    UNKNOWN,    SPACE}; /* This is the Finite State Machine    -- The zero represents a place holder, so the row in the array         starts on row 1 instead of 0                            integer,  real,  negative, operator, unknown, space */int stateTable[] = {{0, INTEGER,  REAL, NEGATIVE, OPERATOR,  UNKNOWN,  SPACE},/* STATE 1 */   {INTEGER,  INTEGER,  REAL,   REJECT,  REJECT,   REJECT,  REJECT},/* STATE 2 */   {REAL,       REAL,  REJECT,  REJECT,  REJECT,   REJECT,  REJECT},/* STATE 3 */   {NEGATIVE, INTEGER,  REAL,   REJECT,  REJECT,   REJECT,  REJECT},/* STATE 4 */   {OPERATOR,  REJECT, REJECT,  REJECT,  REJECT,   REJECT,  REJECT},/* STATE 5 */   {UNKNOWN,   REJECT, REJECT,  REJECT,  REJECT,   UNKNOWN, REJECT},/* STATE 6 */   {SPACE,     REJECT, REJECT,  REJECT,  REJECT,   REJECT,  REJECT}}; // function prototypesvoid DisplayDirections();string ConvertInfixToPostfix(string infix);bool IsMathOperator(char token);int OrderOfOperations(char token);vector<string> Lexer(string postfix);int Get_FSM_Col(char& currentChar);double EvaluatePostfix(const vector<string>& postfix);double Calculate(char token, double op1, double op2); int main(){    // declare variables    string infix = "";    string postfix = "";    double answer = 0;    vector<string> tokens;     // display directions to user    DisplayDirections();     // get data from user    cout<<"\nPlease enter an Infix expression: ";    getline(cin, infix);     postfix = ConvertInfixToPostfix(infix);     // use the "Lexer" function to isolate multi digit, negative and decimal    // numbers, aswell as single digit numbers and math operators    tokens = Lexer(postfix);     // display the found tokens to the screen// for(unsigned x = 0; x < tokens.size(); ++x)// {//     cout<<tokens.at(x)<<endl;// }     cout <<"\nThe Infix expression = "<<infix;    cout <<"\nThe Postfix expression = "<<postfix<<endl;     answer = EvaluatePostfix(tokens);     cout<<"\nFinal answer = "<<answer<<endl;     return 0;}// end of main void DisplayDirections(){// this function displays instructions to the screen    cout << "\n==== Infix To Postfix Conversion & Evaluation ====\n"        <<"\nMath Operators:\n"        <<"+ || Addition\n"        <<"- || Subtraction\n"        <<"* || Multiplication\n"        <<"/ || Division\n"        <<"% || Modulus\n"        <<"^ || Power\n"        <<"\$ || Square Root\n"        <<"s || Sine\n"        <<"c || Cosine\n"        <<"t || Tangent\n"        <<"~ || Negative Number\n"        <<"Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))\n";        // ((sin(-4^5)*1.4)/(sqrt(23+2)--2.8))*(cos(1%2)/(7.28*.1987)^(tan(23)))}// end of DisplayDirections string ConvertInfixToPostfix(string infix){// this function converts an infix expression to postfix    // declare function variables    string postfix;    stack<char> charStack;     // loop thru array until there is no more data    for(unsigned x = 0; x < infix.length(); ++x)    {        // place numbers (standard, decimal, & negative)        // numbers onto the 'postfix' string        if((isdigit(infix[x])) || (infix[x] == '.') || (infix[x] == '~'))        {            postfix += infix[x];        }        else if(isspace(infix[x]))        {            continue;        }        else if(IsMathOperator(infix[x]))        {            postfix += " ";            // use the 'OrderOfOperations' function to check equality            // of the math operator at the top of the stack compared to            // the current math operator in the infix string            while((!charStack.empty()) &&                (OrderOfOperations(charStack.top()) >= OrderOfOperations(infix[x])))            {                // place the math operator from the top of the                // stack onto the postfix string and continue the                // process until complete                postfix += charStack.top();                charStack.pop();            }            // push the remaining math operator onto the stack            charStack.push(infix[x]);        }        // push outer parentheses onto stack        else if(infix[x] == '(')        {            charStack.push(infix[x]);        }        else if(infix[x] == ')')        {            // pop the current math operator from the stack            while((!charStack.empty()) && (charStack.top() != '('))            {                // place the math operator onto the postfix string                postfix += charStack.top();                // pop the next operator from the stack and                // continue the process until complete                charStack.pop();            }             if(!charStack.empty()) // pop '(' symbol off the stack            {                charStack.pop();            }            else // no matching '('            {                cout<<"\nPARENTHESES MISMATCH #1\n";                exit(1);            }        }        else        {            cout<<"\nINVALID INPUT #1\n";            exit(1);        }    }     // place any remaining math operators from the stack onto    // the postfix array    while(!charStack.empty())    {        postfix += charStack.top();        charStack.pop();    }     return postfix;}// end of ConvertInfixToPostfix bool IsMathOperator(char token){// this function checks if operand is a math operator    switch(tolower(token))    {        case '+': case '-': case '*': case '/':        case '%': case '^': case '\$': case 'c':        case 's': case 't':            return true;            break;        default:           return false;           break;    }}// end of IsMathOperator int OrderOfOperations(char token){// this function returns the priority of each math operator    int priority = 0;    switch(tolower(token))    {        case 'c': case 's': case 't':           priority = 5;           break;        case '^': case '\$':           priority = 4;           break;        case '*': case '/': case '%':           priority = 3;           break;        case '-':           priority = 2;           break;        case '+':           priority = 1;           break;    }    return priority;}// end of OrderOfOperations vector<string> Lexer(string postfix){// this function parses a postfix string using an FSM to generate //  each individual token in the expression    vector<string> tokens;    char currentChar = ' ';    int col = REJECT;    int currentState = REJECT;    string currentToken = "";     // use an FSM to parse multidigit and decimal numbers    // also does error check for invalid input of decimals    for(unsigned x = 0; x < postfix.length();)    {        currentChar = postfix[x];         // get the column number for the current character        col = Get_FSM_Col(currentChar);         // exit if the real number has multiple periods "."        // in the expression (i.e: 19.3427.23)        if((currentState == REAL) && (col == REAL))        {            cerr<<"\nINVALID INPUT #2\n";            exit(1);        }        /* ========================================================             THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE               USING THE "col" VARIABLE FROM ABOVE ^           ========================================================= */         // get the current state of our machine        currentState = stateTable[currentState][col];         /* ===================================================           THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE           - If the current state in our machine == REJECT             (the starting state), then we have sucessfully parsed             a token, which is returned to its caller             - ELSE we continue trying to find a sucessful token             =================================================== */        if(currentState == REJECT)        {            if(currentToken != " ") // we dont care about whitespace            {                tokens.push_back(currentToken);            }            currentToken = "";        }        else        {            currentToken += currentChar;            ++x;        }     }    // this ensures the last token gets saved when    // we reach the end of the postfix string buffer    if(currentToken != " ") // we dont care about whitespace    {        tokens.push_back(currentToken);    }    return tokens;}// end of Lexer int Get_FSM_Col(char& currentChar){// this function determines the state of the type of character being examined    // check for whitespace    if(isspace(currentChar))    {        return SPACE;    }     // check for integer numbers    else if(isdigit(currentChar))    {        return INTEGER;    }     // check for real numbers    else if(currentChar == '.')    {        return REAL;    }     // check for negative numbers    else if(currentChar == '~')    {        currentChar = '-';        return NEGATIVE;    }     // check for math operators    else if(IsMathOperator(currentChar))    {        return OPERATOR;    }    return UNKNOWN;}// end of Get_FSM_Col double EvaluatePostfix(const vector<string>& postfix){// this function evaluates a postfix expression    // declare function variables    double op1 = 0;    double op2 = 0;    double answer = 0;    stack<double> doubleStack;     cout<<"\nCalculations:\n";     // loop thru array until there is no more data    for(unsigned x = 0; x < postfix.size(); ++x)    {        // push numbers onto the stack        if((isdigit(postfix[x])) || (postfix[x] == '.'))        {           doubleStack.push(atof(postfix[x].c_str()));        }        // push negative numbers onto the stack        else if((postfix[x].length() > 1) && ((postfix[x] == '-') &&            (isdigit(postfix[x]) || (postfix[x] == '.'))))        {           doubleStack.push(atof(postfix[x].c_str()));        }        // if expression is a math operator, pop numbers from stack        // & send the popped numbers to the 'Calculate' function        else if(IsMathOperator(postfix[x]) && (!doubleStack.empty()))        {            char token = tolower(postfix[x]);             // if expression is square root, sin, cos,            // or tan operation only pop stack once            if(token == '\$' || token == 's' || token == 'c' || token == 't')            {                op2 = 0;                op1 = doubleStack.top();                doubleStack.pop();                answer = Calculate(token, op1, op2);                doubleStack.push(answer);            }            else if(doubleStack.size() > 1)            {                op2 = doubleStack.top();                doubleStack.pop();                op1 = doubleStack.top();                doubleStack.pop();                answer = Calculate(token, op1, op2);                doubleStack.push(answer);            }        }        else // this should never execute, & if it does, something went really wrong        {           cout<<"\nINVALID INPUT #3\n";           exit(1);        }    }    // pop the final answer from the stack, and return to main    if(!doubleStack.empty())    {        answer = doubleStack.top();    }    return answer;}// end of EvaluatePostfix double Calculate(char token, double op1, double op2){// this function carries out the actual math process    double ans = 0;    switch(tolower(token))    {        case '+':           cout<<op1<<token<<op2<<" = ";           ans = op1 + op2;           break;        case '-':           cout<<op1<<token<<op2<<" = ";           ans = op1 - op2;           break;        case '*':           cout<<op1<<token<<op2<<" = ";           ans = op1 * op2;           break;        case '/':           cout<<op1<<token<<op2<<" = ";           ans = op1 / op2;           break;        case '%':           cout<<op1<<token<<op2<<" = ";           ans = ((int)op1%(int)op2)+modf(op1 , &op2);           break;        case '^':           cout<<op1<<token<<op2<<" = ";           ans = pow(op1, op2);           break;        case '\$':           cout<<char(251)<<op1<<" = ";           ans = sqrt(op1);           break;        case 'c':            cout<<"cos("<<op1<<") = ";            ans = cos(op1);            break;        case 's':            cout<<"sin("<<op1<<") = ";            ans = sin(op1);            break;        case 't':            cout<<"tan("<<op1<<") = ";            ans = tan(op1);            break;        default:           ans = 0;           break;    }    cout<<ans<<endl;    return ans;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

```====== RUN 1 ====== ==== Infix To Postfix Conversion & Evaluation ====```

``` Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: 12/3*9 The Infix expression = 12/3*9 The Postfix expression = 12 3 /9* Calculations: 12/3 = 4 4*9 = 36 Final answer = 36 ====== RUN 2 ====== ==== Infix To Postfix Conversion & Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: ~150.89996 - 87.56643 The Infix expression = ~150.89996 - 87.56643 The Postfix expression = ~150.89996 87.56643- Calculations: -150.9-87.5664 = -238.466 Final answer = -238.466 ====== RUN 3 ====== ==== Infix To Postfix Conversion & Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) The Infix expression = ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) The Postfix expression = ~4 5^ s1.4* 23 2+ \$~2.8-/ 1 2% c7.28 .1987* 23t^/* Calculations: -4^5 = -1024 sin(-1024) = 0.158533 0.158533*1.4 = 0.221947 23+2 = 25 √25 = 5 5--2.8 = 7.8 0.221947/7.8 = 0.0284547 1%2 = 1 cos(1) = 0.540302 7.28*0.1987 = 1.44654 tan(23) = 1.58815 1.44654^1.58815 = 1.79733 0.540302/1.79733 = 0.300614 0.0284547*0.300614 = 0.00855389 Final answer = 0.00855389 ```

## C++ || Snippet – How To Override The Default Signal Handler (CTRL-C) The following is sample code which demonstrates the use of the “signal” function call on Unix based systems.

Signals are interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C. The “signal” function call receives two arguments. The first argument is an integer which represents the signal number, and the second argument is a pointer to the user defined signal handling function.

The following program catches the “SIGINT” signal number using the signal() function.

``` How To Override CTRL-C C++ // ============================================================================ // Author: K Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Signal.cpp // Description: Demonstrate the use of overriding the default signal // handler for the case when the user presses Ctrl-C. Test it by // running and pressing Ctrl-C // ============================================================================ #include <iostream> #include <csignal> #include <unistd.h> using namespace std; // function prototype void SignalHandlerFunc(int arg); // global variable int count = 10; int main() { // overide the default signal handler (CTRL-C) // with our own "SignalHandlerFunc" function signal(SIGINT, SignalHandlerFunc); cerr<<"nPlease press CTRL-Cnn"; // loop until condition is met do{ sleep(1); }while(count > 0); // press ENTER on the keyboard to end // the program once all "lives" are lost cin.get(); return 0; }// end of main /** * This function handles the signal * @param arg - the signal number */ void SignalHandlerFunc(int arg) { // display text when user presses CTRL-C if(count > 0) { cerr<<" Haha I have "<<count<<" lives!n"; } else { cerr<<" ** Ahh you got me...n"; } --count; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 // ============================================================================//     Author: K Perkins//     Date:   Oct 3, 2013//     Taken From: http://programmingnotes.org///     File:  Signal.cpp//     Description: Demonstrate the use of overriding the default signal //       handler for the case when the user presses Ctrl-C. Test it by //       running and pressing Ctrl-C// ============================================================================#include <iostream>#include <csignal>#include <unistd.h>using namespace std; // function prototypevoid SignalHandlerFunc(int arg); // global variableint count = 10; int main(){    // overide the default signal handler (CTRL-C)    // with our own "SignalHandlerFunc" function    signal(SIGINT, SignalHandlerFunc);     cerr<<"nPlease press CTRL-Cnn";     // loop until condition is met    do{        sleep(1);    }while(count > 0);     // press ENTER on the keyboard to end    // the program once all "lives" are lost    cin.get();     return 0;}// end of main /** * This function handles the signal * @param arg - the signal number */void SignalHandlerFunc(int arg){    // display text when user presses CTRL-C    if(count > 0)    {        cerr<<" Haha I have "<<count<<" lives!n";    }    else    {        cerr<<" ** Ahh you got me...n";    }    --count;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output:

`Please press CTRL-C`

``` ```

```^C Haha I have 10 lives! ^C Haha I have 9 lives! ^C Haha I have 8 lives! ^C Haha I have 7 lives! ^C Haha I have 6 lives! ^C Haha I have 5 lives! ^C Haha I have 4 lives! ^C Haha I have 3 lives! ^C Haha I have 2 lives! ^C Haha I have 1 lives! ^C ** Ahh you got me... ```

## C++ || Snippet – How To Convert A Decimal Number Into Binary This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 26 was entered into the program, it would display the converted binary value of 11010.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```How To Count In Binary The "Long" Datatype - What Is It? While Loops Online Binary to Decimal Converter - Verify For Correct Results How To Reverse A String ```

If you are looking for sample code which converts binary to decimal, check back here soon!

``` Convert A Decimal Number Into Binary C++ #include <iostream> #include <string> #include <algorithm> using namespace std; // function prototype string DecToBin(long long decNum); int main() { // declare variables long long decNum = 0; string binaryNum=""; // use a string instead of an int to avoid // overflow, because binary numbers can grow large quick cout<<"Please enter an integer value: "; cin >> decNum; if(decNum < 0) { binaryNum = "-"; } // call function to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user cout<<"nThe integer value of "<<decNum<<" = "<<binaryNum<<" in binary"<<endl; return 0; } string DecToBin(long long decNum) { string binary = ""; // use this string to save the binary number if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2)+'0'; // convert int to char decNum /= 2; } // reverse the string reverse(binary.begin(), binary.end()); return binary; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 #include <iostream>#include <string>#include <algorithm> using namespace std; // function prototypestring DecToBin(long long decNum); int main(){ // declare variables long long decNum = 0; string binaryNum=""; // use a string instead of an int to avoid   // overflow, because binary numbers can grow large quick  cout<<"Please enter an integer value: "; cin >> decNum;  if(decNum < 0) { binaryNum = "-"; }  // call function to convert decimal to binary binaryNum += DecToBin(decNum);  // display data to user cout<<"nThe integer value of "<<decNum<<" = "<<binaryNum<<" in binary"<<endl;  return 0;} string DecToBin(long long decNum){ string binary = ""; // use this string to save the binary number  if(decNum < 0) // if input is a neg number, make it positive {               decNum *= -1; }                     // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2)+'0'; // convert int to char decNum /= 2; }  // reverse the string reverse(binary.begin(), binary.end());  return binary;}// http://programmingnotes.org/ ```

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled 3 separate times to display different output

`====== RUN 1 ======`

``` Please enter an integer value: 1987 The integer value of 1987 = 11111000011 in binary ====== RUN 2 ====== Please enter an integer value: -26 The integer value of -26 = -11010 in binary ====== RUN 3 ====== Please enter an integer value: 12345678910 ```

```The integer value of 12345678910 = 1011011111110111000001110000111110 in binary ```

## C++ || Snippet – Simple Linked List Using Delete, Insert, & Display Functions The following is sample code for a simple linked list, which implements the following functions: “Delete, Insert, and Display.”

The sample code provided on this page is a stripped down version of a more robust linked list class which was previously discussed on this site. Sample code for that can be found here.

It is recommended you check that out as the functions implemented within that class are very useful.

``` Simple Linked List C++ // ============================================================================ // Author: K Perkins // Date: Aug 18, 2012 // Taken From: http://programmingnotes.org/ // File: SimpleList.cpp // Description: Demonstrates the use of a simple linked list. // ============================================================================ #include <iostream> #include <string> using namespace std; struct node { /* -- you can use different data types here -- instead of just a string char letter; int number; double fNumber; */ string name; node* next; }; // global variables // this is the front of the list node* head = NULL; // function prototype void Insert(string info); void Delete(string info); void Display(); void DestroyList(); int main() { // if you want to insert data into the list // this is one way you can do it, using a 'temp' pointer node* temp = new node; temp-> name = "My Programming Notes"; temp-> next = NULL; // set the head node to the data thats in the 'temp' pointer head = temp; // display data to the screen cout << head->name <<endl<<endl; // use the insert function to add new data to the list // NOTE: you could have also used the 'insert' function ^ above // to place data into the list Insert("Is An Awesome Site!"); // insert more data into the list Insert("August"); Display(); // delete the selected text from the list Delete("August"); Display(); // destroy the current pointers in the list // after you are finished using them DestroyList(); return 0; }// end of main void Insert(string info) { node* newItem = new node; newItem-> name = info; newItem-> next = NULL; // if the list is empty, add new item to the front if(head == NULL) { head = newItem; } else // if the list isnt empty, add new item to the end { node* iter = head; while(iter->next != NULL) { iter = iter-> next; } iter-> next = newItem; } }// end of Insert void Delete(string info) { node* iter = head; // if the list is empty, do nothing if(head == NULL) { return; } // delete the first item in the list else if(head->name == info) { head = head-> next; delete iter; } // search the list until we find the desired item else { while(iter->next != NULL) { if(iter->next->name == info) { node* deleteNode = iter->next; iter-> next = iter-> next-> next; delete deleteNode; break; } iter = iter->next; } } }// end of Delete void Display() { node* iter = head; // traverse thru the list, displaying the // text at each node location while(iter != NULL) { cout<<iter->name<<endl; iter = iter-> next; } cout<<endl; }// end of Display void DestroyList() { if(head != NULL) { cout << "nnDestroying nodes...n"; while(head != NULL) { node* temp = head; cout << temp-> name << 'n'; head = head-> next; delete temp; } } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 // ============================================================================//     Author: K Perkins//     Date:   Aug 18, 2012//     Taken From: http://programmingnotes.org///     File:  SimpleList.cpp//     Description: Demonstrates the use of a simple linked list.// ============================================================================#include <iostream>#include <string>using namespace std; struct node{ /* -- you can use different data types here      -- instead of just a string char letter; int number; double fNumber; */ string name; node* next;}; // global variables// this is the front of the listnode* head = NULL; // function prototypevoid Insert(string info);void Delete(string info);void Display();void DestroyList(); int main(){    // if you want to insert data into the list    // this is one way you can do it, using a 'temp' pointer    node* temp = new node;    temp-> name = "My Programming Notes";    temp-> next = NULL;     // set the head node to the data thats in the 'temp' pointer    head = temp;     // display data to the screen    cout << head->name <<endl<<endl;     // use the insert function to add new data to the list    // NOTE: you could have also used the 'insert' function ^ above    // to place data into the list    Insert("Is An Awesome Site!");     // insert more data into the list    Insert("August");    Display();     // delete the selected text from the list    Delete("August");    Display();     // destroy the current pointers in the list    // after you are finished using them    DestroyList();     return 0;}// end of main void Insert(string info){    node* newItem = new node;    newItem-> name = info;    newItem-> next = NULL;     // if the list is empty, add new item to the front    if(head == NULL)    {        head = newItem;    }    else // if the list isnt empty, add new item to the end    {        node* iter = head;        while(iter->next != NULL)        {            iter = iter-> next;        }        iter-> next = newItem;    }}// end of Insert void Delete(string info){    node* iter = head;     // if the list is empty, do nothing    if(head == NULL)    {        return;    }    // delete the first item in the list    else if(head->name == info)    {        head = head-> next;        delete iter;    }    // search the list until we find the desired item    else    {        while(iter->next != NULL)        {            if(iter->next->name == info)            {                node* deleteNode = iter->next;                iter-> next = iter-> next-> next;                delete deleteNode;                break;            }            iter = iter->next;        }    }}// end of Delete void Display(){    node* iter = head;    // traverse thru the list, displaying the    // text at each node location    while(iter != NULL)    {        cout<<iter->name<<endl;        iter = iter-> next;    }    cout<<endl;}// end of Display void DestroyList(){    if(head != NULL)    {        cout << "nnDestroying nodes...n";        while(head != NULL)        {            node* temp = head;            cout << temp-> name << 'n';            head = head-> next;            delete temp;        }    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

`My Programming Notes`

``` My Programming Notes Is An Awesome Site! August [DELETE THE TEXT "AUGUST"] My Programming Notes Is An Awesome Site! ```

```Destroying nodes... My Programming Notes Is An Awesome Site! ```

## C++ || Snippet – Custom Template Linked List Sample Code This page will consist of sample code for a singly linked list, which is loosely based on the built in C++ “List” library. Provided in the linked list class are the following functions:

``` * PushFront - Adds new item to the front of the list (LIFO) * PushBack - Adds new item to the back of the list (FIFO) * PopFront - Returns & removes first item from the list * PopBack - Returns & removes last item from the list * Front - Returns (but does not delete) the first item from the list * Back - Returns (but does not delete) the last item from the list * Delete - Searches and deletes the requested item * Display - Display all the current contents in the list * Replace - Replaces existing item from the list with a new item If existing item cannot be found, the new item is added to the back of the list * InsertBefore - Inserts new item before the existing item. If existing item cannot be found, the new item is added to the back of the list * InsertAfter - Inserts new item after the existing item. If existing item cannot be found, the new item is added to the back of the list * InsertInOrder - Inserts new item in numerical order, from lowest to highest * Size - Return the current size of the list * MakeEmpty - Initializes the list to an empty state 123456789101112131415161718192021222324252627282930 * PushFront - Adds new item to the front of the list (LIFO) * PushBack - Adds new item to the back of the list (FIFO) * PopFront - Returns & removes first item from the list * PopBack - Returns & removes last item from the list * Front - Returns (but does not delete) the first item from the list * Back - Returns (but does not delete) the last item from the list * Delete - Searches and deletes the requested item * Display - Display all the current contents in the list * Replace - Replaces existing item from the list with a new item            If existing item cannot be found, the new item is added to the back of the list * InsertBefore - Inserts new item before the existing item.                 If existing item cannot be found, the new item is added to the back of the list * InsertAfter - Inserts new item after the existing item.                 If existing item cannot be found, the new item is added to the back of the list * InsertInOrder - Inserts new item in numerical order, from lowest to highest * Size - Return the current size of the list * MakeEmpty - Initializes the list to an empty state ```

From the following, the functions of interest to look out for are the “Delete, Display, Replace, InsertBefore, InsertAfter, and InsertInOrder” functions as they are typically used as programming assignments in many C++ Data structures courses to further demonstrate how linked lists operate.

``` #include 'LinkedList.h' C++ // ============================================================================ // Author: K Perkins // Date: Jul 26, 2012 // Taken From: http://programmingnotes.org/ // File: LinkedList.h // Description: This is a class which implements various functions which // demonstrates the use of a Linked List. // ============================================================================ #include <iostream> using namespace std; template <class ItemType> class LinkedList { public: LinkedList(); /* Function: Constructor initializes list Precondition: None Postcondition: Defines private variables */ bool IsEmpty(); /* Function: Determines whether queue is empty Precondition: List has been created Postcondition: The function = true if the list is empty and the function = false if list is not empty */ void PushFront(ItemType item); /* Function: Adds new item to the front of the list (LIFO) Precondition: List has been created and is not full Postcondition: Item is in the list */ void PushBack(ItemType item); /* Function: Adds new item to the back of the list (FIFO) Precondition: List has been created and is not full Postcondition: Item is in the list */ ItemType PopFront(); /* Function: Returns & removes first item from the last Precondition: List has been initialized Postcondition: The first item in the list is removed */ ItemType PopBack(); /* Function: Returns & removes last item from the list Precondition: List has been initialized Postcondition: The last item in the list is removed */ ItemType Front(); /* Function: Returns (but does not delete) the first item from the list Precondition: List has been initialized Postcondition: The first item in the list is removed */ ItemType Back(); /* Function: Returns (but does not delete) the last item from the list Precondition: List has been initialized Postcondition: The last item in the list is removed */ void Delete(ItemType item); /* Function: Searches and deletes the requested item Precondition: List has been created and is not empty Postcondition: Item removed from the list */ void Display(); /* Function: Display all the current contents in the list Precondition: List has been created and is not empty Postcondition: List is displayed to the screen */ void Replace(ItemType initial, ItemType replace); /* Function: Replaces existing item from the list with a new item Precondition: List has been created and is not empty Postcondition: Initial item is replaced with the new one */ void InsertBefore(ItemType initial, ItemType newItem); /* Function: Inserts new item before the existing item Precondition: List has been created and is not empty Postcondition: New item is inserted before the existing item */ void InsertAfter(ItemType initial, ItemType newItem); /* Function: Inserts new item after the existing item Precondition: List has been created and is not empty Postcondition: New item is inserted after the existing item */ void InsertInOrder(ItemType item); /* Function: Inserts new item in numerical order, from lowest to highest Precondition: List has been created and is not empty Postcondition: The list is sorted in numerical order */ int Size(); /* Function: Return the current size of the list Precondition: List has been initialized Postcondition: The size of the list is returned */ void MakeEmpty(); /* Function: Initializes the list to an empty state Precondition: List has been created Postcondition: List no longer exists */ ~LinkedList(); /* Function: Deletes all the items in the list Precondition: List has been declared Postcondition: List no longer exists */ private: struct node { ItemType info; node* next; }; node* head; int size; }; //========================= Implementation ================================// template <class ItemType> LinkedList<ItemType>::LinkedList() { head = NULL; size = 0; }// end of LinkedList template <class ItemType> bool LinkedList<ItemType>::IsEmpty() { return (head==NULL); }// end of IsEmpty template <class ItemType> void LinkedList<ItemType>::PushFront(ItemType item) { // LIFO node* temp = new node; temp-> info = item; temp-> next = head; head = temp; ++size; }// end of PushFront template <class ItemType> void LinkedList<ItemType>::PushBack(ItemType item) { // FIFO node* temp = new node; temp->info = item; temp->next = NULL; if(IsEmpty()) { head=temp; } else { node* temp2 = head; while(temp2->next!=NULL) { temp2=temp2->next; } temp2->next=temp; } ++size; }// end of PushBack template <class ItemType> ItemType LinkedList<ItemType>::PopFront() { if(IsEmpty()) { cout<<"nLIST EMPTYn"; } else { ItemType item = head-> info; node* temp = head; head = head-> next; delete temp; --size; return item; } }// end of PopFront template <class ItemType> ItemType LinkedList<ItemType>::PopBack() { if(IsEmpty()) { cout<<"nLIST EMPTYn"; } else if(size == 1) { ItemType item = PopFront(); return item; } else { node* temp = head; ItemType item; while(temp->next != NULL) { if(temp->next->next==NULL) { node* temp2=temp->next; temp->next=temp->next->next; item = temp2-> info; delete temp2; break; } temp=temp->next; } --size; return item; } }// end of PopBack template <class ItemType> ItemType LinkedList<ItemType>::Front() { if(IsEmpty()) { cout<<"nLIST EMPTYn"; } else { return head-> info; } }// end of Front template <class ItemType> ItemType LinkedList<ItemType>::Back() { if(IsEmpty()) { cout<<"nLIST EMPTYn"; } else { node* temp = head; while(temp->next != NULL) { temp = temp-> next; } ItemType item = temp-> info; return item; } }// end of Back template <class ItemType> void LinkedList<ItemType>::Delete(ItemType item) { node* temp=head; if(IsEmpty()) { return; } else if(temp->info==item) { head=head->next; delete temp; --size; } else { while(temp->next!=NULL) { if(temp->next->info==item) { node* temp2=temp->next; temp->next=temp->next->next; delete temp2; --size; break; } temp=temp->next; } } }// end of Delete template <class ItemType> void LinkedList<ItemType>::Display() { node* temp=head; while(temp!=NULL) { cout<<temp->info<<endl; temp=temp->next; } }// end of Display template <class ItemType> void LinkedList<ItemType>::Replace(ItemType initial, ItemType replace) { node* temp=head; if(IsEmpty()) { PushFront(replace); } else if(temp->info==initial) { temp->info=replace; } else { while(temp->next!=NULL) { if(temp->info==initial) { temp->info=replace; break; } temp=temp->next; } if(temp->next==NULL) { PushBack(replace); } } }// end of Replace template <class ItemType> void LinkedList<ItemType>::InsertBefore(ItemType initial, ItemType newItem) { node* temp=head; node* temp2=new node; temp2->info=initial; temp2->next=NULL; if(IsEmpty()) { PushFront(newItem); } else if(temp->info==initial) { temp->info=newItem; temp2->next=temp->next; temp->next=temp2; ++size; } else { while(temp->next!=NULL) { if(temp->info==initial) { temp->info=newItem; temp2->next=temp->next; temp->next=temp2; ++size; break; } temp=temp->next; } if(temp->next==NULL) { PushBack(newItem); } } }// end of InsertBefore template <class ItemType> void LinkedList<ItemType>::InsertAfter(ItemType initial, ItemType newItem) { node* temp=head; node* temp2=new node; temp2->info=newItem; temp2->next=NULL; if(IsEmpty()) { PushFront(newItem); } else if(temp->info==initial) { temp2->next=temp->next; temp->next=temp2; ++size; } else { while(temp->next!=NULL) { if(temp->info==initial) { temp2->next=temp->next; temp->next=temp2; ++size; break; } temp=temp->next; } if(temp->next==NULL) { PushBack(newItem); } } }// end of InsertAfter template <class ItemType> void LinkedList<ItemType>::InsertInOrder(ItemType item) { if(IsEmpty()) { PushFront(item); } else { node* temp=head; node* temp2=new node; if(item <=(temp->info)) { ItemType placeHolder=temp->info; temp2->info=placeHolder; temp->info=item; temp2->next=temp->next; temp->next=temp2; ++size; } else { while(temp->next!=NULL) { if(((temp->info) <= item) && (item <= (temp->next->info))) { temp2->info=item; temp2->next=temp->next; temp->next=temp2; ++size; return; } temp=temp->next; } if(temp->next==NULL) { PushBack(item); } } } }// end of InsertInOrder template <class ItemType> int LinkedList<ItemType>::Size() { if(IsEmpty()) { cout<<"nLIST EMPTYn"; } return size; }// end of Size template <class ItemType> void LinkedList<ItemType>::MakeEmpty() { if(!IsEmpty()) { cout << "nnDestroying nodes...n"; while(!IsEmpty()) { node* temp = head; //cout << temp-> info << 'n'; head = head-> next; delete temp; } size = 0; } }// end of MakeEmpty template <class ItemType> LinkedList<ItemType>::~LinkedList() { MakeEmpty(); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453 // ============================================================================//     Author: K Perkins//     Date:   Jul 26, 2012//     Taken From: http://programmingnotes.org///     File:  LinkedList.h//     Description: This is a class which implements various functions which//          demonstrates the use of a Linked List. // ============================================================================#include <iostream>using namespace std; template <class ItemType>class LinkedList{public:    LinkedList(); /*   Function: Constructor initializes list Precondition: None Postcondition: Defines private variables */    bool IsEmpty(); /*   Function: Determines whether queue is empty Precondition: List has been created Postcondition: The function = true if the list is empty and the function = false if list is not empty */    void PushFront(ItemType item); /*   Function: Adds new item to the front of the list (LIFO) Precondition:  List has been created and is not full Postcondition: Item is in the list */    void PushBack(ItemType item); /*   Function: Adds new item to the back of the list (FIFO) Precondition:  List has been created and is not full Postcondition: Item is in the list */    ItemType PopFront(); /*   Function: Returns & removes first item from the last Precondition: List has been initialized Postcondition: The first item in the list is removed */    ItemType PopBack(); /*   Function: Returns & removes last item from the list Precondition: List has been initialized Postcondition: The last item in the list is removed */    ItemType Front(); /*   Function: Returns (but does not delete) the first item from the list Precondition: List has been initialized Postcondition: The first item in the list is removed */    ItemType Back(); /*   Function: Returns (but does not delete) the last item from the list Precondition: List has been initialized Postcondition: The last item in the list is removed */    void Delete(ItemType item); /*   Function: Searches and deletes the requested item Precondition:  List has been created and is not empty Postcondition: Item removed from the list */    void Display(); /*   Function: Display all the current contents in the list Precondition:  List has been created and is not empty Postcondition: List is displayed to the screen */    void Replace(ItemType initial, ItemType replace); /*   Function: Replaces existing item from the list with a new item Precondition:  List has been created and is not empty Postcondition: Initial item is replaced with the new one */    void InsertBefore(ItemType initial, ItemType newItem); /*   Function: Inserts new item before the existing item Precondition:  List has been created and is not empty Postcondition: New item is inserted before the existing item */    void InsertAfter(ItemType initial, ItemType newItem); /*   Function: Inserts new item after the existing item Precondition:  List has been created and is not empty Postcondition: New item is inserted after the existing item */ void InsertInOrder(ItemType item);   /*   Function: Inserts new item in numerical order, from lowest to highest Precondition:  List has been created and is not empty Postcondition: The list is sorted in numerical order */ int Size(); /*   Function: Return the current size of the list Precondition: List has been initialized Postcondition: The size of the list is returned */ void MakeEmpty(); /*   Function: Initializes the list to an empty state Precondition: List has been created Postcondition: List no longer exists */    ~LinkedList(); /*   Function: Deletes all the items in the list Precondition: List has been declared Postcondition: List no longer exists */ private:    struct node    {        ItemType info;        node* next;    };    node* head;     int size;}; //=========================  Implementation  ================================// template <class ItemType>LinkedList<ItemType>::LinkedList(){    head = NULL;    size = 0;}// end of LinkedList template <class ItemType>bool LinkedList<ItemType>::IsEmpty(){    return (head==NULL);}// end of IsEmpty template <class ItemType>void LinkedList<ItemType>::PushFront(ItemType item){    // LIFO     node* temp = new node;    temp-> info = item;    temp-> next = head;    head = temp;    ++size;}// end of PushFront template <class ItemType>void LinkedList<ItemType>::PushBack(ItemType item){    // FIFO    node* temp = new node;    temp->info = item;    temp->next = NULL;        if(IsEmpty())    {        head=temp;    }    else    {        node* temp2 = head;                while(temp2->next!=NULL)        {            temp2=temp2->next;        }        temp2->next=temp;    }    ++size;}// end of PushBack template <class ItemType>ItemType LinkedList<ItemType>::PopFront(){    if(IsEmpty())    {        cout<<"nLIST EMPTYn";    }    else    {          ItemType item = head-> info;          node* temp = head;        head = head-> next;        delete temp;        --size;        return item;    }}// end of PopFront template <class ItemType>ItemType LinkedList<ItemType>::PopBack(){    if(IsEmpty())    {        cout<<"nLIST EMPTYn";    }    else if(size == 1)    {        ItemType item = PopFront();        return item;    }    else    {        node* temp = head;        ItemType item;        while(temp->next != NULL)        {            if(temp->next->next==NULL)            {                node* temp2=temp->next;                temp->next=temp->next->next;                item = temp2-> info;                delete temp2;                break;            }            temp=temp->next;        }        --size;        return item;    } }// end of PopBack template <class ItemType>ItemType LinkedList<ItemType>::Front(){    if(IsEmpty())    {        cout<<"nLIST EMPTYn";    }    else    {         return head-> info;    }}// end of Front template <class ItemType>ItemType LinkedList<ItemType>::Back() {    if(IsEmpty())    {        cout<<"nLIST EMPTYn";    }    else    {        node* temp = head;         while(temp->next != NULL)        {            temp = temp-> next;        }        ItemType item = temp-> info;        return item;    } }// end of Back template <class ItemType>void LinkedList<ItemType>::Delete(ItemType item){    node* temp=head;    if(IsEmpty())    {        return;    }    else if(temp->info==item)    {        head=head->next;        delete temp;        --size;    }    else    {        while(temp->next!=NULL)        {            if(temp->next->info==item)            {                node* temp2=temp->next;                temp->next=temp->next->next;                delete temp2;                --size;                break;            }            temp=temp->next;        }    }}// end of Delete template <class ItemType>void LinkedList<ItemType>::Display(){    node* temp=head;    while(temp!=NULL)    {        cout<<temp->info<<endl;        temp=temp->next;    }}// end of Display template <class ItemType>void LinkedList<ItemType>::Replace(ItemType initial, ItemType replace){    node* temp=head;    if(IsEmpty())    {        PushFront(replace);    }    else if(temp->info==initial)    {        temp->info=replace;    }    else    {                while(temp->next!=NULL)        {            if(temp->info==initial)            {                temp->info=replace;                break;            }            temp=temp->next;        }        if(temp->next==NULL)        {            PushBack(replace);        }    }}// end of Replace template <class ItemType>void LinkedList<ItemType>::InsertBefore(ItemType initial, ItemType newItem){    node* temp=head;    node* temp2=new node;    temp2->info=initial;    temp2->next=NULL;             if(IsEmpty())    {        PushFront(newItem);    }    else if(temp->info==initial)    {        temp->info=newItem;         temp2->next=temp->next;        temp->next=temp2;        ++size;    }    else    {        while(temp->next!=NULL)        {            if(temp->info==initial)            {                temp->info=newItem;                 temp2->next=temp->next;                temp->next=temp2;                ++size;                break;            }            temp=temp->next;                   }        if(temp->next==NULL)        {            PushBack(newItem);        }    }}// end of InsertBefore template <class ItemType>void LinkedList<ItemType>::InsertAfter(ItemType initial, ItemType newItem){    node* temp=head;    node* temp2=new node;    temp2->info=newItem;    temp2->next=NULL;        if(IsEmpty())    {        PushFront(newItem);    }    else if(temp->info==initial)    {        temp2->next=temp->next;        temp->next=temp2;        ++size;    }    else    {           while(temp->next!=NULL)        {            if(temp->info==initial)            {                temp2->next=temp->next;                temp->next=temp2;                ++size;                break;            }            temp=temp->next;        }        if(temp->next==NULL)        {            PushBack(newItem);        }    }}// end of InsertAfter template <class ItemType>void LinkedList<ItemType>::InsertInOrder(ItemType item){    if(IsEmpty())    {        PushFront(item);    }    else    {        node* temp=head;        node* temp2=new node;            if(item <=(temp->info))        {              ItemType placeHolder=temp->info;            temp2->info=placeHolder;            temp->info=item;            temp2->next=temp->next;            temp->next=temp2;            ++size;        }         else        {            while(temp->next!=NULL)            {                     if(((temp->info) <= item) && (item <= (temp->next->info)))                {                             temp2->info=item;                    temp2->next=temp->next;                    temp->next=temp2;                    ++size;                    return;                }                temp=temp->next;            }            if(temp->next==NULL)            {                PushBack(item);            }        }    }}// end of InsertInOrder template <class ItemType>int LinkedList<ItemType>::Size(){    if(IsEmpty())    {        cout<<"nLIST EMPTYn";    }    return size;}// end of Size  template <class ItemType>void LinkedList<ItemType>::MakeEmpty(){    if(!IsEmpty())    {        cout << "nnDestroying nodes...n";        while(!IsEmpty())        {            node* temp = head;            //cout << temp-> info << 'n';            head = head-> next;            delete temp;        }        size = 0;    }}// end of MakeEmpty template <class ItemType>LinkedList<ItemType>::~LinkedList(){ MakeEmpty();}// http://programmingnotes.org/ ```

===== DEMONSTRATION HOW TO USE =====

Use of the above template class is the same as its STL counterpart. Here is a sample program demonstrating its use.

``` How To Use #include 'LinkedList.h' C++ #include <iostream> #include <string> #include "LinkedList.h" using namespace std; int main() { // declare variables, using a string as // the item type for the class. // NOTE: you can also use an int, float, double etc. // instead of a string LinkedList<string> list; // demontrate the "InOrder" function cout<<"** These are names of fruits sorted in order" <<" using the 'InsertInOrder()' function:nn"; list.InsertInOrder("Tomato"); list.InsertInOrder("Orange"); list.InsertInOrder("Apple"); list.InsertInOrder("Plum"); list.Display(); cout<<"nThere is currently "<<list.Size()<<" items in the listnn"; // demonstrate the "Delete" function cout<<"n** Here is the same list with the word 'Plum' deleted" << "nusing the 'Delete()' function:nn"; list.Delete("Plum"); list.Display(); cout<<"nThere is currently "<<list.Size()<<" items in the listnn"; // demonstrate the "InsertAfter" function cout<<"n** Now the word 'Bike' will be added to the list," <<"nright after the word 'Apple' using the " <<"'InsertAfter()' funciton:nn"; list.InsertAfter("Apple","Bike"); list.Display(); cout<<"nThere is currently "<<list.Size()<<" items in the listnn"; // demonstrate the "InsertBefore" function cout<<"n** Now the name 'Jessica' will be added to the list," <<"nright before the word 'Orange' using the " <<"'InsertBefore()' funciton:nn"; list.InsertBefore("Orange","Jessica"); list.Display(); cout<<"nThere is currently "<<list.Size()<<" items in the listnn"; // demonstrate the "Replace" function cout<<"n** The word 'Orange' will now be replaced with the name," <<"n'Kat' using the 'Replace()' function:nn"; list.Replace("Orange","Kat"); list.Display(); cout<<"nThere is currently "<<list.Size()<<" items in the listnn"; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 #include <iostream>#include <string>#include "LinkedList.h"using namespace std; int main(){ // declare variables, using a string as // the item type for the class.   // NOTE: you can also use an int, float, double etc. // instead of a string LinkedList<string> list;  // demontrate the "InOrder" function cout<<"** These are names of fruits sorted in order" <<" using the 'InsertInOrder()' function:nn"; list.InsertInOrder("Tomato"); list.InsertInOrder("Orange"); list.InsertInOrder("Apple"); list.InsertInOrder("Plum"); list.Display();  cout<<"nThere is currently "<<list.Size()<<" items in the listnn";  // demonstrate the "Delete" function cout<<"n** Here is the same list with the word 'Plum' deleted" << "nusing the 'Delete()' function:nn"; list.Delete("Plum"); list.Display();  cout<<"nThere is currently "<<list.Size()<<" items in the listnn";  // demonstrate the "InsertAfter" function cout<<"n** Now the word 'Bike' will be added to the list," <<"nright after the word 'Apple' using the " <<"'InsertAfter()' funciton:nn"; list.InsertAfter("Apple","Bike"); list.Display();  cout<<"nThere is currently "<<list.Size()<<" items in the listnn";  // demonstrate the "InsertBefore" function cout<<"n** Now the name 'Jessica' will be added to the list," <<"nright before the word 'Orange' using the " <<"'InsertBefore()' funciton:nn"; list.InsertBefore("Orange","Jessica"); list.Display();  cout<<"nThere is currently "<<list.Size()<<" items in the listnn";  // demonstrate the "Replace" function cout<<"n** The word 'Orange' will now be replaced with the name," <<"n'Kat' using the 'Replace()' function:nn"; list.Replace("Orange","Kat"); list.Display();  cout<<"nThere is currently "<<list.Size()<<" items in the listnn";}// http://programmingnotes.org/ ```

Once compiled, you should get this as your output

`** These are names of fruits sorted in order using the 'InsertInOrder()' function:`

``` Apple Orange Plum Tomato There is currently 4 items in the list ** Here is the same list with the word 'Plum' deleted using the 'Delete()' function: Apple Orange Tomato There is currently 3 items in the list ** Now the word 'Bike' will be added to the list, right after the word 'Apple' using the 'InsertAfter()' funciton: Apple Bike Orange Tomato There is currently 4 items in the list ** Now the name 'Jessica' will be added to the list, right before the word 'Orange' using the 'InsertBefore()' funciton: Apple Bike Jessica Orange Tomato There is currently 5 items in the list ** The word 'Orange' will now be replaced with the name, 'Kat' using the 'Replace()' function: Apple Bike Jessica Kat Tomato ```

```There is currently 5 items in the list ```

## C++ || Snippet – How To Swap Two Numbers Without Using A Third “Temporary” Variable The following are three programs which demonstrates how to swap two numbers without using a third “temporary” variable.

Why would anyone want to swap two numbers without utilizing a third variable? There is no real reason to do so other than the fact that exercises such as these are typically used as programming assignments/interview questions. This is a technique that’s rarely ever practical in a real world setting, but it is still an interesting task nonetheless.

``` #1 - Using Simple Math C++ #include <iostream> using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using simple math x = x+y; y = x-y; x = x-y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728 #include <iostream>using namespace std; int main() { // declare variables int x = 0; int y = 0;  // get data cout <<"Please enter two numbers: "; cin >> x >> y;  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl;  cout <<"nSwitching the numbers..n"; // switch the numbers using simple math x = x+y; y = x-y; x = x-y;  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/ ```

SAMPLE OUTPUT:

`Please enter two numbers: 7 28`

``` Item #1 = 7 Item #2 = 28 Switching the numbers.. ```

```Item #1 = 28 Item #2 = 7 ```

``` #2 - Using The XOR Swap Algorithm C++ #include <iostream> using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using the xor swap algorithm x ^= y; y ^= x; x ^= y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728 #include <iostream>using namespace std; int main() { // declare variables int x = 0; int y = 0;  // get data cout <<"Please enter two numbers: "; cin >> x >> y;  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl;  cout <<"nSwitching the numbers..n"; // switch the numbers using the xor swap algorithm x ^= y; y ^= x; x ^= y;  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/ ```

SAMPLE OUTPUT:

`Please enter two numbers: 5 12453`

``` Item #1 = 5 Item #2 = 12453 Switching the numbers.. ```

```Item #1 = 12453 Item #2 = 5 ```

``` #3 - Using The In-Built Swap Function C++ #include <iostream> #include <algorithm> using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using the in-built swap function swap(x, y); cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627 #include <iostream>#include <algorithm>using namespace std; int main() { // declare variables int x = 0; int y = 0;  // get data cout <<"Please enter two numbers: "; cin >> x >> y;  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl;  cout <<"nSwitching the numbers..n"; // switch the numbers using the in-built swap function swap(x, y);  cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/ ```

SAMPLE OUTPUT:

`Please enter two numbers: 2132 6547546`

``` Item #1 = 2132 Item #2 = 6547546 Switching the numbers.. ```

```Item #1 = 6547546 Item #2 = 2132 ```

## C++ || Snippet – Palindrome Checker Using A Stack & Queue This page consists of a sample program which demonstrates how to use a stack and a queue to test for a palindrome. This program is great practice for understanding how the two data structures work.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Structs Classes Template Classes - What Are They? Stacks Queues LIFO - Last In First Out FIFO - First In First Out #include 'SingleQueue.h' #include 'ClassStackListType.h' ```

This program first asks the user to enter in text which they wish to compare for similarity. The data is then saved into the system using the “enqueue” and “push” functions available within the queue and stack classes. After the data is obtained, a while loop is used to iterate through both classes, checking to see if the characters at each location within both classes are the same. If the text within both classes are the same, it is a palindrome.

NOTE: This program uses two custom template.h classes. To obtain the code for both class, click here and here.

``` Palindrome Checker Using Stack & Queue C++ #include <iostream> #include <cctype> #include "SingleQueue.h" #include "ClassStackListType.h" using namespace std; int main() { // declare variable char singleChar = ' '; bool isPalindrome = true; SingleQueue<char> queue; StackListType<char> stack; // get data from user, then place them into the // queue and stack for storage. This loop also // displays the user input back to the screen via cout cout <<"Enter in some text to see if its a palindrome: "; while(cin.get(singleChar) && singleChar != '\n') { cout<<singleChar; queue.EnQueue(toupper(singleChar)); stack.Push(toupper(singleChar)); } // determine if the string is a palindrome while((!queue.IsEmpty() && !stack.IsEmpty()) && isPalindrome) { if(queue.Front() != stack.Top()) { isPalindrome = false; } else { queue.DeQueue(); stack.Pop(); } } // display results to the screen if(isPalindrome) { cout<<" is a palindrome!\n"; } else { cout<<" is NOT a palindrome..\n"; } return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 #include <iostream>#include <cctype>#include "SingleQueue.h"#include "ClassStackListType.h"using namespace std; int main(){ // declare variable char singleChar = ' '; bool isPalindrome = true; SingleQueue<char> queue; StackListType<char> stack;  // get data from user, then place them into the // queue and stack for storage. This loop also // displays the user input back to the screen via cout cout <<"Enter in some text to see if its a palindrome: "; while(cin.get(singleChar) && singleChar != '\n') { cout<<singleChar; queue.EnQueue(toupper(singleChar)); stack.Push(toupper(singleChar)); }  // determine if the string is a palindrome while((!queue.IsEmpty() && !stack.IsEmpty()) && isPalindrome) { if(queue.Front() != stack.Top()) { isPalindrome = false; } else { queue.DeQueue(); stack.Pop(); } }  // display results to the screen if(isPalindrome) { cout<<" is a palindrome!\n"; } else { cout<<" is NOT a palindrome..\n"; }  return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: The code was compiled 2 separate times to demonstrate different output)

`====== RUN 1 ======`

``` Enter in some text to see if its a palindrome: StEP on No pETS StEP on No pETS is a palindrome! ====== RUN 2 ====== Enter in some text to see if its a palindrome: Hello World ```

```Hello World is NOT a palindrome.. ```

## C++ || Convert Numbers To Words Using A Switch Statement This program demonstrates more practice using arrays and switch statements.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Integer Arrays Cin.get Isdigit For loops While Loops Switch Statements - How To Use ```

Using “cin.get(),” this program first asks the user to enter in a number (one at a time) that they wish to translate into words. If the text which was entered into the system is a number, the program will save the user input into an integer array. If the text is not a number, the input is discarded. After integer data is obtained, a for loop is used to traverse the integer array, passing the data to a switch statement, which translates the number to text.

This program is very simple, so it does not have the ability to display any number prefixes. As a result, if the number “1858” was entered into the system, the program would output the converted text: “One Eight Five Eight.”

``` Convert Numbers To Words C++ #include <iostream> #include <cctype> using namespace std; int main() { // declare variables int numberArry; int numElems=0; char singleNum=' '; // ask the user for a number cout<<"Enter number: "; // get data from the user, one character at a time while(cin.get(singleNum) && singleNum != 'n') { // only numbers will be saved into the array, everything // else is ignored if(isdigit(singleNum)) { // this converts a char into an integer using ascii values numberArry[numElems] = (singleNum)-'0'; ++numElems; } } cout<<endl; // using the data from the array, display the // numbers to the screen using a switch statement for(int index=0; index < numElems; ++index) { switch(numberArry[index]) { case 0 : cout<<"Zero "; break; case 1 : cout<<"One "; break; case 2: cout<<"Two "; break; case 3: cout<<"Three "; break; case 4: cout<<"Four "; break; case 5: cout<<"Five "; break; case 6: cout<<"Six "; break; case 7: cout<<"Seven "; break; case 8: cout<<"Eight "; break; case 9: cout<<"Nine "; break; default: cout<<"nERROR!n"; break; } } cout<<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 #include <iostream>#include <cctype>using namespace std; int main(){ // declare variables int numberArry; int numElems=0; char singleNum=' ';  // ask the user for a number cout<<"Enter number: ";  // get data from the user, one character at a time while(cin.get(singleNum) && singleNum != 'n') { // only numbers will be saved into the array, everything // else is ignored if(isdigit(singleNum)) { // this converts a char into an integer using ascii values numberArry[numElems] = (singleNum)-'0'; ++numElems; } }  cout<<endl;  // using the data from the array, display the // numbers to the screen using a switch statement for(int index=0; index < numElems; ++index) { switch(numberArry[index]) { case 0 : cout<<"Zero "; break; case 1 : cout<<"One "; break; case 2: cout<<"Two "; break; case 3: cout<<"Three "; break; case 4: cout<<"Four "; break; case 5: cout<<"Five "; break; case 6: cout<<"Six "; break; case 7: cout<<"Seven "; break; case 8: cout<<"Eight "; break; case 9: cout<<"Nine "; break; default: cout<<"nERROR!n"; break; } } cout<<endl;  return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled four separate times to display different output

`======= Run #1 ======= `

``` Enter number: 77331 Seven Seven Three Three One ======= Run #2 ======= Enter number: 234-43-1275 Two Three Four Four Three One Two Seven Five ======= Run #3 ======= Enter number: 1(800) 123-5678 One Eight Zero Zero One Two Three Five Six Seven Eight ======= Run #4 ======= Enter number: This 34 Is 24 A 5 Number 28 ```

```Three Four Two Four Five Two Eight ```

## C++ || Char Array – Palindrome Number Checker Using A Character Array, Strlen, Strcpy, & Strcmp The following is a palindromic number checking program, which demonstrates more use of character array’s, Strlen, & Strcmp.

Want sample code for a palindrome checker which works for numbers and words? Click here.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Character Arrays How to reverse a character array Palindrome - What is it? Strlen Strcpy Strcmp Isdigit Atoi - Convert a char array to a number Do/While Loops For Loops ```

This program first asks the user to enter a number that they wish to compare for similarity. If the number which was entered into the system is a palindrome, the program will prompt a message to the user via cout. This program determines similarity by using the strcmp function to compare two arrays together. Using a for loop, this program also demonstrates how to reverse a character array, aswell as demonstrates how to determine if the text contained in a character array is a number or not.

This program will repeatedly prompt the user for input until an “exit code” is obtained. The designated exit code in this program is the number 0 (zero). So the program will not stop asking for user input until the number 0 is entered into the program.

``` Palindrome Number Checker Using A Char Array C++ #include <iostream> #include <cctype> #include <cstring> #include <cstdlib> using namespace std; // function prototypes void Reverse(char arry[]); bool IsArryANum(char arry[]); // constant int, which is the exit value const int EXIT_VALUE = 0; int main() { // declare variables char arry; char arryReversed; do{// get data from user using do/while loop cout<<"nEnter a positive integer, or ("<<EXIT_VALUE<<") to exit: "; cin >> arry; if(atoi(arry) < 0) // check for negative numbers { cout <<"n*** error: "<<arry<<" must be greater than zeron"; } else if(!IsArryANum(arry)) // check for any letters { cout <<"n*** error: ""<<arry<<"" is not an integern"; } else if(atoi(arry)==EXIT_VALUE) // check for "exit code" { cout <<"nExiting program...n"; } else // if all else is good, determine if number is a palindrome { // copy the user input from the first array (arry) // into the second array (arryReversed) strcpy(arryReversed,arry); // function call to reverse the contents inside the // "arryReversed" array to check for similarity Reverse(arryReversed); cout <<endl<<arry; // use strcmp to determine if the two arrays are the same if(strcmp(arryReversed,arry)==0) { cout <<" is a Palindrome..n"; } else { cout <<" is NOT a Palindrome!n"; } } }while(strcmp("0",arry)!=0); // keep going until user enters the exit value cout <<"nBYE!n"; return 0; }// end of main void Reverse(char arry[]) { // get the length of the current word in the array index int length = strlen(arry)-1; // increment thru each letter within the current char array index // reversing the order of the array for (int currentChar=0; currentChar < length; --length, ++currentChar) { // copy 1st letter in the array index into temp char temp = arry[currentChar]; // copy last letter in the array index into the 1st array index arry[currentChar] = arry[length]; // copy temp into last array index arry[length] = temp; } }// end of Reverse bool IsArryANum(char arry[]) { // LOOP UNTIL U REACH THE NULL CHARACTER, // AKA THE END OF THE CHAR ARRAY for(int x=0; arry[x]!='�'; ++x) { // if the current char isnt a number, // exit the loop & return false if(!isdigit(arry[x])) { return false; } } return true; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 #include <iostream>#include <cctype>#include <cstring>#include <cstdlib>using namespace std; // function prototypesvoid Reverse(char arry[]);bool IsArryANum(char arry[]); // constant int, which is the exit value const int EXIT_VALUE = 0; int main(){ // declare variables char arry; char arryReversed; do{// get data from user using do/while loop cout<<"nEnter a positive integer, or ("<<EXIT_VALUE<<") to exit: "; cin >> arry; if(atoi(arry) < 0) // check for negative numbers { cout <<"n*** error: "<<arry<<" must be greater than zeron"; } else if(!IsArryANum(arry)) // check for any letters { cout <<"n*** error: ""<<arry<<"" is not an integern"; } else if(atoi(arry)==EXIT_VALUE) // check for "exit code" { cout <<"nExiting program...n"; } else // if all else is good, determine if number is a palindrome { // copy the user input from the first array (arry) // into the second array (arryReversed) strcpy(arryReversed,arry);  // function call to reverse the contents inside the // "arryReversed" array to check for similarity Reverse(arryReversed); cout <<endl<<arry;  // use strcmp to determine if the two arrays are the same if(strcmp(arryReversed,arry)==0) { cout <<" is a Palindrome..n"; } else { cout <<" is NOT a Palindrome!n"; } } }while(strcmp("0",arry)!=0); // keep going until user enters the exit value  cout <<"nBYE!n"; return 0;}// end of main void Reverse(char arry[]){ // get the length of the current word in the array index int length = strlen(arry)-1; // increment thru each letter within the current char array index // reversing the order of the array for (int currentChar=0; currentChar < length; --length, ++currentChar) { // copy 1st letter in the array index into temp char temp = arry[currentChar]; // copy last letter in the array index into the 1st array index arry[currentChar] = arry[length]; // copy temp into last array index arry[length] = temp; }}// end of Reverse bool IsArryANum(char arry[]){ // LOOP UNTIL U REACH THE NULL CHARACTER, // AKA THE END OF THE CHAR ARRAY for(int x=0; arry[x]!=''; ++x) { // if the current char isnt a number, // exit the loop & return false if(!isdigit(arry[x])) { return false; } } return true;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

`Enter a positive integer, or (0) to exit: L33T`

``` *** error: "L33T" is not an integer Enter a positive integer, or (0) to exit: -728 *** error: -728 must be greater than zero Enter a positive integer, or (0) to exit: 1858 1858 is NOT a Palindrome! Enter a positive integer, or (0) to exit: 7337 7337 is a Palindrome.. Enter a positive integer, or (0) to exit: 0 Exiting program... ```

```BYE! ```

## C++ || Convert Time From Seconds Into Hours, Min, Sec Format Here is another simple programming assignment. This page will demonstrate how to convert time from -seconds- into HH::MM::SS (hours, minutes seconds) format. So for example, if you had an input time of 9630 seconds, the program would display the converted time of 2 hours, 40 minutes, and 30 seconds.

Using simple math, this program utilizes the modulus operator, and the division operator during the conversion process.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Modulus - What is it? How Many Seconds Are In One Hour? How Many Seconds Are In One Minute? ```

``` Convert Seconds Into HH::MM::SS Format C++ #include <iostream> using namespace std; int main() { // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 #include <iostream>using namespace std; int  main(){ // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compile five separate times to display different output)

`====== RUN 1 ======`

``` Enter a time in seconds: 9630 The time in HH:MM:SS format is: 2 hours, 40 minutes, and 30 seconds! ====== RUN 2 ====== Enter a time in seconds: 7200 The time in HH:MM:SS format is: 2 hours, 0 minutes, and 0 seconds! ====== RUN 3 ====== Enter a time in seconds: 45 The time in HH:MM:SS format is: 0 hours, 0 minutes, and 45 seconds! ====== RUN 4 ====== Enter a time in seconds: 134 The time in HH:MM:SS format is: 0 hours, 2 minutes, and 14 seconds! ====== RUN 5 ====== Enter a time in seconds: 31536000 ```

```The time in HH:MM:SS format is: 8760 hours, 0 minutes, and 0 seconds! ```

## C++ || Char Array – Determine If A String Is A Number Or Not The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using and manipulating character arrays.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Character Arrays Cin.getline Strlen - Get The Length Of A Char Array Isalpha Isspace ```

This program first prompts the user to input a line of text. After it obtains data from the user, using a for loop, it then displays the the string to the screen one letter (char) at a time. If the current character at that specific array index is a letter, a “flag” is set, indicating that the current word which is being displayed is not a number. If the “flag” is not set, the current word is indeed a number.

This program has the ability to intake multiple words at a time, so for example, if the user input was “Hello World 2012” the program would display the output:

```Hello is NOT a number! World is NOT a number! 2012 is a number..```

``` Determine If A String Is A Number Or Not C++ #include <iostream> #include <iomanip> #include <cstring> #include <cctype> using namespace std; // function prototype void IsArryANum(char arry[]); int main() { // declare & initialize variables char arry; int length=0; // obtain data from user cout << "Enter some text to see if its a number or not: "; cin.getline(arry,sizeof(arry)); // getting line // get the length of the char array // and place a [space] at the end of it. Then // set the array index after the [space] to NULL length = strlen(arry); arry[length]=' '; arry[length+1]='�'; cout<<endl; IsArryANum(arry); return 0; }// end of main void IsArryANum(char arry[]) { int notANumber=0; // LOOP UNTIL U REACH THE NULL CHARACTER, // AKA THE END OF THE CHAR ARRAY for(int x=0; arry[x]!='�'; ++x) { cout<<arry[x]; // display the char at the current index // if the current char isnt a number, increment counter if(isalpha(arry[x])) { ++notANumber; } // if curerent char is a space, that indicates we are // at the end of the current word, so we // display the results to the user else if(isspace(arry[x])) { if(notANumber > 0) { cout<<"is NOT a number!" <<" There are "<<notANumber<<" letters" <<" in that word...n"; } else { cout<<"is a number..n"; } notANumber=0; } } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 #include <iostream>#include <iomanip>#include <cstring>#include <cctype>using namespace std; // function prototypevoid IsArryANum(char arry[]); int main(){ // declare & initialize variables char arry; int length=0;   // obtain data from user cout << "Enter some text to see if its a number or not: "; cin.getline(arry,sizeof(arry)); // getting line  // get the length of the char array // and place a [space] at the end of it. Then // set the array index after the [space] to NULL length = strlen(arry); arry[length]=' '; arry[length+1]=''; cout<<endl; IsArryANum(arry);  return 0;}// end of main void IsArryANum(char arry[]){ int notANumber=0;  // LOOP UNTIL U REACH THE NULL CHARACTER, // AKA THE END OF THE CHAR ARRAY for(int x=0; arry[x]!=''; ++x) { cout<<arry[x]; // display the char at the current index  // if the current char isnt a number, increment counter if(isalpha(arry[x])) { ++notANumber; } // if curerent char is a space, that indicates we are // at the end of the current word, so we // display the results to the user else if(isspace(arry[x])) { if(notANumber > 0) { cout<<"is NOT a number!" <<" There are "<<notANumber<<" letters" <<" in that word...n"; } else { cout<<"is a number..n"; } notANumber=0; } }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compiled three separate times to display different output)

`====== RUN 1 ======`

``` Enter some text to see if its a number or not: My Programming Notes My is NOT a number! There are 2 letters in that word... Programming is NOT a number! There are 11 letters in that word... Notes is NOT a number! There are 5 letters in that word... ====== RUN 2 ====== Enter some text to see if its a number or not: May 30th 2012 May is NOT a number! There are 3 letters in that word... 30th is NOT a number! There are 2 letters in that word... 2012 is a number.. ====== RUN 3 ====== Enter some text to see if its a number or not: 5 31 2012 ```

```5 is a number.. 31 is a number.. 2012 is a number..```

## C++ || Snippet – Doubly Linked List Custom Template Queue Sample Code This page will consist of sample code for a custom doubly linked list template queue. This implementation is considered a doubly linked list because it uses two nodes to store data in the queue – a ‘front’ and a ‘rear’ node. This is not a circular linked list, nor does it link forwards and/or backwards.

Looking for sample code for a stack? Click here.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Structs Classes Template Classes - What Are They? Queue - What is it? FIFO - First In First Out #include < queue> Linked Lists - How To Use ```

This template class is a custom duplication of the Standard Template Library (STL) queue class. Whether you like building your own data structures, you simply do not like to use any inbuilt functions, opting to build everything yourself, or your homework requires you make your own data structure, this sample code is really useful. I feel its beneficial building functions such as this, that way you better understand the behind the scene processes.

``` #include 'DoubleQueue.h' C++ // ============================================================================ // Author: K Perkins // Date: May 20, 2012 // Taken From: http://programmingnotes.org/ // File: DoubleQueue.h // Description: This is a class which implements various functions // demonstrating the use of a queue. // ============================================================================ #include <iostream> template <class ItemType> class DoubleQueue { public: DoubleQueue(); /* Function: Constructor initializes queue Precondition: None Postcondition: Defines private variables */ bool IsEmpty(); /* Function: Determines whether queue is empty Precondition: Queue has been created Postcondition: The function = true if the queue is empty and the function = false if queue is not empty */ bool IsFull(); /* Function: Determines whether queue is full Precondition: Queue has been created Postcondition: The function = true if the queue is full and the function = false if queue is not full */ void EnQueue(ItemType item); /* Function: Adds new item to the back of the queue Precondition: Queue has been created and is not full Postcondition: Item is in the queue */ ItemType DeQueue(); /* Function: Returns and then deletes the first item in the queue Precondition: Queue has been created and is not empty Postcondition: The first item in the queue has been removed and the queue order is maintained */ ItemType Front(); /* Function: Returns (but does not delete) the first item in the queue Precondition: Queue has been created and is not empty Postcondition: The first item in the queue has been returned and the queue order is maintained */ ItemType Rear(); /* Function: Returns (but does not delete) the last item in the queue Precondition: Queue has been created and is not empty Postcondition: The last item in the queue has been returned and the queue order is maintained */ int Size(); /* Function: Return the current size of the queue Precondition: Queue has been initialized Postcondition: The size of the queue is returned */ void MakeEmpty(); /* Function: Initializes queue to an empty state Precondition: Queue has been created Postcondition: Queue no longer exists */ ~DoubleQueue(); /* Function: Removes the queue Precondition: Queue has been declared Postcondition: Queue no longer exists */ private: struct NodeType { ItemType currentItem; NodeType* next; }; NodeType* front; // front of queue NodeType* rear; // back of queue int size; }; //========================= Implementation ================================// template<class ItemType> DoubleQueue<ItemType>::DoubleQueue() { front = NULL; rear = NULL; size = 0; }/* end of DoubleQueue */ template<class ItemType> bool DoubleQueue<ItemType>::IsEmpty() { return (front == NULL); }/* end of IsEmpty */ template<class ItemType> bool DoubleQueue<ItemType>::IsFull() { try { NodeType* location = new NodeType; delete location; return false; } catch(std::bad_alloc&) { return true; } }/* end of IsFull */ template<class ItemType> void DoubleQueue<ItemType>::EnQueue(ItemType newItem) { if(IsFull()) { std::cout<<"nQUEUE FULLn"; } else { NodeType* newNode = new NodeType; // adds new node newNode-> currentItem = newItem; newNode-> next = NULL; if(rear == NULL) { front = newNode; } else { rear-> next = newNode; } rear = newNode; ++size; } }/* end of EnQueue */ template<class ItemType> ItemType DoubleQueue<ItemType>::DeQueue() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { NodeType* tempPtr = front; // temporary pointer ItemType item = front-> currentItem; front = front-> next; if(front == NULL) { rear = NULL; } delete tempPtr; --size; return item; } }/* end of DeQueue */ template<class ItemType> ItemType DoubleQueue<ItemType>::Front() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return front-> currentItem; } }/* end of Front */ template<class ItemType> ItemType DoubleQueue<ItemType>::Rear() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return rear-> currentItem; } }/* end of Rear */ template<class ItemType> int DoubleQueue<ItemType>::Size() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } return size; }/* end of Size */ template<class ItemType> void DoubleQueue<ItemType>::MakeEmpty() { if(!IsEmpty()) { std::cout << "Destroying nodes ...n"; while(!IsEmpty()) { NodeType* tempPtr = front; //std::cout << tempPtr-> currentItem << 'n'; front = front-> next; delete tempPtr; } rear = NULL; size = 0; } }/* end of MakeEmpty */ template<class ItemType> DoubleQueue<ItemType>::~DoubleQueue() { MakeEmpty(); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210 // ============================================================================//     Author: K Perkins//     Date:   May 20, 2012//     Taken From: http://programmingnotes.org///     File:  DoubleQueue.h//     Description: This is a class which implements various functions//          demonstrating the use of a queue. // ============================================================================#include <iostream> template <class ItemType>class DoubleQueue{public: DoubleQueue(); /*   Function: Constructor initializes queue Precondition: None Postcondition: Defines private variables */ bool IsEmpty(); /*   Function: Determines whether queue is empty Precondition: Queue has been created Postcondition: The function = true if the queue is empty and the function = false if queue is not empty */ bool  IsFull(); /*   Function: Determines whether queue is full Precondition: Queue has been created Postcondition: The function = true if the queue is full and the function = false if queue is not full */ void EnQueue(ItemType item); /*   Function: Adds new item to the back of the queue Precondition:  Queue has been created and is not full Postcondition: Item is in the queue */ ItemType DeQueue(); /*   Function: Returns and then deletes the first item in the queue Precondition:  Queue has been created and is not empty Postcondition: The first item in the queue has been removed and the queue order is maintained */ ItemType Front(); /*   Function: Returns (but does not delete) the first item in the queue Precondition:  Queue has been created and is not empty Postcondition: The first item in the queue has been returned and the queue order is maintained */ ItemType Rear(); /*   Function: Returns (but does not delete) the last item in the queue Precondition:  Queue has been created and is not empty Postcondition: The last item in the queue has been returned and the queue order is maintained */ int Size();          /*   Function: Return the current size of the queue               Precondition: Queue has been initialized               Postcondition: The size of the queue is returned */ void MakeEmpty(); /*   Function: Initializes queue to an empty state Precondition: Queue has been created Postcondition: Queue no longer exists */ ~DoubleQueue(); /*   Function: Removes the queue Precondition: Queue has been declared Postcondition: Queue no longer exists */private: struct  NodeType { ItemType currentItem; NodeType* next; }; NodeType* front; // front of queue NodeType* rear; // back of queue int size;}; //=========================  Implementation  ================================// template<class ItemType>DoubleQueue<ItemType>::DoubleQueue(){ front = NULL; rear = NULL; size = 0;}/* end of DoubleQueue */ template<class ItemType>bool DoubleQueue<ItemType>::IsEmpty(){ return (front == NULL);}/* end of IsEmpty */ template<class ItemType>bool DoubleQueue<ItemType>::IsFull(){ try { NodeType* location = new NodeType; delete location; return false; } catch(std::bad_alloc&) { return true; }}/* end of IsFull */ template<class ItemType>void DoubleQueue<ItemType>::EnQueue(ItemType newItem){ if(IsFull()) { std::cout<<"nQUEUE FULLn"; } else { NodeType* newNode = new NodeType; // adds new node newNode-> currentItem = newItem; newNode-> next = NULL; if(rear == NULL) { front = newNode; } else { rear-> next = newNode; } rear = newNode; ++size; }}/* end of EnQueue */ template<class ItemType>ItemType DoubleQueue<ItemType>::DeQueue() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { NodeType* tempPtr = front; // temporary pointer ItemType item = front-> currentItem; front = front-> next;  if(front == NULL) { rear = NULL; } delete tempPtr; --size; return item; } }/* end of DeQueue */ template<class ItemType>ItemType DoubleQueue<ItemType>::Front() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return front-> currentItem; } }/* end of Front */ template<class ItemType>ItemType DoubleQueue<ItemType>::Rear() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return rear-> currentItem; } }/* end of Rear */ template<class ItemType>int DoubleQueue<ItemType>::Size(){ if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } return size;}/* end of Size */ template<class ItemType>void DoubleQueue<ItemType>::MakeEmpty(){ if(!IsEmpty()) { std::cout << "Destroying nodes ...n"; while(!IsEmpty()) { NodeType* tempPtr = front; //std::cout << tempPtr-> currentItem << 'n'; front = front-> next; delete tempPtr; } rear = NULL; size = 0; }}/* end of MakeEmpty */ template<class ItemType>DoubleQueue<ItemType>::~DoubleQueue() { MakeEmpty();}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above template class is the same as its STL counterpart. Here is a sample program demonstrating its use.

``` How To Use #include 'DoubleQueue.h' C++ #include <iostream> #include "DoubleQueue.h" using namespace std; int main() { // declare variables DoubleQueue<char> charQueue; DoubleQueue<int> intQueue; DoubleQueue<float> floatQueue; // ------ Char Example ------// char charArry[]="My Programming Notes Helped Me Succeed!"; int counter=0; while(charArry[counter]!='\0') { charQueue.EnQueue(charArry[counter]); ++counter; } cout<<"charQueue has "<<charQueue.Size()<<" items in it " <<"and contains the text:n"; while(!charQueue.IsEmpty()) { cout<<charQueue.DeQueue(); } cout<<endl; // ------ Int Example ------// int intArry[]={1,22,3,46,5,66,7,8,1987}; counter=0; while(counter<9) { intQueue.EnQueue(intArry[counter]); ++counter; } cout<<"nintQueue has "<<intQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; counter=0; while(!intQueue.IsEmpty()) { counter-=intQueue.DeQueue(); } cout<<counter<<endl; // ------ Float Example ------// float floatArry[]={41.6,2.8,43.9,4.4,19.87,6.23,7.787,68.99,9.6,81.540}; float sum=0; counter=0; while(counter<10) { floatQueue.EnQueue(floatArry[counter]); ++counter; } cout<<"nfloatQueue has "<<floatQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; while(!floatQueue.IsEmpty()) { sum-=floatQueue.DeQueue(); } cout<<sum<<endl; return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 #include <iostream>#include "DoubleQueue.h"using namespace std; int main(){ // declare variables DoubleQueue<char> charQueue; DoubleQueue<int> intQueue; DoubleQueue<float> floatQueue; // ------ Char Example ------// char charArry[]="My Programming Notes Helped Me Succeed!"; int counter=0; while(charArry[counter]!='\0') { charQueue.EnQueue(charArry[counter]); ++counter; } cout<<"charQueue has "<<charQueue.Size()<<" items in it " <<"and contains the text:n"; while(!charQueue.IsEmpty()) { cout<<charQueue.DeQueue(); } cout<<endl; // ------ Int Example ------// int intArry[]={1,22,3,46,5,66,7,8,1987}; counter=0; while(counter<9) { intQueue.EnQueue(intArry[counter]); ++counter; } cout<<"nintQueue has "<<intQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; counter=0; while(!intQueue.IsEmpty()) { counter-=intQueue.DeQueue(); } cout<<counter<<endl; // ------ Float Example ------// float floatArry[]={41.6,2.8,43.9,4.4,19.87,6.23,7.787,68.99,9.6,81.540}; float sum=0; counter=0; while(counter<10) { floatQueue.EnQueue(floatArry[counter]); ++counter; } cout<<"nfloatQueue has "<<floatQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; while(!floatQueue.IsEmpty()) { sum-=floatQueue.DeQueue(); } cout<<sum<<endl;  return 0;}// http://programmingnotes.org/ ```

Once compiled, you should get this as your output

```charQueue has 39 items in it and contains the text: My Programming Notes Helped Me Succeed!```

``` intQueue has 9 items in it. The sum of the numbers in the queue is: -2145 ```

```floatQueue has 10 items in it. The sum of the numbers in the queue is: -286.717 ```

## C++ || Snippet – How To Find The Minimum & Maximum Of 3 Numbers, Print In Ascending Order This page will demonstrate how to find the minimum and maximum of 3 numbers. After the maximum and minimum numbers are obtained, the 3 numbers are displayed to the screen in ascending order.

This program uses multiple if-statements to determine equality, and uses 3 seperate int varables to store its data. This program is very basic, so it does not utilize an integer array, or any sorting methods.

NOTE: If you want to find the Minimum & Maximum of numbers contained in an integer array, click here.

``` Find The Minimum & Maximum Of 3 Numbers C++ // ============================================================================ // Author: K Perkins // Date: Apr 29, 2012 // Taken From: http://programmingnotes.org/ // File: min_mid_max.cpp // Description: Demonstrates how to find the minimum & maximum of 3 numbers // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int a=0; int b=0; int c=0; int max=0; int min=0; int middle=0; // get data from user cout<<"Please enter 3 numbers: "; cin >> a >> b >> c; // display information back to the user cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl; // check for the highest number if(a > b && a > c) { max = a; } else if(b > a && b > c) { max = b; } else { max = c; } // check for the lowest number if(a < b && a < c) { min = a; } else if(b < a && b < c) { min = b; } else { min = c; } // use the 'min' and 'max' variables from above ^ to find // the 'middle' value if((max == a && min == b) || (max == b && min == a)) { middle = c; } else if((max == b && min == c) || (max == c && min == b)) { middle = a; } else { middle = b; } // display data to the screen cout<<"nThe maximum number is: "<<max; cout<<"nThe minimum number is: "<<min; cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 // ============================================================================//     Author: K Perkins//     Date:   Apr 29, 2012//     Taken From: http://programmingnotes.org///     File:  min_mid_max.cpp//     Description: Demonstrates how to find the minimum & maximum of 3 numbers// ============================================================================#include <iostream>using namespace std; int main(){    // declare variables    int a=0;    int b=0;    int c=0;    int max=0;    int min=0;    int middle=0;        // get data from user    cout<<"Please enter 3 numbers: ";    cin >> a >> b >> c;        // display information back to the user    cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl;        // check for the highest number    if(a > b && a > c)    {        max = a;    }    else if(b > a && b > c)    {        max = b;    }    else    {        max = c;    }        // check for the lowest number    if(a < b && a < c)    {        min = a;    }    else if(b < a && b < c)    {        min = b;    }    else    {        min = c;    }        // use the 'min' and 'max' variables from above ^ to find    // the 'middle' value    if((max == a && min == b) || (max == b && min == a))    {        middle = c;    }    else if((max == b && min == c) || (max == c && min == b))    {        middle = a;    }    else    {        middle = b;    }        // display data to the screen    cout<<"nThe maximum number is: "<<max;    cout<<"nThe minimum number is: "<<min;    cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<endl;        return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

```Please enter 3 numbers: 89 56 1987 The numbers you just entered are: 89 56 1987```

``` ```

```The maximum number is: 1987 The minimum number is: 56 The numbers in order are: 56 89 1987 ```

## C++ || Snippet – How To Read & Write Data From A User Specified Text File This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program is very similar to an earlier snippet which was presented on this site, but in this example, the user has the option of choosing which file they want to manipulate. This program also demonstrates how to read in data from a file (numbers), manipulate that data, and output new data into a different text file.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Fstream Ifstream Ofstream Working With Files C_str() - Convert A String To Char Array Equivalent Getline - String Version```

Note: The data file that is used in this example can be downloaded here.

Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in

`Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]`

``` User Specified Input/Output Manipulation C++ #include <iostream> #include <fstream> #include <string> #include <cmath> #include <cstdlib> using namespace std; int main() { // declare variables // char fileName; string fileName; ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0; // get the name of the file from the user cout << "Please enter the name of the file: "; getline(cin, fileName); // ^ you could also use a character array instead // of a string. Your getline declaration would look // like this: // --------------------------------------------- // cin.getline(fileName,80); // this opens the input file // NOTE: you need to convert the string to a // char array using the function "c_str()" infile.open(fileName.c_str()); // ^ if you used a char array as the file name instead // of a string, the declaration to open the file // would look like this: // --------------------------------------------- // infile.open(fileName); // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"nError, the input file could not be found!n"; exit(1); } // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt"); // this loop reads in data until there is no more // data contained in the file while(infile.peek() != EOF) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile>> a >> b>> c; // NOTE: if you want to read data into an array // your declaration would be like this // ------------------------------------ // infile>> a[counter] >> b[counter] >> c[counter]; // ++counter; } // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via cout cout <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; cout <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; outfile <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // close the input/output files once you are done using them infile.close(); outfile.close(); // stops the program from automatically closing cout<<"nPress ENTER to continue..."; cin.get(); return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 #include <iostream>#include <fstream>#include <string>#include <cmath>#include <cstdlib>using namespace std; int main() {    // declare variables    // char fileName;    string fileName;        ifstream infile;    ofstream outfile;    double a=0,b=0,c=0;    double root1=0, root2=0;            // get the name of the file from the user    cout << "Please enter the name of the file: ";        getline(cin, fileName);        // ^ you could also use a character array instead    // of a string. Your getline declaration would look    // like this:    // ---------------------------------------------    // cin.getline(fileName,80);      // this opens the input file    // NOTE: you need to convert the string to a     // char array using the function "c_str()"    infile.open(fileName.c_str());        // ^  if you used a char array as the file name instead     // of a string, the declaration to open the file     // would look like this:    // ---------------------------------------------    // infile.open(fileName);        // check to see if the file even exists, & if not then EXIT    if(infile.fail())    {        cout<<"nError, the input file could not be found!n";        exit(1);    }        // this opens the output file    // if the file doesnt already exist, it will be created    outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt");          // this loop reads in data until there is no more     // data contained in the file    while(infile.peek() != EOF)    {        // this assigns the incoming data to the        // variables 'a', 'b' and 'c'        // NOTE: it is just like a cin >> statement        infile>> a >> b>> c;         // NOTE: if you want to read data into an array        // your declaration would be like this        // ------------------------------------         // infile>> a[counter] >> b[counter] >> c[counter];        // ++counter;    }            // this does the quadratic formula calculations    root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a);    root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a);     // this displays the numbers to screen via cout    cout <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl;    cout <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl;         // this saves the data to the output file    // NOTE: its almost exactly the same as the cout statement    outfile <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl;    outfile <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl;     // close the input/output files once you are done using them    infile.close();    outfile.close();     // stops the program from automatically closing    cout<<"nPress ENTER to continue...";    cin.get();     return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

`Please enter the name of the file: INPUT_Quadratic_programmingnotes_freeweq_com.txt`

``` For the numbers a = 2 b = 4 c = -16 root 1 = 2 root 2 = -4 ```

`Press ENTER to continue...`