## 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[][7] = {{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][0])) || (postfix[x][0] == '.')) { doubleStack.push(atof(postfix[x].c_str())); } // push negative numbers onto the stack else if((postfix[x].length() > 1) && ((postfix[x][0] == '-') && (isdigit(postfix[x][1]) || (postfix[x][1] == '.')))) { 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][0]) && (!doubleStack.empty())) { char token = tolower(postfix[x][0]); // 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[][7] = {{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][0])) || (postfix[x][0] == '.'))        {           doubleStack.push(atof(postfix[x].c_str()));        }        // push negative numbers onto the stack        else if((postfix[x].length() > 1) && ((postfix[x][0] == '-') &&            (isdigit(postfix[x][1]) || (postfix[x][1] == '.'))))        {           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][0]) && (!doubleStack.empty()))        {            char token = tolower(postfix[x][0]);             // 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 ```

## Java || Snippet – How To Do Simple Math Using Integer Arrays

This page will consist of simple programs which demonstrate the process of doing simple math with numbers that are stored in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays The "Random" Class For Loops Assignment Operators - Simple Math Operations Custom Setw/Setfill In Java ```

Note: In all of the examples on this page, a random number generator was used to place numbers into the array. If you do not know how to obtain data from the user, or if you do not know how to insert data into an array, click here for a demonstration.

The first code snippet will demonstrate how to add numbers together which are stored in an integer array. This example uses the “+=” assignment operator.

``` #1 - Addition Using An Int Array Java import java.util.Random; public class Addition { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe sum of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum + arry[x] totalSum += arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Addition{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe sum of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum + arry[x] totalSum += arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// 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.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 22 26 41 89 35 90 15 99 85 5 95 86 -------------------------------------------------- The sum of the items in the array is: 688 ```

===== SUBTRACTION =====

The second code snippet will demonstrate how to subtract numbers which are stored in an integer array. This example uses the “-=” assignment operator.

``` #2 - Subtraction Using An Int Array Java import java.util.Random; public class Subtraction { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe difference of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum - arry[x] totalSum -= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Subtraction{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe difference of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum - arry[x] totalSum -= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// 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.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 99 92 91 26 1 52 98 62 51 22 64 65 -------------------------------------------------- The difference of the items in the array is: -723 ```

===== MULTIPLICATION =====

The third code snippet will demonstrate how to multiply numbers which are stored in an integer array. This example uses the “*=” assignment operator.

``` #3 - Multiplication Using An Int Array Java import java.util.Random; public class Multiplication { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe product of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum * arry[x] totalSum *= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Multiplication{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe product of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum * arry[x] totalSum *= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// 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.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 95 63 32 19 93 83 71 35 32 37 66 95 -------------------------------------------------- The product of the items in the array is: 494770176 ```

===== DIVISION =====

The fourth code snippet will demonstrate how to divide numbers which are stored in an integer array. This example uses the “/=” assignment operator.

``` #4 - Division Using An Int Array Java import java.util.Random; public class Division { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable double totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe quotient of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum / arry[x] totalSum /= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Division{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable double totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe quotient of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum / arry[x] totalSum /= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// 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.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 28 85 90 52 1 64 93 85 4 22 4 28 -------------------------------------------------- The quotient of the items in the array is: 1.8005063061510687E-17 ```

## Java || Snippet – How To Find The Highest & Lowest Numbers Contained In An Integer Array

This page will consist of a simple demonstration for finding the highest and lowest numbers contained in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Custom Setw/Setfill In Java ```

Finding the highest/lowest values in an array can be found in one or two ways. The first way would be via a sort, which would obviously render the highest/lowest numbers contained in the array because the values would be sorted in order from highest to lowest. But a sort may not always be practical, especially when you want to keep the array values in the same order that they originally came in.

The second method of finding the highest/lowest values is by traversing through the array, literally checking each value it contains one by one to determine if the current number which is being compared truly is a target value or not. That method will be displayed below.

``` Find The Highest/Lowest Numbers In An Array Java import java.util.Random; public class HighestLowestArray { // global variable declaration final static int ARRAY_SIZE = 14; // const int allocating space for the array static Random rand = new Random(); // this is the call to the "Random" class public static void main(String[] args) { // declare & initialize variables int[] arry = new int[ARRAY_SIZE]; int highestScore = -999999; int lowestScore = 999999; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < ARRAY_SIZE; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Output the original array values for(int x = 0; x < ARRAY_SIZE; ++x) { System.out.print(arry[x]+" "); } System.out.println(""); // creates a line seperator setwLF("",60,'-'); // use a for loop to go thru the array checking to see the highest/lowest element System.out.print("nThese are the highest and lowest array values: "); for(int index=0; index < ARRAY_SIZE; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(arry[index] > highestScore) { highestScore = arry[index]; } // if current 'lowestScore' element is bigger than the current array element, // then set 'lowestScore' equal to the current array element if(arry[index] < lowestScore) { lowestScore = arry[index]; } }// end for loop // display the results to the user System.out.print("nHighest: "+highestScore); System.out.print("nLowest: "+lowestScore); System.out.println(""); }// end of main static public void setwLF(String str, int width, char fill) { for (int x = str.length(); x < width; ++x) { System.out.print(fill); } System.out.print(str); }// end of setwLF }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 import java.util.Random; public class HighestLowestArray{ // global variable declaration final static int ARRAY_SIZE = 14; // const int allocating space for the array static Random rand = new Random(); // this is the call to the "Random" class public static void main(String[] args) { // declare & initialize variables int[] arry = new int[ARRAY_SIZE]; int highestScore = -999999; int lowestScore = 999999;      System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < ARRAY_SIZE; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Output the original array values for(int x = 0; x < ARRAY_SIZE; ++x) { System.out.print(arry[x]+"  "); } System.out.println(""); // creates a line seperator setwLF("",60,'-'); // use a for loop to go thru the array checking to see the highest/lowest element System.out.print("nThese are the highest and lowest array values: "); for(int index=0; index < ARRAY_SIZE; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(arry[index] > highestScore) { highestScore = arry[index]; } // if current 'lowestScore' element is bigger than the current array element, //  then set 'lowestScore' equal to the current array element if(arry[index] < lowestScore) { lowestScore = arry[index]; } }// end for loop // display the results to the user System.out.print("nHighest: "+highestScore); System.out.print("nLowest: "+lowestScore); System.out.println(""); }// end of main static public void setwLF(String str, int width, char fill) { for (int x = str.length(); x < width; ++x) { System.out.print(fill); } System.out.print(str); }// end of setwLF }// 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

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 36 35 46 86 86 58 44 38 79 52 27 78 65 79 ------------------------------------------------------------ These are the highest and lowest array values: Highest: 86 Lowest: 27 ```

## Java || Snippet – How To Input Numbers Into An Integer Array & Display Its Contents Back To User

This snippet demonstrates how to place numbers into an integer array. It also shows how to display the contents of the array back to the user via stdout.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Final Variables ```

``` Insert & Display Items In An Array Java import java.util.Scanner; public class ArrayInput { // global variable declaration static Scanner cin = new Scanner(System.in); final static int ARRAY_SIZE = 100; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int numElems = 0; int[] myArray = new int[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements System.out.println("Welcome to My Programming Notes' Java Program.n"); // ask user how many items they want to place in array System.out.print("How many items do you want to place into the array?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter item #"+(index+1)+": "); myArray[index] = cin.nextInt(); } // display data to user System.out.print("nThe current items inside the array are: "); // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { System.out.print("nItem #"+(index+1)+": "+myArray[index]); } System.out.println(""); }// end of main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041 import java.util.Scanner; public class ArrayInput{ // global variable declaration static Scanner cin = new Scanner(System.in); final static int ARRAY_SIZE = 100; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int numElems = 0; int[] myArray = new int[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements      System.out.println("Welcome to My Programming Notes' Java Program.n"); // ask user how many items they want to place in array System.out.print("How many items do you want to place into the array?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter item #"+(index+1)+": "); myArray[index] = cin.nextInt(); } // display data to user System.out.print("nThe current items inside the array are: "); // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { System.out.print("nItem #"+(index+1)+": "+myArray[index]); } System.out.println(""); }// end of main }// 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

`Welcome to My Programming Notes' Java Program.`

``` How many items do you want to place into the array?: 5 Enter item #1: 12 Enter item #2: 43 Enter item #3: 5 Enter item #4: 643 Enter item #5: 2321 ```

```The current items inside the array are: Item #1: 12 Item #2: 43 Item #3: 5 Item #4: 643 Item #5: 2321 ```

## 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[50]; 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[50]; 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[80]; char arryReversed[80]; 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[80]; char arryReversed[80]; 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! ```

## Java || Searching An Integer Array For A Target Value

Here is another actual homework assignment which was presented in an intro to programming class which was used to introduce more practice using integer arrays.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Integer Arrays For Loops Methods (A.K.A "Functions") - What Are They? Final Variables If/Else Statements ```

This is a small and simple program which demonstrates how to search for a target value which is stored in an integer array. This program first prompts the user to enter five values into an int array. After the user enters all the values into the system, it then displays a prompt asking the user for a search value. Once it has a search value, the program searches through the array looking for the target value; and wherever the value is found, the program display’s the current array index in which that target value is located. After it displays all the locations where the target value resides, it display’s the total number of occurrences the search value was found within the array.

``` Array Search Java import java.util.Scanner; public class ArraySearch { // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_INTS = 5; public static void main(String[] args) { // declare variables int searchValue = 0; int numOccurences = 0; int[] numValues = new int[NUM_INTS]; // int array size is initialized with a const value // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get data from user via a 'for loop' System.out.println("Please enter "+ NUM_INTS +" integer values:"); for (int index=0; index < NUM_INTS; ++index) { System.out.print("#" + (index + 1) + ": "); numValues[index] = cin.nextInt(); } // get a search value from the user System.out.print("Please enter a search value: "); searchValue = cin.nextInt(); System.out.println(""); // finds the number of occurences the search value was found in the array numOccurences = SearchArray(numValues, searchValue); // display data to user System.out.println("nThe total occurrences of value "+ searchValue + " within the array is: " + numOccurences); }// end of main // ==== SearchArray =========================================================== // // This method will take as input the array, the number of array // elements, and the target value to search for. The function will traverse // the array looking for the target value, and when it finds it, display the // index location within the array. // // Input: // limit [IN] -- the array, the number of array // elements, and the target value // // Output: // The total number of occurrences of the target value in the array // // ============================================================================ public static int SearchArray(int[] numValues, int searchValue) { int numFound=0; for (int index=0; index < NUM_INTS; ++index) { if (numValues[index] == searchValue) { System.out.println("t" + searchValue + " was found at array " + "index #" + index); ++numFound; // if the search values was found, // increment the variable by 1 } } return numFound; } }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 import java.util.Scanner; public class ArraySearch{ // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_INTS = 5; public static void main(String[] args) { // declare variables int searchValue = 0; int numOccurences = 0; int[] numValues = new int[NUM_INTS]; // int array size is initialized with a const value // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get data from user via a 'for loop' System.out.println("Please enter "+ NUM_INTS +" integer values:"); for (int index=0; index < NUM_INTS; ++index) { System.out.print("#" + (index + 1) + ": "); numValues[index] = cin.nextInt(); } // get a search value from the user System.out.print("Please enter a search value: "); searchValue = cin.nextInt(); System.out.println(""); // finds the number of occurences the search value was found in the array numOccurences = SearchArray(numValues, searchValue); // display data to user System.out.println("nThe total occurrences of value "+ searchValue + " within the array is: " + numOccurences); }// end of main // ==== SearchArray =========================================================== // // This method will take as input the array, the number of array // elements, and the target value to search for. The function will traverse // the array looking for the target value, and when it finds it, display the // index location within the array. // // Input: //       limit [IN]  -- the array, the number of array // elements, and the target value // // Output: //       The total number of occurrences of the target value in the array // // ============================================================================ public static int SearchArray(int[] numValues, int searchValue) { int numFound=0; for (int index=0; index < NUM_INTS; ++index) { if (numValues[index] == searchValue) { System.out.println("t" + searchValue + " was found at array " + "index #" + index); ++numFound; // if the search values was found,            // increment the variable by 1 } } return numFound; }}// 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 3 separate times to display the different outputs its able to produce

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

``` Welcome to My Programming Notes' Java Program. Please enter 5 integer values: #1: 25 #2: 25 #3: 25 #4: 25 #5: 25 Please enter a search value: 25 25 was found at array index #0 25 was found at array index #1 25 was found at array index #2 25 was found at array index #3 25 was found at array index #4 The total occurrences of value 25 within the array is: 5 ====== RUN 2 ====== Welcome to My Programming Notes' Java Program. Please enter 5 integer values: #1: 8 #2: 19 #3: 97 #4: 56 #5: 8 Please enter a search value: 8 8 was found at array index #0 8 was found at array index #4 The total occurrences of value 8 within the array is: 2 ====== RUN 3 ====== Welcome to My Programming Notes' Java Program. Please enter 5 integer values: #1: 78 #2: 65 #3: 3 #4: 45 #5: 89 Please enter a search value: 12 ```

`The total occurrences of value 12 within the array is: 0`

## Java || Find The Average Using an Array – Omit Highest And Lowest Scores

This page will consist of two programs which calculates the average of a specific amount of numbers using an array.

REQUIRED KNOWLEDGE FOR BOTH PROGRAMS

```Double Data Type Final Variables Arrays For Loops Assignment Operators Basic Math - How To Find The Average ```

====== FIND THE AVERAGE USING AN ARRAY ======

The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via stdout.

``` #1 - Find The Average Java import java.util.Scanner; public class FindTheAverage { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int numElems = 0; double sum = 0; double[] average = new double[100]; // declare array which has the ability to hold 100 elements // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // determine how many numbers the user wants in the array System.out.print("How many numbers do you want to find the average for?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter value #" +(index+1)+ ": "); average[index] = cin.nextDouble(); sum += average[index]; } // find the average. // Note: the expression below literally // means: sum = sum / numElems; sum /= numElems; System.out.println("nThe average of the " + numElems + " numbers is " + sum); }// end of main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041 import java.util.Scanner; public class FindTheAverage{ // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int numElems = 0; double sum = 0; double[] average = new double[100]; // declare array which has the ability to hold 100 elements // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // determine how many numbers the user wants in the array System.out.print("How many numbers do you want to find the average for?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter value #" +(index+1)+ ": "); average[index] = cin.nextDouble(); sum += average[index]; } // find the average. // Note: the expression below literally // means: sum = sum / numElems; sum /= numElems; System.out.println("nThe average of the " + numElems + " numbers is " + sum); }// end of main}// http://programmingnotes.org/ ```

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

ARRAY
Notice the array declaration on line #13. The type of array being used in this program is a dynamic array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.

FOR LOOP
Lines 27-32 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different println statements into your code asking the user to input data. Line 31 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.

Once compiled, you should get this as your output:

`Welcome to My Programming Notes' Java Program.`

``` ```

```How many numbers do you want to find the average for?: 4 Enter value #1: 21 Enter value #2: 24 Enter value #3: 19 Enter value #4: 17 The average of the 4 numbers is 20.25 ```

====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======

The second program is really practical in a real world setting. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via stdout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.

``` #2 - Find The Average Omitting The Highest/Lowest Score Java import java.util.Scanner; public class FindOmittedAverage { // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_JUDGES = 6; public static void main(String[] args) { // declare variables double highestScore = -999999; double lowestScore = 999999; double sumOfScores = 0; double avgScores = 0; double[] scores = new double[NUM_JUDGES]; // array is initialized using a final variable // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); System.out.print("Judges, enter one score each for the current competitor: "); // use a for loop to obtain data from user using the final variable for(int index=0; index < NUM_JUDGES; ++index) { // this puts data into the current array index scores[index] = cin.nextDouble(); // this calculates a running total of all the scores // adding each element in the array together sumOfScores += scores[index]; // if current score in the array index is bigger than the current 'highestScore' // value, then set 'highestScore' equal to the current value in the array if(scores[index] > highestScore) { highestScore = scores[index]; } // if current score in the array index is smaller than the current 'lowestScore' // value, then set 'lowestScore' equal to the current value in the array if(lowestScore > scores[index]) { lowestScore = scores[index]; } } System.out.print("nThese are the scores from the " + NUM_JUDGES + " judges: "); // use another for loop to redisplay the data back to the user via stdout for(int index=0; index < NUM_JUDGES; ++index) { System.out.print("nThe score for judge #"+(index+1)+" is: "+scores[index]); } // display the highest/lowest numbers to the screen System.out.print("nnThese are the highest and lowest scores: "); System.out.print("ntHighest: "+ highestScore); System.out.print("ntLowest: "+ lowestScore); // find the average avgScores = sumOfScores/NUM_JUDGES; System.out.print("nThe average score is: "+ avgScores); // reset data back to 0 so we can find the ommitted average sumOfScores = 0; avgScores = 0; System.out.print("nThe average adjusted score omitting the highest and lowest result is: "); // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest scores for(int index=0; index < NUM_JUDGES; ++index) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if((scores[index] != highestScore) && (scores[index] != lowestScore)) { sumOfScores += scores[index]; } } // find the average, minus the 2 scores avgScores = sumOfScores/(NUM_JUDGES-2); System.out.print(avgScores); }// end of main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 import java.util.Scanner; public class FindOmittedAverage{ // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_JUDGES = 6; public static void main(String[] args) { // declare variables double highestScore = -999999; double lowestScore = 999999; double sumOfScores = 0; double avgScores = 0; double[] scores = new double[NUM_JUDGES]; // array is initialized using a final variable // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); System.out.print("Judges, enter one score each for the current competitor: "); // use a for loop to obtain data from  user using the final variable for(int index=0; index < NUM_JUDGES; ++index) { // this puts data into the current array index scores[index] = cin.nextDouble(); // this calculates a running total of all the scores // adding each element in the array together sumOfScores += scores[index]; // if current score in the array index is bigger than the current 'highestScore' // value, then set 'highestScore' equal to the current value in the array if(scores[index] > highestScore) { highestScore = scores[index]; } // if current score in the array index is smaller than the current 'lowestScore' // value, then set 'lowestScore' equal to the current value in the array if(lowestScore > scores[index]) { lowestScore = scores[index]; } } System.out.print("nThese are the scores from the " + NUM_JUDGES + " judges: "); // use another for loop to redisplay the data back to the user via stdout for(int index=0; index < NUM_JUDGES; ++index) { System.out.print("nThe score for judge #"+(index+1)+" is: "+scores[index]); } // display the highest/lowest numbers to the screen System.out.print("nnThese are the highest and lowest scores: "); System.out.print("ntHighest: "+ highestScore); System.out.print("ntLowest: "+ lowestScore); // find the average avgScores = sumOfScores/NUM_JUDGES; System.out.print("nThe average score is: "+ avgScores); // reset data back to 0 so we can find the ommitted average sumOfScores = 0; avgScores = 0; System.out.print("nThe average adjusted score omitting the highest and lowest result is: "); // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest scores for(int index=0; index < NUM_JUDGES; ++index) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if((scores[index] != highestScore) && (scores[index] != lowestScore)) { sumOfScores += scores[index]; } } // find the average, minus the 2 scores avgScores = sumOfScores/(NUM_JUDGES-2); System.out.print(avgScores); }// end of main}// http://programmingnotes.org/ ```

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

FINAL
A final variable was declared and used to initialize the array (line 7). This was used to initialize the size of the array.

FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 24, 51 and 73. The final variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.

HIGHEST/LOWEST SCORES
This is noted on lines 35-45, and it is really simple to understand the process once you see the code.

OMITTING HIGHEST/LOWEST SCORE
Lines 73-81 highlights this process. The loop basically traverses the array, skipping over the highest/lowest elements.

Once compiled, you should get this as your output

`Welcome to My Programming Notes' Java Program.`

``` Judges, enter one score each for the current competitor: 123 453 -789 2 23345 987 These are the scores from the 6 judges: The score for judge #1 is: 123.0 The score for judge #2 is: 453.0 The score for judge #3 is: -789.0 The score for judge #4 is: 2.0 The score for judge #5 is: 23345.0 The score for judge #6 is: 987.0 ```

```These are the highest and lowest scores: Highest: 23345.0 Lowest: -789.0 The average score is: 4020.1666666666665 The average adjusted score omitting the highest and lowest result is: 391.25 ```

## 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[256]; 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[256]; 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++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed

Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:

```(1) Stack Based Infix To Postfix Conversion (Single Digit) (2) Stack Based Postfix Evaluation (Single Digit)```

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Stack Data Structure Cin.getline #include "ClassStackListType.h" ```

A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.

``` Well-Formed Expressions | Ill-Formed Expressions ------------------------------------|-------------------------------------- ( a b c [ ] ) | ( a b c [ ) ( ) [ ] { } | ( ( { ( a b c d e ) ( ) } | [ a b c d e ) ( ) } ( a + [ b - c ] / d ) | ( a + [ b - c } / d ) 123456 Well-Formed Expressions             |           Ill-Formed Expressions------------------------------------|--------------------------------------( a b c [ ] )                       |             ( a b c [ )( ) [ ] { }                         |             ( ({ ( a b c d e ) ( ) }               |             [ a b c d e ) ( ) }( a + [ b - c ] / d )               |             ( a + [ b - c } /  d ) ```

Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:

``` // An algorithm for a Well Formed expression Set 'balanced' to true Set 'symbol' to the first character in the current expression while(there are more characters AND 'balanced' == true) { if('symbol' is an opening symbol) { Push 'symbol' onto the stack } else if('symbol' is a closing symbol) { if the stack is empty 'balanced' = false else Set the 'openSymbol' to the item at the top of the stack Pop the stack Check to see if 'symbol' matches 'openSymbol' (i.e - if openSymbol == '(' and symbol == ')' then 'balanced' = true) } Set 'symbol' to the next character in the current expression } if('balanced' == true AND stack is empty) { Expression is well formed } else { Expression is NOT well formed }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233 // An algorithm for a Well Formed expression Set 'balanced' to trueSet 'symbol' to the first character in the current expression while(there are more characters AND 'balanced' == true){ if('symbol' is an opening symbol) { Push 'symbol' onto the stack } else if('symbol' is a closing symbol) { if the stack is empty 'balanced' = false else Set the 'openSymbol' to the item at the top of the stack Pop the stack Check to see if 'symbol' matches 'openSymbol' (i.e - if openSymbol == '(' and symbol == ')' then 'balanced' = true) } Set 'symbol' to the next character in the current expression} if('balanced' == true AND stack is empty){ Expression is well formed}else{ Expression is NOT well formed}// http://programmingnotes.org/ ```

======= WELL-FORMED EXPRESSIONS =======

This program uses a custom template.h class. To obtain the code for that class, click here.

``` Is The Expression Well-Formed? C++ #include <iostream> #include "ClassStackListType.h" using namespace std; // function prototypes bool IsOpen(char symbol); bool IsClosed(char symbol); bool IsWellFormed(char symbol, char openSymbol); int main() { // declare variables char expression[120]; char openSymbol; int index=0; bool balanced = true; StackListType<char> stack; // this is the stack declaration // obtain data from the user using a char array cout <<"Enter an expression and press ENTER. "<<endl; cin.getline(expression,sizeof(expression)); cout<<"nThe expression: "<<expression; // loop thru the char array until we reach the 'NULL' character // and while 'balanced' == true while(expression[index]!='�' && balanced) { // if input is an "open bracket" push onto stack // else, process info if (IsOpen(expression[index])) { stack.Push(expression[index]); } else if (IsClosed(expression[index])) { if(stack.IsEmpty()) { balanced = false; } else { openSymbol = stack.Top(); stack.Pop(); balanced = IsWellFormed(expression[index], openSymbol); } } ++index; } if(balanced && stack.IsEmpty()) { cout << " is well formed..."<<endl; } else { cout<< " is NOT well formed!!! "<<endl; } }// End of Main bool IsOpen(char symbol) { if((symbol== '(')||(symbol== '{') || (symbol== '[')) { return true; } else { return false; } }// End of IsOpen bool IsClosed(char symbol) { if((symbol == ')')||(symbol=='}')||(symbol== ']')) { return true; } else { return false; } }// End of IsClosed bool IsWellFormed(char symbol, char openSymbol) { return (((openSymbol=='(')&& symbol==')')||((openSymbol=='{')&& symbol=='}') ||((openSymbol == '[')&& symbol == ']')); }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 #include <iostream>#include "ClassStackListType.h"using namespace std; // function prototypesbool IsOpen(char symbol);bool IsClosed(char symbol);bool IsWellFormed(char symbol, char openSymbol); int main(){ // declare variables char expression[120]; char openSymbol; int index=0; bool balanced = true; StackListType<char> stack; // this is the stack declaration  // obtain data from the user using a char array cout <<"Enter an expression and press ENTER. "<<endl; cin.getline(expression,sizeof(expression));  cout<<"nThe expression: "<<expression;  // loop thru the char array until we reach the 'NULL' character // and while 'balanced' == true while(expression[index]!='' && balanced) { // if input is an "open bracket" push onto stack // else, process info if (IsOpen(expression[index])) { stack.Push(expression[index]); } else if (IsClosed(expression[index])) { if(stack.IsEmpty()) { balanced = false; } else { openSymbol = stack.Top(); stack.Pop(); balanced = IsWellFormed(expression[index], openSymbol); } } ++index; }  if(balanced && stack.IsEmpty()) { cout << " is well formed..."<<endl; } else { cout<< " is NOT well formed!!! "<<endl; }}// End of Main bool IsOpen(char symbol){ if((symbol== '(')||(symbol== '{') || (symbol== '[')) { return true; } else { return false; }}// End of IsOpen bool IsClosed(char symbol){ if((symbol == ')')||(symbol=='}')||(symbol== ']')) { return true; } else { return false; }}// End of IsClosed bool IsWellFormed(char symbol, char openSymbol){ return (((openSymbol=='(')&& symbol==')')||((openSymbol=='{')&& symbol=='}') ||((openSymbol == '[')&& symbol == ']'));}// 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 four separate times to display different output)

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

``` Enter an expression and press ENTER. (( The expression: (( is NOT well formed!!! ====== RUN 2 ====== Enter an expression and press ENTER. (a{b[]}c) The expression: (a{b[]}c) is well formed... ====== RUN 3 ====== Enter an expression and press ENTER. [(7 * 28) - 1987] The expression: [(7 * 28) - 1987] is well formed... ====== RUN 4 ====== Enter an expression and press ENTER. {3 + [2 / 3] - (9 + 18) * 12) ```

```The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!! ```

## 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[80]; 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[80];    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...`

## C++ || Class & Input/Output – Display The Contents Of A User Specified Text File To The Screen

The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using the class data structure, which is very similar to the struct data structure.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Header Files - How To Use Them Class - What Is It? How To Read Data From A File String - Getline Array - Cin.Getline Strcpy - Copy Contents Of An Array #Define ```

This program first prompts the user to input a file name. After it obtains a file name from the user, it then attempts to display the contents of the user specified file to the output screen. If the file could not be found, an error message appears. If the file is found, the program continues as normal. After the file contents finishes being displayed, a summary indicating the total number of lines which has been read is also shown to the screen.

This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).

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]`

======== FILE #1 – Main.cpp ========

``` File #1 - Main.cpp C++ // ============================================================================ // File: Main.cpp // ============================================================================ // This program tests the "CFileDisp" object. It prompts the user for an input // filename, then attempts to display the contents of that file to stdout. // After the file contents have been displayed, a summary line indicating the // total number of lines that have been displayed is written to stdout. // ============================================================================ #include <iostream> #include <fstream> #include "CFileDisp.h" using namespace std; // ==== main ================================================================== // // ============================================================================ int main() { CFileDisp myFile; char fname[MAX_LENGTH]; int numLines; // get the filename from the user cout << "Enter a filename: "; cin.getline(fname, MAX_LENGTH); // copy the user's filename into the file object myFile.SetFilename(fname); // have the object open the file myFile.OpenFile(); // if all is good and well... if(myFile.IsValid()==true) { numLines = myFile.DisplayFileContents(); // close the file myFile.CloseFile(); // write how many lines were displayed to stdout cout << "nt*** Total lines displayed: " << numLines << endl; } return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 // ============================================================================// File: Main.cpp // ============================================================================// This program tests the "CFileDisp" object.  It prompts the user for an input// filename, then attempts to display the contents of that file to stdout.// After the file contents have been displayed, a summary line indicating the// total number of lines that have been displayed is written to stdout.// ============================================================================#include <iostream>#include <fstream>#include "CFileDisp.h"using namespace std; // ==== main ==================================================================//// ============================================================================ int main(){ CFileDisp       myFile; char            fname[MAX_LENGTH]; int             numLines; // get the filename from the user cout << "Enter a filename: "; cin.getline(fname, MAX_LENGTH); // copy the user's filename into the file object myFile.SetFilename(fname); // have the object open the file myFile.OpenFile(); // if all is good and well... if(myFile.IsValid()==true) { numLines = myFile.DisplayFileContents(); // close the file myFile.CloseFile(); // write how many lines were displayed to stdout cout << "nt*** Total lines displayed: " << numLines << endl; } return 0;}// http://programmingnotes.org/ ```

======== FILE #2 – CFileDisp.h ========

Remember, you need to name the header file the same as the #include from the Main.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.

``` File #2 - CFileDisp.h C++ // ============================================================================ // File: CFileDisp.h // ============================================================================ // This is the header file which declares the objects which are used to open // a text file and display its contents to stdout. // ============================================================================ #ifndef CFILE_DISP_HEADER #define CFILE_DISP_HEADER #include <fstream> using namespace std; #define MAX_LENGTH 256 class CFileDisp { public: // constructor CFileDisp(); // member functions void SetFilename(char newFilename[]); /* Purpose: Copy the user's filename into the file object */ void OpenFile(); /* Purpose: Open's the file which is specified by the user */ bool IsValid(); /* Purpose: Checks if the file exists. Post: Returns false if file cannot be found */ int DisplayFileContents(); /* Purpose: Display's the file contents to stdout Post: Returns the total number of lines contained in the file */ void CloseFile(); /* Purpose: Closes the file */ // destructor ~CFileDisp(); private: bool m_bIsValid; char m_filename[MAX_LENGTH]; ifstream m_inFile; }; #endif // CFILE_DISP_HEADER // http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243 // ============================================================================// File: CFileDisp.h// ============================================================================// This is the header file which declares the objects which are used to open // a text file and display its contents to stdout.// ============================================================================#ifndef CFILE_DISP_HEADER#define CFILE_DISP_HEADER #include <fstream>using namespace std; #define MAX_LENGTH  256 class   CFileDisp{public: // constructor CFileDisp(); // member functions void SetFilename(char  newFilename[]); /*  Purpose: Copy the user's filename into the file object */ void OpenFile(); /* Purpose: Open's the file which is specified by the user */ bool IsValid(); /* Purpose: Checks if the file exists.    Post: Returns false if file cannot be found */ int DisplayFileContents(); /* Purpose: Display's the file contents to stdout    Post: Returns the total number of lines contained in the file */ void CloseFile(); /* Purpose: Closes the file */ // destructor ~CFileDisp(); private:    bool            m_bIsValid;    char            m_filename[MAX_LENGTH];    ifstream        m_inFile;};#endif   // CFILE_DISP_HEADER // http://programmingnotes.org/ ```

======== FILE #3 – CFileDisp.cpp ========

This is the function implementation file for the CFileDisp.h class. This file can be named anything you wish as long as you #include “CFileDisp.h”

``` File #3 - CFileDisp.cpp C++ // ============================================================================ // File: CFileDisp.cpp // ============================================================================ // This file implements the functions which are declared in the CFileDisp // class, which is located in CFileDisp.h // ============================================================================ #include <iostream> #include <cstring> #include <string> #include "CFileDisp.h" using namespace std; CFileDisp::CFileDisp() { m_bIsValid = 0; }// end of CFileDisp void CFileDisp::SetFilename(char newFilename[]) { strcpy(m_filename,newFilename); }// end of SetFilename void CFileDisp::OpenFile() { m_inFile.open(m_filename); }// end of OpenFile bool CFileDisp::IsValid() { if (m_inFile.fail()) { cout << m_filename << " was not found...nn"; return false; } else { return true; } }// end of IsValid int CFileDisp::DisplayFileContents() { int total=0; string inLine; cout << endl; while(getline(m_inFile, inLine)) { cout << inLine << endl; ++total; } return total; }// end of DisplayFileContents void CFileDisp::CloseFile() { m_inFile.close(); }// end of CloseFile // this is the destructor CFileDisp::~CFileDisp() { m_bIsValid = 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 // ============================================================================// File: CFileDisp.cpp// ============================================================================// This file implements the functions which are declared in the CFileDisp// class, which is located in CFileDisp.h// ============================================================================#include <iostream>#include <cstring>#include <string>#include "CFileDisp.h"using namespace std; CFileDisp::CFileDisp(){ m_bIsValid = 0;}// end of CFileDisp void CFileDisp::SetFilename(char  newFilename[]){    strcpy(m_filename,newFilename);}// end of SetFilename void CFileDisp::OpenFile(){ m_inFile.open(m_filename);}// end of OpenFile bool CFileDisp::IsValid(){ if (m_inFile.fail()) { cout << m_filename << " was not found...nn"; return false; } else { return true; }}// end of IsValid int CFileDisp::DisplayFileContents(){ int total=0; string inLine; cout << endl; while(getline(m_inFile, inLine)) { cout << inLine << endl; ++total; } return total;}// end of DisplayFileContents void CFileDisp::CloseFile(){ m_inFile.close();}// end of CloseFile // this is the destructorCFileDisp::~CFileDisp(){ m_bIsValid = 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

``` Enter a filename: input_file_display_programmingnotes_freeweq_com.txt 346 130 982 90 656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441 190 985 214 509 2 571 77 81 681 651 995 93 74 310 9 995 561 92 14 288 466 664 892 8 766 34 639 151 64 98 813 67 834 369 This is a line of text! *** Total lines displayed: 10 1234567891011121314 Enter a filename: input_file_display_programmingnotes_freeweq_com.txt 346     130     982     90      656     117   595415     948     126     4       558     571   8742      360     412     721     463     47    119441     190     985     214     509     2     57177      81      681     651     995     93    74310     9       995     561     92      14    288466     664     892     8       766     34    639151     64      98      813     67      834   369                 This is a line of text!         *** Total lines displayed: 10 ```

## C++ || Class – Roman Numeral To Integer & Integer To Roman Numeral Conversion

The following is another homework assignment which was presented in a C++ Data Structures course. This program was assigned in order to practice the use of the class data structure, which is very similar to the struct data structure.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Header Files - How To Use Them Class - What Is It? Do/While Loop Passing a Value By Reference Roman Numerals - How Do You Convert To Decimal? Online Roman Numeral Converter - Check For Correct Results ```

This is an interactive program in which the user has the option of selecting from 7 modes of operation. Of those modes, the user has the option of entering in roman numerals for conversion, entering in decimal numbers for conversion, displaying the recently entered number, and finally converting between roman or decimal values.

A sample of the menu is as followed:
(Where the user would enter numbers 1-7 to select a choice)

``` From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 1234567891011 From the following menu: 1.  Enter a Decimal number2.  Enter a Roman Numeral3.  Convert from Decimal to Roman4.  Convert from Roman to Decimal5.  Print the current Decimal number6.  Print the current Roman Numeral7.  Quit Please enter a selection: ```

This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).

======== FILE #1 – Menu.cpp ========

NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.

``` File #1 - Menu.cpp C++ // ============================================================================ // File: Menu.cpp // Purpose: Converts a number enetered in Decimal to Roman Numeral and a // Roman Numeral to a Decimal Number // ============================================================================ #include <iostream> #include <iomanip> #include <string> #include "ClassRomanType.h" using namespace std; // function prototypes void DisplayMenu(); int GetCommand(int command); void RunChoice(int command, ClassRomanType& romanObject); int main() { int command=7; // Holds which action the user chooses to make ClassRomanType romanObject; // Gives access to the class do{ DisplayMenu(); command = GetCommand(command); RunChoice(command, romanObject); cout<<"n--------------------------------------------------------------------n"; }while(command!=7); cout<<"nBye!n"; return 0; }// End of main void RunChoice(int command, ClassRomanType& romanObject) {// Function: Execute the choice selected from the menu // declare private variables int decimalNumber=0; // Holds decimal value char romanNumeral[150]; //Holds value of roman numeral // execute the desired choice cout <<"ntYou selected choice #"<<command<<" which will: "; switch(command) { case 1: cout << "Get Decimal Numbernn"; cout <<"Enter a Decimal Number: "; cin >> decimalNumber; romanObject.GetDecimalNumber(decimalNumber); break; case 2: cout << "Get Roman Numeralnn"; cout <<"nEnter a Roman Numeral: "; cin >> romanNumeral; romanObject.GetRomanNumeral(romanNumeral); break; case 3: cout << "Convert from Decimal to Romannn"; romanObject.ConvertDecimalToRoman(); cout<<"Running....nComplete!n"; break; case 4: cout << "Convert from Roman to Decimalnn"; romanObject.ConvertRomanToDecimal(); cout<<"Running....nComplete!n"; break; case 5: cout << "Print the current Decimal numbernn"; cout<<"n The current Roman to Decimal Value is: "; cout << romanObject.ReturnDecimalNumber()<<endl; break; case 6: cout << "Print the current Roman Numeralnn"; cout<<"n The current Decimal to Roman Value is: "; cout << romanObject.ReturnRomanNumber()<<endl; break; case 7: cout << "Quitnn"; break; default: cout << "nError, you entered an invalid command!nPlease try again..."; break; } }//End of RunChoice int GetCommand(int command) {// Function: Gets choice from menu cout <<"nPlease enter a selection: "; cin>> command; return command; }// End of GetCommand void DisplayMenu() {// Function: Displays menu cout <<"From the following menu:n"<<endl; cout <<left<<setw(2)<<"1."<<left<<setw(15)<<" Enter a Decimal number"<<endl; cout <<left<<setw(2)<<"2."<<left<<setw(15)<<" Enter a Roman Numeral"<<endl; cout <<left<<setw(2)<<"3."<<left<<setw(15)<<" Convert from Decimal to Roman"<<endl; cout <<left<<setw(2)<<"4."<<left<<setw(15)<<" Convert from Roman to Decimal"<<endl; cout <<left<<setw(2)<<"5."<<left<<setw(15)<<" Print the current Decimal number"<<endl; cout <<left<<setw(2)<<"6."<<left<<setw(15)<<" Print the current Roman Numeral"<<endl; cout <<left<<setw(2)<<"7."<<left<<setw(15)<<" Quit"<<endl; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 // ============================================================================//  File: Menu.cpp//  Purpose: Converts a number enetered in Decimal to Roman Numeral and a //  Roman Numeral to a Decimal Number // ============================================================================#include <iostream>#include <iomanip>#include <string>#include "ClassRomanType.h"using namespace std; // function prototypesvoid DisplayMenu();int GetCommand(int command);void RunChoice(int command, ClassRomanType& romanObject); int main(){ int command=7; // Holds which action the user chooses to make ClassRomanType romanObject; // Gives access to the class  do{ DisplayMenu(); command = GetCommand(command); RunChoice(command, romanObject); cout<<"n--------------------------------------------------------------------n"; }while(command!=7);  cout<<"nBye!n";  return 0;}// End of main void RunChoice(int command, ClassRomanType& romanObject){// Function: Execute the choice selected from the menu  // declare private variables int decimalNumber=0; // Holds decimal value char romanNumeral[150]; //Holds value of roman numeral  // execute the desired choice cout <<"ntYou selected choice #"<<command<<" which will: "; switch(command) { case 1: cout << "Get Decimal Numbernn"; cout <<"Enter a Decimal Number: "; cin >> decimalNumber; romanObject.GetDecimalNumber(decimalNumber); break; case 2: cout << "Get Roman Numeralnn"; cout <<"nEnter a Roman Numeral: "; cin >> romanNumeral; romanObject.GetRomanNumeral(romanNumeral); break; case 3: cout << "Convert from Decimal to Romannn"; romanObject.ConvertDecimalToRoman(); cout<<"Running....nComplete!n"; break; case 4: cout << "Convert from Roman to Decimalnn"; romanObject.ConvertRomanToDecimal(); cout<<"Running....nComplete!n"; break; case 5: cout << "Print the current Decimal numbernn"; cout<<"n The current Roman to Decimal Value is: "; cout << romanObject.ReturnDecimalNumber()<<endl; break; case 6: cout << "Print the current Roman Numeralnn"; cout<<"n The current Decimal to Roman Value is: "; cout << romanObject.ReturnRomanNumber()<<endl; break; case 7: cout << "Quitnn"; break; default: cout << "nError, you entered an invalid command!nPlease try again..."; break; }}//End of RunChoice int GetCommand(int command){// Function: Gets choice from menu cout <<"nPlease enter a selection: "; cin>> command; return command;}// End of GetCommand void DisplayMenu(){// Function: Displays menu cout <<"From the following menu:n"<<endl; cout <<left<<setw(2)<<"1."<<left<<setw(15)<<"  Enter a Decimal number"<<endl; cout <<left<<setw(2)<<"2."<<left<<setw(15)<<"  Enter a Roman Numeral"<<endl; cout <<left<<setw(2)<<"3."<<left<<setw(15)<<"  Convert from Decimal to Roman"<<endl; cout <<left<<setw(2)<<"4."<<left<<setw(15)<<"  Convert from Roman to Decimal"<<endl; cout <<left<<setw(2)<<"5."<<left<<setw(15)<<"  Print the current Decimal number"<<endl; cout <<left<<setw(2)<<"6."<<left<<setw(15)<<"  Print the current Roman Numeral"<<endl; cout <<left<<setw(2)<<"7."<<left<<setw(15)<<"  Quit"<<endl;}// http://programmingnotes.org/ ```

======== FILE #2 – ClassRomanType.h ========

Remember, you need to name the header file the same as the #include from the Menu.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.

``` File #2 - ClassRomanType.h C++ // ============================================================================ // File: ClassRomanType.h // Purpose: Header file for Roman Numeral conversion. It contains all // declarations and prototypes for the class members to carry out the // conversion // ============================================================================ #include <string> using namespace std; class ClassRomanType { public: ClassRomanType(); /* Function: constructor initializes class variables to "0" Precondition: none Postcondition: defines private variables */ // member functions void GetDecimalNumber(int decimalNumber); /* Function: gets decimal number Precondition: none Postcondition: Gets arabic number from user */ void GetRomanNumeral(char romanNumeral[]); /* Function: gets roman numeral Precondition: none Postcondition: Gets roman numeral from user */ void ConvertDecimalToRoman(); /* Function: converts decimal number to ronman numeral Precondition: arabic and roman numeral characters should be known Postcondition: Gets roman numeral from user */ void ConvertRomanToDecimal(); /* Function: converts roman numeral to arabic number Precondition: arabic and roman numeral characters should be known Postcondition: Gets decimal number from user */ int ReturnDecimalNumber(); /* Function: displays converted decimal number Precondition: the converted roman numeral to decimal number Postcondition: displays decimal number to user */ string ReturnRomanNumber(); /* Function: displays converted roman numeral Precondition: the converted decimal number to roman numeral Postcondition: displays roman numeral to user */ ~ClassRomanType(); /* Function: destructor used to return memory to the system Precondition: the converted decimal number to roman numeral Postcondition: none */ private: char m_romanValue[150]; // An array holding the roman value within the class int m_decimalValue; // Holds the final output answer of the roman to decimal conversion }; // http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 // ============================================================================//  File:  ClassRomanType.h//  Purpose:  Header file for Roman Numeral conversion. It contains all//  declarations and prototypes for the class members to carry out the //  conversion// ============================================================================#include <string>using namespace std; class   ClassRomanType{public:    ClassRomanType();          /*   Function: constructor initializes class variables to "0"               Precondition: none               Postcondition: defines private variables */  // member functions    void GetDecimalNumber(int  decimalNumber);          /*   Function: gets decimal number Precondition: none Postcondition: Gets arabic number from user */     void GetRomanNumeral(char romanNumeral[]);          /*   Function: gets roman numeral Precondition: none Postcondition: Gets roman numeral from user */     void ConvertDecimalToRoman();          /*   Function: converts decimal number to ronman numeral Precondition: arabic and roman numeral characters should be known Postcondition: Gets roman numeral from user */     void ConvertRomanToDecimal();          /*   Function: converts roman numeral to arabic number Precondition: arabic and roman numeral characters should be known Postcondition: Gets decimal number from user */     int ReturnDecimalNumber();          /*   Function: displays converted decimal number Precondition: the converted roman numeral to decimal number Postcondition: displays decimal number to user */     string ReturnRomanNumber();          /*   Function: displays converted roman numeral Precondition: the converted decimal number to roman numeral Postcondition: displays roman numeral to user */     ~ClassRomanType();          /*   Function: destructor used to return memory to the system Precondition: the converted decimal number to roman numeral Postcondition: none */ private: char m_romanValue[150];  // An array holding the roman value within the class int m_decimalValue; // Holds the final output answer of the roman to decimal conversion}; // http://programmingnotes.org/ ```

======== FILE #3 – RomanType.cpp ========

This is the function implementation file for the ClassRomanType.h class. This file can be named anything you wish as long as you #include “ClassRomanType.h”

``` File #3 - RomanType.cpp C++ // ============================================================================ // File: RomanType.cpp // Purpose: Contains the implementation of the class members for the // roman numeral conversion // // *NOTE*: Uncomment cout statements to visualize whats happening // ============================================================================ #include <iostream> #include <string> #include <cstring> #include "ClassRomanType.h" using namespace std; ClassRomanType::ClassRomanType() { m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined"); }// end of ClassRomanType void ClassRomanType:: GetDecimalNumber(int decimalNumber) { m_decimalValue = decimalNumber; }// end of GetDecimalNumber void ClassRomanType:: GetRomanNumeral(char romanNumeral[]) { strcpy(m_romanValue,romanNumeral); }// end of GetRomanNumeral void ClassRomanType:: ConvertDecimalToRoman() { strcpy(m_romanValue,""); // erases any previous data int numericValue[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,0}; char *romanNumeral[]={"M","CM","D","CD","C","XC","L" ,"XL","X","IX","V","IV","I",0}; for (int x=0; numericValue[x] > 0; ++x) { //cout<<endl<<numericValue[x]<<endl; while (m_decimalValue >= numericValue[x]) { //cout<<"current m_decimalValue = " <<m_decimalValue<<endl; //cout<<"current numericValue = "<<numericValue[x]<<endl<<endl; if(strlen(m_romanValue)==0) { strcpy(m_romanValue,romanNumeral[x]); } else { strcat(m_romanValue,romanNumeral[x]); } m_decimalValue -= numericValue[x]; } } }// end of ConvertDecimalToRoman void ClassRomanType:: ConvertRomanToDecimal() { int currentNumber = 0; // Holds value of each letter numerical value int previousNumber = 0; // Holds the numerical value being compared m_decimalValue=0; // Resets the current 'romanToDecimalValue' to zero if(strcmp(m_romanValue,"Currently Undefined")!=0) { for (int counter = strlen(m_romanValue)-1; counter >= 0; counter--) { if ((m_romanValue[counter] == 'M') || (m_romanValue[counter] == 'm')) { currentNumber = 1000; } else if ((m_romanValue[counter] == 'D') || (m_romanValue[counter] == 'd')) { currentNumber = 500; } else if ((m_romanValue[counter] == 'C') || (m_romanValue[counter] == 'c')) { currentNumber = 100; } else if ((m_romanValue[counter] == 'L') || (m_romanValue[counter] == 'l')) { currentNumber = 50; } else if ((m_romanValue[counter] == 'X') || (m_romanValue[counter] == 'x')) { currentNumber = 10; } else if ((m_romanValue[counter] == 'V') || (m_romanValue[counter] == 'v')) { currentNumber = 5; } else if ((m_romanValue[counter] == 'I') || (m_romanValue[counter] == 'i')) { currentNumber = 1; } else { currentNumber = 0; } //cout<<"previousNumber = " <<previousNumber<<endl; //cout<<"currentNumber = " <<currentNumber<<endl; if (previousNumber > currentNumber) { m_decimalValue -= currentNumber; previousNumber = currentNumber; } else { m_decimalValue += currentNumber; previousNumber = currentNumber; } //cout<<"current m_decimalValue = " <<m_decimalValue<<endl<<endl; } } }// end of ConvertRomanToDecimal int ClassRomanType::ReturnDecimalNumber() { return m_decimalValue; }// end of ReturnDecimalNumber string ClassRomanType::ReturnRomanNumber() { return m_romanValue; }// end of ReturnRomanNumber ClassRomanType::~ClassRomanType() { m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined"); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 // ============================================================================//  File:  RomanType.cpp//  Purpose:  Contains the implementation of the class members for the //  roman numeral conversion//  //  *NOTE*: Uncomment cout statements to visualize whats happening// ============================================================================#include <iostream>#include <string> #include <cstring>#include "ClassRomanType.h"using namespace std; ClassRomanType::ClassRomanType(){ m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined");}// end of ClassRomanType void ClassRomanType:: GetDecimalNumber(int decimalNumber){ m_decimalValue = decimalNumber;}// end of GetDecimalNumber void ClassRomanType:: GetRomanNumeral(char romanNumeral[]){ strcpy(m_romanValue,romanNumeral);}// end of GetRomanNumeral void ClassRomanType:: ConvertDecimalToRoman(){ strcpy(m_romanValue,""); // erases any previous data int numericValue[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,0}; char *romanNumeral[]={"M","CM","D","CD","C","XC","L" ,"XL","X","IX","V","IV","I",0}; for (int x=0; numericValue[x] > 0; ++x) { //cout<<endl<<numericValue[x]<<endl; while (m_decimalValue >= numericValue[x]) { //cout<<"current m_decimalValue = " <<m_decimalValue<<endl; //cout<<"current numericValue = "<<numericValue[x]<<endl<<endl; if(strlen(m_romanValue)==0) { strcpy(m_romanValue,romanNumeral[x]); } else { strcat(m_romanValue,romanNumeral[x]); } m_decimalValue  -= numericValue[x]; } }}// end of ConvertDecimalToRoman void ClassRomanType:: ConvertRomanToDecimal(){ int currentNumber = 0; // Holds value of each letter numerical value int previousNumber = 0; // Holds the numerical value being compared m_decimalValue=0; // Resets the current 'romanToDecimalValue' to zero  if(strcmp(m_romanValue,"Currently Undefined")!=0) { for (int counter = strlen(m_romanValue)-1; counter >= 0; counter--) { if ((m_romanValue[counter] == 'M') || (m_romanValue[counter] == 'm')) { currentNumber = 1000; } else if ((m_romanValue[counter] == 'D') || (m_romanValue[counter] == 'd')) { currentNumber = 500; } else if ((m_romanValue[counter] == 'C') || (m_romanValue[counter] == 'c')) { currentNumber = 100; } else if ((m_romanValue[counter] == 'L') || (m_romanValue[counter] == 'l')) { currentNumber = 50; } else if ((m_romanValue[counter] == 'X') || (m_romanValue[counter] == 'x')) { currentNumber = 10; } else if ((m_romanValue[counter] == 'V') || (m_romanValue[counter] == 'v')) { currentNumber = 5; }   else if ((m_romanValue[counter] == 'I') || (m_romanValue[counter] == 'i')) { currentNumber = 1; } else { currentNumber = 0; } //cout<<"previousNumber = " <<previousNumber<<endl; //cout<<"currentNumber = " <<currentNumber<<endl;  if (previousNumber > currentNumber) { m_decimalValue -= currentNumber; previousNumber = currentNumber; } else { m_decimalValue += currentNumber; previousNumber = currentNumber; } //cout<<"current m_decimalValue = " <<m_decimalValue<<endl<<endl; } }}// end of ConvertRomanToDecimal int ClassRomanType::ReturnDecimalNumber(){ return m_decimalValue;}// end of ReturnDecimalNumber string ClassRomanType::ReturnRomanNumber(){ return  m_romanValue;}// end of ReturnRomanNumber ClassRomanType::~ClassRomanType(){ m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined");}// 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

`From the following menu:`

``` 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 9 You selected choice #9 which will: Error, you entered an invalid command! Please try again... -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 5 You selected choice #5 which will: Print the current Decimal number The current Roman to Decimal Value is: 0 -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 6 You selected choice #6 which will: Print the current Roman Numeral The current Decimal to Roman Value is: Currently Undefined -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 1 You selected choice #1 which will: Get Decimal Number Enter a Decimal Number: 1987 -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 5 You selected choice #5 which will: Print the current Decimal number The current Roman to Decimal Value is: 1987 -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 3 You selected choice #3 which will: Convert from Decimal to Roman Running.... Complete! -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 6 You selected choice #6 which will: Print the current Roman Numeral The current Decimal to Roman Value is: MCMLXXXVII -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 2 You selected choice #2 which will: Get Roman Numeral Enter a Roman Numeral: mMxiI -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 6 You selected choice #6 which will: Print the current Roman Numeral The current Decimal to Roman Value is: mMxiI -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 4 You selected choice #4 which will: Convert from Roman to Decimal Running.... Complete! -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 5 You selected choice #5 which will: Print the current Decimal number The current Roman to Decimal Value is: 2012 -------------------------------------------------------------------- From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. Quit Please enter a selection: 7 ```

``` You selected choice #7 which will: Quit -------------------------------------------------------------------- Bye! ```

## C++ || “One Size Fits All” – BubbleSort Which Works For Integer, Float, & Char Arrays

Here is another sorting algorithm, which sorts data that is contained in an array. The difference between this method, and the previous methods of sorting data is that this method works with multiple data types, all in one function. So for example, if you wanted to sort an integer and a character array within the same program, the code demonstrated on this page has the ability to sort both data types, eliminating the need to make two separate sorting functions for the two different data types.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Integer Arrays Character Arrays BubbleSort Pointers Function Pointers - What Are They? Memcpy Sizeof Sizet Malloc```

``` BubbleSort - One Size Fits All C++ #include <iostream> #include <cstdlib> #include <cctype> #include <iomanip> #include <cstring> #include <ctime> using namespace std; // function prototypes void BubbleSort(void* list, size_t nelm, size_t size, int (*cmp) (const void*, const void*)); void Swap(void* a, void* b, size_t width); int IntCompare (const void * a, const void * b); int StrCompare(const void *a, const void *b); int FloatCompare (const void * a, const void * b); // constant variable for int arrays const int NUM_INTS=14; int main() { // seed random number generator srand(time(NULL)); // =================== INT EXAMPLE =================== // int intNumbers[100]; int numInts=0; // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { intNumbers[x] =rand()%100+1; } cout<<"Original values in the int array:n"; // show original data to the user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // this is the function call, which takes in an // integer array for sorting purposes // NOTICE: the function "IntCompare" is being used as a parameter BubbleSort(intNumbers,NUM_INTS,sizeof(int),IntCompare); cout<<"nnThe sorted values in the int array:n"; // display sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // =================== FLOAT EXAMPLE =================== // float floatNumbers[100]; // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { floatNumbers[x] =(rand()%100+1)+(0.5); } cout<<"Original values in the float array:n"; // show original array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // this is the function call, which takes in a // float array for sorting purposes // NOTICE: the function "FloatCompare" is being used as a parameter BubbleSort(floatNumbers,NUM_INTS,sizeof(float),FloatCompare); cout<<"nnThe sorted values in the float array:n"; // show sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // =================== CHAR EXAMPLE =================== // char* names[100]={"This", "Is","Random","Text","Brought","To", "You","By","My","Programming","Notes"}; int numNames=11; cout<<"Original values in the char array:n"; // show original array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } // this is the function call, which takes in a // char array for sorting purposes // NOTICE: the function "StrCompare" is being used as a parameter BubbleSort(names,numNames,sizeof(char*),StrCompare); cout<<"nnThe sorted values in the char array:n"; // show sorted array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } cout<<endl; return 0; }// end of main void BubbleSort(void* arry, size_t nelm, size_t size, int (*cmp) (const void*, const void*)) {// this function sorts the received array bool sorted = false; do{ sorted = true; for(unsigned int x=0; x < nelm-1; ++x) { if(cmp((((char*)arry)+(x*size)), (((char*)arry)+((x+1)*size))) > 0) { Swap((((char*)arry)+((x)*size)), (((char*)arry)+((x+1)*size)),size); sorted=false; } } --nelm; }while(!sorted); }// end of BubbleSort void Swap(void* a, void* b, size_t width) {// this function swaps the values in the array void *tmp = malloc(width); memcpy(tmp, a, width); memcpy(a, b, width); memcpy(b, tmp, width); free(tmp); }// end of Swap int FloatCompare (const void * a, const void * b) {// this function compares two float values together return (*(float*)a - *(float*)b); }// end of FloatCompare int IntCompare (const void * a, const void * b) {// this function compares two int values together return (*(int*)a - *(int*)b); }// end of IntCompare int StrCompare(const void *a, const void *b) {// this function compares two char values together return(strcmp(*(const char **)a, *(const char **)b)); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 #include <iostream>#include <cstdlib>#include <cctype>#include <iomanip>#include <cstring>#include <ctime>using namespace std; // function prototypesvoid BubbleSort(void* list, size_t nelm, size_t size, int (*cmp) (const void*, const void*));void Swap(void* a, void* b, size_t width);int IntCompare (const void * a, const void * b);int StrCompare(const void *a, const void *b);int FloatCompare (const void * a, const void * b); // constant variable for int arraysconst int NUM_INTS=14; int main(){ // seed random number generator srand(time(NULL));  // ===================    INT EXAMPLE    =================== // int intNumbers[100]; int numInts=0;   // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { intNumbers[x] =rand()%100+1; }   cout<<"Original values in the int array:n"; // show original data to the user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // this is the function call, which takes in an // integer array for sorting purposes // NOTICE: the function "IntCompare" is being used as a parameter BubbleSort(intNumbers,NUM_INTS,sizeof(int),IntCompare); cout<<"nnThe sorted values in the int array:n"; // display sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; }  // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // ===================    FLOAT EXAMPLE    =================== // float floatNumbers[100];  // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { floatNumbers[x] =(rand()%100+1)+(0.5); } cout<<"Original values in the float array:n"; // show original array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // this is the function call, which takes in a // float array for sorting purposes // NOTICE: the function "FloatCompare" is being used as a parameter BubbleSort(floatNumbers,NUM_INTS,sizeof(float),FloatCompare); cout<<"nnThe sorted values in the float array:n"; // show sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n";  // ===================    CHAR EXAMPLE    =================== // char* names[100]={"This", "Is","Random","Text","Brought","To", "You","By","My","Programming","Notes"}; int numNames=11;   cout<<"Original values in the char array:n"; // show original array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } // this is the function call, which takes in a // char array for sorting purposes // NOTICE: the function "StrCompare" is being used as a parameter BubbleSort(names,numNames,sizeof(char*),StrCompare); cout<<"nnThe sorted values in the char array:n"; // show sorted array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } cout<<endl;  return 0;}// end of main void BubbleSort(void* arry, size_t nelm, size_t size, int (*cmp) (const void*, const void*)){// this function sorts the received array bool sorted = false; do{ sorted = true; for(unsigned int x=0; x < nelm-1; ++x) { if(cmp((((char*)arry)+(x*size)), (((char*)arry)+((x+1)*size))) > 0) { Swap((((char*)arry)+((x)*size)), (((char*)arry)+((x+1)*size)),size); sorted=false; } } --nelm; }while(!sorted);}// end of BubbleSort  void Swap(void* a, void* b, size_t width){// this function swaps the values in the array void *tmp = malloc(width); memcpy(tmp, a, width); memcpy(a, b, width); memcpy(b, tmp, width); free(tmp);}// end of Swap int FloatCompare (const void * a, const void * b){// this function compares two float values together return (*(float*)a - *(float*)b);}// end of FloatCompare int IntCompare (const void * a, const void * b){// this function compares two int values together return (*(int*)a - *(int*)b);}// end of IntCompare int StrCompare(const void *a, const void *b){// this function compares two char values together  return(strcmp(*(const char **)a, *(const char **)b));}// http://programmingnotes.org/ ```

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

Notice, the same function declaration is being used for all 3 different data types, with the only difference between each function call are the parameters which are being sent out.

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 function works for all three data types)

``` Original values in the int array: 44 91 43 22 20 100 77 80 84 60 47 91 51 81```

``` The sorted values in the int array: 20 22 43 44 47 51 60 77 80 81 84 91 91 100 --------------------------------------------------------------------------------------- Original values in the float array: 49.5 30.5 67.5 50.5 29.5 89.5 78.5 80.5 54.5 7.5 54.5 38.5 56.5 70.5 The sorted values in the float array: 7.5 29.5 30.5 38.5 49.5 50.5 54.5 54.5 56.5 67.5 70.5 78.5 80.5 89.5 --------------------------------------------------------------------------------------- Original values in the char array: This Is Random Text Brought To You By My Programming Notes ```

```The sorted values in the char array: Brought By Is My Notes Programming Random Text This To You ```