## C++ || Stack Based Postfix Evaluation (Single Digit)

This page consists of another homework assignment which was presented in a C++ Data Structures course. While the previously discussed program dealt with converting Infix expressions to Postfix, this program will demonstrate exactly how to evaluate them.

NOTE: Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```What Is Postfix? How To Convert Infix To Postfix Equations Stack Data Structure Cin.getline How To Evaluate Postfix Expressions The Order Of Operations #include "ClassStackType.h"```

The title of this page is called – “Stack Based Postfix Evaluation (Single Digit).” Why “single digit?” The program demonstrated on this page has the ability to evaluate a postfix equation, but it only has the ability to evaluate single digit values. What do I mean by that? Consider the infix equation: 5+2. When that expression is converted to postfix, it will come out to be: 52+, and the answer will be 7 (5+2=7). But what if we have an equation like 12+2? When that expression is converted to postfix, it will come out to be: 122+. The postfix conversion is correct, but when you try to evaluate the expression, we do not know if the math operation should be 12+2 or 1+22, it can be read either way.

Question: So why is this program being displayed if it only works for single digits?
Answer: Because it demonstrates the process of evaluating postfix equations very well.

Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!

Before we get into things, here is a helpful algorithm for evaluating a postfix expression in pseudo code:

``` // An algorithm for postfix evaluation. // For example, (1 + 2) / (5 + 6) translates to 1 2 + 5 6 + / // which equals the result of 0.272727 // Valid operands are single digits: 0-9 // Valid operators are: +, -, *, /, ^, \$ // Highest precedence: ^, \$ // Lowest precedence: +,- // the operators ')' and '('never goes on stack. double EvaluatePostfix(char* postfix) { while there is input { if input is a number push current number on stack else if input is a math operator and stack is not empty set operand2 to the top of the operand stack pop the stack set operand1 to the top of the operand stack pop the stack apply the math operation that represents to operand1 and operand2 push the result onto the stack else error } // When the loop is finished, the operand stack will contain one item, // the result of evaluating the expression pop the stack return the answer to the caller }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 // An algorithm for postfix evaluation.// For example,  (1 + 2) / (5 + 6) translates to  1 2 + 5 6 + /// which equals the result of 0.272727// Valid operands are single digits: 0-9// Valid operators are: +, -, *, /, ^, \$// Highest precedence: ^, \$// Lowest precedence: +,-// the operators ')' and '('never goes on stack. double EvaluatePostfix(char* postfix){  while there is input  { if input is a number push current number on stack else if input is a math operator and stack is not empty set operand2 to the top of the operand stack pop the stack set operand1 to the top of the operand stack pop the stack apply the math operation that represents to operand1 and operand2 push the result onto the stack else error  }     // When the loop is finished, the operand stack will contain one item, // the result of evaluating the expression  pop the stack  return the answer to the caller}// http://programmingnotes.org/ ```

Once you understand the process of converting from infix to postfix, adding the ability to evaluate multiple digits within this program should be doable.

======= POSTFIX EVALUATION =======

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

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

Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!

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 three separate times to display different output)

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

``` ==== Postfix Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Postfix Equation: 45^14*232+\$2-/12%24*/* Please enter a postfix expression: 1 2 + 5 6 + / The postfix expression = 1 2 + 5 6 + / Calculations: 1+2 = 3 5+6 = 11 3/11 = 0.272727 Final answer = 0.272727 ====== RUN 2 ====== ==== Postfix Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Postfix Equation: 45^14*232+\$2-/12%24*/* Please enter a postfix expression: 35*76^+ The postfix expression = 35*76^+ Calculations: 3*5 = 15 7^6 = 117649 15+117649 = 117664 Final answer = 117664 ====== RUN 3 ====== ==== Postfix Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Postfix Equation: 45^14*232+\$2-/12%24*/* Please enter a postfix expression: 45^4*32+\$2-/12%24*/* The postfix expression = 45^4*32+\$2-/12%24*/* ```

```Calculations: 4^5 = 1024 1024*4 = 4096 3+2 = 5 √5 = 2.23607 2.23607-2 = 0.236068 4096/0.236068 = 17350.9 1%2 = 1 2*4 = 8 1/8 = 0.125 17350.9*0.125 = 2168.87 Final answer = 2168.87```

## C++ || Stack Based Infix To Postfix Conversion (Single Digit)

This page consists of another homework assignment which was presented in a C++ Data Structures course. No matter which institution you attend, it seems every instructor assigns a program similar to this at one time or another.

Want to evaluate a postfix expression? Click here.

Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```What Is Infix? What Is Postfix? Stack Data Structure Cin.getline How To Convert To Postfix The Order Of Operations #include "ClassStackType.h"```

The program demonstrated on this page has the ability to convert a normal infix equation to postfix equation, so for example, if the user enters the infix equation of (1*2)+3, the program will display the postfix result of 12*3+.

Before we get into things, here is a helpful algorithm for converting from infix to postfix in pseudo code:

======= INFIX TO POSTFIX CONVERSION =======

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

``` Infix To Postfix Conversion (Single Digit) C++ // ============================================================================ // Author: K Perkins // Date: Mar 23, 2012 // Taken From: http://programmingnotes.org/ // File: PostfixConversion.cpp // Description: Demonstrate the use of a stack based infix to // postfix conversion. // ============================================================================ #include <iostream> #include <cctype> #include <cstdlib> #include <cstring> #include "ClassStackType.h" using namespace std; // function prototypes void DisplayDirections(); void ConvertInfixToPostfix(char* infix); int OrderOfOperations(char token); bool IsMathOperator(char token); int main() { // declare variables char expression[50]; // array holding the infix data // display directions to user DisplayDirections(); // get data from user cout<<"\nPlease enter an infix expression: "; cin.getline(expression, sizeof(expression)); cout <<"\nThe Infix expression = "<<expression<<endl; ConvertInfixToPostfix(expression); cout<<"The Postfix expression = "<<expression<<endl; return 0; }// end of main void DisplayDirections() { cout << "\n==== Infix to Postfix Conversion ====\n" <<"\nMath Operators:\n" <<"+ || Addition\n" <<"- || Subtraction\n" <<"* || Multiplication\n" <<"/ || Division\n" <<"% || Modulus\n" <<"^ || Power\n" <<"\$ || Square Root\n" <<"Sample Infix Equation: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4)\n"; }// end of DisplayDirections void ConvertInfixToPostfix(char* infix) { // declare function variables int infixCounter = 0; int postfixCounter = 0; char token = 'a'; char postfix[50]; StackType<char> charStack; // loop thru array until there is no more data while(infix[infixCounter] != '\0') { // push numbers/letters onto 'postfix' array if(isdigit(infix[infixCounter]) || isalpha(infix[infixCounter])) { postfix[postfixCounter] = infix[infixCounter]; ++postfixCounter; } else if(isspace(infix[infixCounter])) { // DO NOTHING } else if(IsMathOperator(infix[infixCounter])) { // if stack is empty, place first math operator onto stack token = infix[infixCounter]; if(charStack.IsEmpty()) { charStack.Push(token); } else { // get the current math operator from the top of the stack token = charStack.Top(); charStack.Pop(); // use the 'OrderOfOperations' function to check equality // of the math operators while(OrderOfOperations(token) >= OrderOfOperations(infix[infixCounter])) { // if stack is empty, do nothing if(charStack.IsEmpty()) { break; } // place the popped math operator from above ^ // onto the postfix array else { postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } // push any remainding math operators onto the stack charStack.Push(token); charStack.Push(infix[infixCounter]); } } // push outer parentheses onto stack else if(infix[infixCounter] == '(') { charStack.Push(infix[infixCounter]); } else if(infix[infixCounter] == ')') { // pop the current math operator from the stack token = charStack.Top(); charStack.Pop(); while(token != '(' && !charStack.IsEmpty()) { // place the math operator onto the postfix array postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } else { cout<<"\nINVALID INPUT\n"; exit(1); } ++infixCounter; } // place any remaining math operators from the stack onto // the postfix array while(!charStack.IsEmpty()) { postfix[postfixCounter] = charStack.Top(); ++postfixCounter; charStack.Pop(); } postfix[postfixCounter] = '\0'; // copy the data from the postfix array into the infix array // the data in the infix array gets sent back to main // since the array is passed by reference strcpy(infix,postfix); }// end of ConvertInfixToPostfix int OrderOfOperations(char token) {// this function checks priority of each math operator int priority = 0; if(token == '^'|| token == '\$') { priority = 4; } else if(token == '*' || token == '/' || token == '%') { priority = 3; } else if(token == '-') { priority = 2; } else if(token == '+') { priority = 1; } return priority; }// end of OrderOfOperations bool IsMathOperator(char token) {// this function checks if operand is a math operator switch(token) { case '+': return true; break; case '-': return true; break; case '*': return true; break; case '/': return true; break; case '%': return true; break; case '^': return true; break; case '\$': return true; break; default: return false; break; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216 // ============================================================================//     Author: K Perkins//     Date:   Mar 23, 2012//     Taken From: http://programmingnotes.org///     File:  PostfixConversion.cpp//     Description: Demonstrate the use of a stack based infix to //         postfix conversion.// ============================================================================#include <iostream>#include <cctype>#include <cstdlib>#include <cstring>#include "ClassStackType.h"using namespace std; // function prototypesvoid DisplayDirections();void ConvertInfixToPostfix(char* infix);int OrderOfOperations(char token);bool IsMathOperator(char token); int main(){ // declare variables char expression[50]; // array holding the infix data // display directions to user DisplayDirections(); // get data from user cout<<"\nPlease enter an infix expression: "; cin.getline(expression, sizeof(expression)); cout <<"\nThe Infix expression = "<<expression<<endl; ConvertInfixToPostfix(expression); cout<<"The Postfix expression = "<<expression<<endl; return 0;}// end of main void DisplayDirections(){ cout << "\n==== Infix to Postfix Conversion ====\n" <<"\nMath Operators:\n" <<"+ || Addition\n" <<"- || Subtraction\n" <<"* || Multiplication\n" <<"/ || Division\n" <<"% || Modulus\n" <<"^ || Power\n" <<"\$ || Square Root\n" <<"Sample Infix Equation: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4)\n";}// end of DisplayDirections void ConvertInfixToPostfix(char* infix){ // declare function variables int infixCounter = 0; int postfixCounter = 0; char token = 'a'; char postfix[50]; StackType<char> charStack; // loop thru array until there is no more data while(infix[infixCounter] != '\0') { // push numbers/letters onto 'postfix' array if(isdigit(infix[infixCounter]) || isalpha(infix[infixCounter])) { postfix[postfixCounter] = infix[infixCounter]; ++postfixCounter; } else if(isspace(infix[infixCounter])) { // DO NOTHING } else if(IsMathOperator(infix[infixCounter])) { // if stack is empty, place first math operator onto stack token = infix[infixCounter]; if(charStack.IsEmpty()) { charStack.Push(token); } else { // get the current math operator from the top of the stack token = charStack.Top(); charStack.Pop(); // use the 'OrderOfOperations' function to check equality // of the math operators while(OrderOfOperations(token) >= OrderOfOperations(infix[infixCounter])) { // if stack is empty, do nothing if(charStack.IsEmpty()) { break; } // place the popped math operator from above ^ // onto the postfix array else { postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } // push any remainding math operators onto the stack charStack.Push(token); charStack.Push(infix[infixCounter]); } } // push outer parentheses onto stack else if(infix[infixCounter] == '(') { charStack.Push(infix[infixCounter]); } else if(infix[infixCounter] == ')') { // pop the current math operator from the stack token = charStack.Top(); charStack.Pop(); while(token != '(' && !charStack.IsEmpty()) { // place the math operator onto the postfix array postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } else { cout<<"\nINVALID INPUT\n"; exit(1); } ++infixCounter; } // place any remaining math operators from the stack onto // the postfix array while(!charStack.IsEmpty()) { postfix[postfixCounter] = charStack.Top(); ++postfixCounter; charStack.Pop(); } postfix[postfixCounter] = '\0'; // copy the data from the postfix array into the infix array // the data in the infix array gets sent back to main // since the array is passed by reference strcpy(infix,postfix);}// end of ConvertInfixToPostfix int OrderOfOperations(char token){// this function checks priority of each math operator int priority = 0; if(token == '^'|| token == '\$') { priority = 4; } else if(token == '*' || token == '/' || token == '%') { priority = 3; } else if(token == '-') { priority = 2; } else if(token == '+') { priority = 1; } return priority; }// end of OrderOfOperations bool IsMathOperator(char token){// this function checks if operand is a math operator     switch(token)     { case '+': return true; break; case '-': return true; break; case '*': return true; break; case '/': return true; break; case '%': return true; break; case '^': return true; break; case '\$': return true; break;   default: return false; break; }}// http://programmingnotes.org/ ```

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

Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!

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

Want to evaluate a postfix expression? Click here for sample code.

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

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

``` ==== Infix to Postfix Conversion ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Infix Equation: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4) Please enter an infix expression: ((a+b)+c)/(d^e) The Infix expression = ((a+b)+c)/(d^e) The Postfix expression = ab+c+de^/ ====== RUN 2 ====== ==== Infix to Postfix Conversion ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Infix Equation: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4) Please enter an infix expression: (3*5)+(7^6) The Infix expression = (3*5)+(7^6) The Postfix expression = 35*76^+ ====== RUN 3 ====== ==== Infix to Postfix Conversion ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root Sample Infix Equation: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4) ```

```Please enter an infix expression: (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4) The Infix expression = (((4^5)*14)/(\$(23+2)-2))*(1%2)/(2*4) The Postfix expression = 45^14*232+\$2-/12%24*/*```

## C++ || Snippet – Array Based Custom Template Stack Sample Code

This page will consist of sample code for a custom array based template stack.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Classes Template Classes - What Are They? Stacks LIFO - What Is It? #include < stack>```

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

``` #include 'ClassStackType.h' C++ // ============================================================================ // Author: K Perkins // Date: Mar 22, 2012 // Taken From: http://programmingnotes.org/ // File: ClassStackType.h // Description: This is a class which implements various functions // demonstrating the use of a stack. // ============================================================================ #include <iostream> template <class ItemType> class StackType { public: StackType(); /* Function: constructor initializes class variables Precondition: none Postcondition: defines private variables */ bool IsEmpty(); /* Function: Determines whether the stack is empty Precondition: Stack has been initialized Postcondition: Function value = (stack is empty) */ bool IsFull(); /* Function: Determines whether the stack is full Precondition: Stack has been initialized Postcondition: Function value = (stack is full) */ int Size(); /* Function: Return the current size of the stack Precondition: Stack has been initialized Postcondition: If (stack is full) exception FullStack is thrown else newItem is at the top of the stack */ void MakeEmpty(); /* Function: Empties the stack Precondition: Stack has been initialized Postcondition: Stack is empty */ void Push(ItemType newItem); /* Function: Adds newItem to the top of the stack Precondition: Stack has been initialized Postcondition: If (stack is full) exception FullStack is thrown else newItem is at the top of the stack */ ItemType Pop(); /* Function: Returns & then removes top item from the stack Precondition: Stack has been initialized Postcondition: If (stack is empty) exception EmptyStack is thrown else top element has been removed from the stack */ ItemType Top(); /* Function: Returns the top item from the stack Precondition: Stack has been initialized Postcondition: If (stack is empty) exception EmptyStack is thrown else top element has been removed from the stack */ ~StackType(); /* Function: destructor deallocates class variables Precondition: none Postcondition: deallocates private variables */ private: int top; // indicates which element is on top int MAX_ITEMS; // max number of items in the list ItemType stack[200]; // array holding the popped/pushed data }; //========================= Implementation ================================// template<class ItemType> StackType<ItemType>::StackType() { top = -1; MAX_ITEMS = 200; }// End of StackType template<class ItemType> bool StackType<ItemType>::IsEmpty() { return (top == -1); }// End of IsEmpty template<class ItemType> bool StackType<ItemType>::IsFull() { return (top==(MAX_ITEMS-1)); }// End of IsFull template<class ItemType> int StackType<ItemType>::Size() { if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return top+1; }// End of Size template<class ItemType> void StackType<ItemType>::MakeEmpty() { top = -1; }// End of MakeEmpty template<class ItemType> void StackType<ItemType>::Push(ItemType newItem) { if(IsFull()) { std::cout<<"nSTACK FULLn"; return; } stack[++top]=newItem; }// End of Push template<class ItemType> ItemType StackType<ItemType>::Pop() { if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return(stack[top--]); }// End of Pop template<class ItemType> ItemType StackType<ItemType>::Top() { if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return(stack[top]); }// End of Top template<class ItemType> StackType<ItemType>::~StackType() { top = -1; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 // ============================================================================//     Author: K Perkins//     Date:   Mar 22, 2012//     Taken From: http://programmingnotes.org///     File:  ClassStackType.h//     Description: This is a class which implements various functions//          demonstrating the use of a stack. // ============================================================================#include <iostream> template <class ItemType>class StackType{public: StackType(); /*   Function: constructor initializes class variables Precondition: none Postcondition: defines private variables */ bool IsEmpty(); /*   Function: Determines whether the stack is empty Precondition: Stack has been initialized Postcondition: Function value = (stack is empty) */ bool IsFull(); /*   Function: Determines whether the stack is full Precondition: Stack has been initialized Postcondition: Function value = (stack is full) */ int Size(); /*   Function: Return the current size of the stack Precondition: Stack has been initialized Postcondition: If (stack is full) exception FullStack is thrown else newItem is at the top of the stack */ void MakeEmpty(); /*   Function: Empties the stack Precondition: Stack has been initialized Postcondition: Stack is empty */ void Push(ItemType newItem); /*   Function: Adds newItem to the top of the stack Precondition: Stack has been initialized Postcondition: If (stack is full) exception FullStack is thrown else newItem is at the top of the stack */ ItemType Pop(); /*   Function: Returns & then removes top item from the stack Precondition: Stack has been initialized Postcondition: If (stack is empty) exception EmptyStack is thrown else top element has been removed from the stack */ ItemType Top(); /*   Function: Returns the top item from the stack Precondition: Stack has been initialized Postcondition: If (stack is empty) exception EmptyStack is thrown else top element has been removed from the stack */ ~StackType(); /*   Function: destructor deallocates class variables Precondition: none Postcondition: deallocates private variables */ private: int top; // indicates which element is on top int MAX_ITEMS;     // max number of items in the list ItemType stack[200]; // array holding the popped/pushed data}; //=========================  Implementation  ================================// template<class ItemType>StackType<ItemType>::StackType(){ top = -1; MAX_ITEMS = 200;}// End of StackType template<class ItemType>bool StackType<ItemType>::IsEmpty(){ return (top == -1);}// End of IsEmpty template<class ItemType>bool StackType<ItemType>::IsFull(){ return (top==(MAX_ITEMS-1));}// End of IsFull template<class ItemType>int StackType<ItemType>::Size(){ if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return top+1;}// End of Size template<class ItemType>void StackType<ItemType>::MakeEmpty(){ top = -1;}// End of MakeEmpty template<class ItemType>void StackType<ItemType>::Push(ItemType newItem){ if(IsFull()) { std::cout<<"nSTACK FULLn"; return; } stack[++top]=newItem;}// End of Push template<class ItemType>ItemType StackType<ItemType>::Pop(){ if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return(stack[top--]);}// End of Pop template<class ItemType>ItemType StackType<ItemType>::Top(){ if(IsEmpty()) { std::cout<<"nSTACK EMPTYn"; return('?'); } return(stack[top]);}// End of Top template<class ItemType>StackType<ItemType>::~StackType(){ top = -1;}// http://programmingnotes.org/ ```

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

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

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

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

``` How To Use #include 'ClassStackType.h' C++ #include <iostream> #include "ClassStackType.h" using namespace std; int main() { // declare variables StackType<char> charStack; StackType<int> intStack; StackType<float> floatStack; // ------ Char Example ------// char charArry[]="My Programming Notes"; int counter=0; while(charArry[counter]!='�') { charStack.Push(charArry[counter]); ++counter; } cout<<"charStack has "<<charStack.Size()<<" items in itn" <<"and contains the text: "<<charArry<<" backwards "; while(!charStack.IsEmpty()) { cout<<charStack.Pop(); } cout<<endl; // ------ Int Example ------// int intArry[]={1,2,3,4,5,6,7,8,9}; counter=0; while(counter<9) { intStack.Push(intArry[counter]); ++counter; } cout<<"intStack has "<<intStack.Size()<<" items in it.n" <<"The sum of the numbers in the stack is: "; counter=0; while(!intStack.IsEmpty()) { counter+=intStack.Pop(); } cout<<counter<<endl; // ------ Float Example ------// float floatArry[]={1.6,2.8,3.9,4.4,5.987,6.23,7.787,8.99,9.6,1.540}; float sum=0; counter=0; while(counter<10) { floatStack.Push(floatArry[counter]); ++counter; } cout<<"floatStack has "<<floatStack.Size()<<" items in it.n" <<"The sum of the numbers in the stack is: "; while(!floatStack.IsEmpty()) { sum+=floatStack.Pop(); } cout<<sum<<endl; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 #include <iostream>#include "ClassStackType.h"using namespace std; int  main(){    // declare variables StackType<char> charStack; StackType<int> intStack; StackType<float> floatStack; // ------ Char Example ------// char charArry[]="My Programming Notes"; int counter=0; while(charArry[counter]!='') { charStack.Push(charArry[counter]); ++counter; } cout<<"charStack has "<<charStack.Size()<<" items in itn" <<"and contains the text: "<<charArry<<" backwards "; while(!charStack.IsEmpty()) { cout<<charStack.Pop(); } cout<<endl; // ------ Int Example ------// int intArry[]={1,2,3,4,5,6,7,8,9}; counter=0; while(counter<9) { intStack.Push(intArry[counter]); ++counter; } cout<<"intStack has "<<intStack.Size()<<" items in it.n" <<"The sum of the numbers in the stack is: "; counter=0; while(!intStack.IsEmpty()) { counter+=intStack.Pop(); } cout<<counter<<endl; // ------ Float Example ------// float floatArry[]={1.6,2.8,3.9,4.4,5.987,6.23,7.787,8.99,9.6,1.540}; float sum=0; counter=0; while(counter<10) { floatStack.Push(floatArry[counter]); ++counter; } cout<<"floatStack has "<<floatStack.Size()<<" items in it.n" <<"The sum of the numbers in the stack is: "; while(!floatStack.IsEmpty()) { sum+=floatStack.Pop(); } cout<<sum<<endl; }// http://programmingnotes.org/ ```

Once compiled, you should get this as your output

``` charStack has 20 items in it and contains the text: My Programming Notes backwards setoN gnimmargorP yM```

``` intStack has 9 items in it. The sum of the numbers in the stack is: 45 ```

```floatStack has 10 items in it. The sum of the numbers in the stack is: 52.834 ```

## C++ || Snippet – How To Reverse An Integer Using Modulus & While Loop

This page will consist of a simple program which demonstrates how to reverse an integer (not an int array) using modulus and a while loop.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Functions Modulus While Loops```

``` Reversing An Integer C++ #include <iostream> using namespace std; // function prototype int ReverseNumber(int number); int main() { // declare variables int number = 0; int numReversed = 0; // get data from user cout << "Enter a number: "; cin >> number; // function call which will return the reversed number numReversed = ReverseNumber(number); // display new data to user cout <<endl<< number << " reversed is: "<< numReversed <<endl; return 0; }// end of main int ReverseNumber(int number) { // declare function variable int rev=0; while(number > 0) { rev = rev * 10 + (number % 10); number = number/10; } return rev; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738 #include <iostream>using namespace std; // function prototypeint ReverseNumber(int number); int main(){ // declare variables int number = 0; int numReversed = 0;  // get data from user cout << "Enter a number: "; cin >> number;  // function call which will return the reversed number numReversed = ReverseNumber(number);  // display new data to user cout <<endl<< number << " reversed is: "<< numReversed <<endl;  return 0;}// end of main int ReverseNumber(int number){ // declare function variable int rev=0;  while(number > 0) { rev = rev * 10 + (number % 10); number = number/10; }  return rev;}// 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 a number: 2012 2012 reversed is: 2102 ==== RUN #2 ==== Enter a number: 1987 1987 reversed is: 7891 ==== RUN #3 ==== ```

```Enter a number: 241 241 reversed is: 142 ```

## Java || Using If Statements, Char & String Variables

As previously mentioned, you can use the “int/float/double” data type to store numbers. But what if you want to store letters? Char and Strings help you do that.

===== SINGLE CHAR =====

This example will demonstrate a simple program using char, which checks to see if you inputted the correctly predefined letter

``` #1 - Guess a letter Java import java.util.Scanner; public class GuessALetter { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables char userInput =' '; System.out.print("Please try to guess the letter I am thinking of: "); // get a single character from the user data input userInput = cin.next().charAt(0); // Use an If Statement to check equality if (userInput == 'a' || userInput == 'A') { System.out.print("You have Guessed correctly!n"); } else { System.out.print("Sorry, that was not the correct letter I was thinking ofn"); } }// end main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 import java.util.Scanner; public class GuessALetter{    // global variable declaration    static Scanner cin = new Scanner(System.in);     public static void main(String[] args)    {        // declare variables        char userInput =' ';                   System.out.print("Please try to guess the letter I am thinking of: ");         // get a single character from the user data input        userInput = cin.next().charAt(0);                // Use an If Statement to check equality        if (userInput == 'a' || userInput == 'A')        {         System.out.print("You have Guessed correctly!n");        }        else        {         System.out.print("Sorry, that was not the correct letter I was thinking ofn");        }                   }// end main    }// http://programmingnotes.org/ ```

Notice in line 11 I declare the char data type, naming it “userInput.” I also initialized it as an empty variable. In line 18 I used an “If/Else Statement” to determine if the user inputted value matches the predefined letter within the program. I also used the “OR” operator in line 18 to determine if the letter the user inputted was lower or uppercase. Try compiling the program simply using this
`if (userInput == 'a')` as your if statement, and notice the difference.

The resulting code should give this as output

```Please try to guess the letter I am thinking of: A You have Guessed correctly! ```

===== CHECK IF LETTER IS UPPER CASE =====

This example is similar to the previous one, and will check if a letter is uppercase

``` #2 - Is Input Uppercase? Java import java.util.Scanner; public class CheckIfUppercase { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables char userInput =' '; System.out.print("Please enter an UPPERCASE letter: "); // get a single character from the user data input userInput = cin.next().charAt(0); // Checks to see if inputted data falls between uppercase values if ((userInput >= 'A')&&(userInput <= 'Z')) { System.out.print(userInput+" is an uppercase lettern"); } else { System.out.print(userInput+" is not an uppercase lettern"); } }// end main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 import java.util.Scanner; public class CheckIfUppercase{    // global variable declaration    static Scanner cin = new Scanner(System.in);         public static void main(String[] args)    {        // declare variables        char userInput =' ';             System.out.print("Please enter an UPPERCASE letter: ");         // get a single character from the user data input        userInput = cin.next().charAt(0);             // Checks to see if inputted data falls between uppercase values        if ((userInput >= 'A')&&(userInput <= 'Z'))        {         System.out.print(userInput+" is an uppercase lettern");        }        else        {         System.out.print(userInput+" is not an uppercase lettern");        }                   }// end main    }// http://programmingnotes.org/ ```

Notice in line 18, an If statement was used, which checked to see if the user inputted data fell between letter A and letter Z. We did that by using the “AND” operator. So that IF statement is basically saying (in plain english)

`IF ('userInput' is equal to or greater than 'A') AND ('userInput' is equal to or less than 'Z')`

``` ```

`THEN it is an uppercase letter`

The resulting code should give this as output

```Please enter an UPPERCASE letter: p p is not an uppercase letter```

===== CHECK IF LETTER IS A VOWEL =====

This example will utilize more if statements, checking to see if the user inputted data is a vowel or not. This will be very similar to the previous example, utilizing the OR operator once again.

``` #3 - Is Input a Vowel? Java import java.util.Scanner; public class CheckIfVowel { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables char userInput =' '; System.out.print("Please enter a vowel: "); // get a single character from the user data input userInput = cin.next().charAt(0); // Checks to see if inputted data is A,E,I,O,U,Y if ((userInput == 'a')||(userInput == 'A')||(userInput == 'e')|| (userInput == 'E')||(userInput == 'i')||(userInput == 'I')|| (userInput == 'o')||(userInput == 'O')||(userInput == 'u')|| (userInput == 'U')||(userInput == 'y')||(userInput == 'Y')) { System.out.print("Correct, "+userInput+" is a vowel!n"); } else { System.out.print("Sorry, "+userInput+" is not a voweln"); } }// end main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132 import java.util.Scanner; public class CheckIfVowel{    // global variable declaration    static Scanner cin = new Scanner(System.in);         public static void main(String[] args)    {        // declare variables        char userInput =' ';                   System.out.print("Please enter a vowel: ");         // get a single character from the user data input        userInput = cin.next().charAt(0);                 // Checks to see if inputted data is A,E,I,O,U,Y         if ((userInput == 'a')||(userInput == 'A')||(userInput == 'e')||            (userInput == 'E')||(userInput == 'i')||(userInput == 'I')||            (userInput == 'o')||(userInput == 'O')||(userInput == 'u')||            (userInput == 'U')||(userInput == 'y')||(userInput == 'Y'))         {              System.out.print("Correct, "+userInput+" is a vowel!n");         }         else         {              System.out.print("Sorry, "+userInput+" is not a voweln");         }                   }// end main    }// http://programmingnotes.org/ ```

This program should be very straight forward, and its basically checking to see if the user inputted data is the letter A, E, I, O, U or Y.

The resulting code should give the following output

```Please enter a vowel: o Correct, o is a vowel!```

===== HELLO WORLD v2 =====

This last example will demonstrate using the string data type to print the line “Hello World!” to the screen.

``` #4 - Hello World - String Version Java import java.util.Scanner; public class HelloWorldString { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables String userInput =""; System.out.print("Please enter a sentence: "); // get a string from the user userInput = cin.nextLine(); // display message to user System.out.println("You entered: "+userInput); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122 import java.util.Scanner; public class HelloWorldString{    // global variable declaration    static Scanner cin = new Scanner(System.in);      public static void main(String[] args)    {        // declare variables        String userInput ="";                   System.out.print("Please enter a sentence: ");         // get a string from the user        userInput = cin.nextLine();                // display message to user        System.out.println("You entered: "+userInput);       }// end main    }// http://programmingnotes.org/ ```

The resulting code should give following output

```Please enter a sentence: Hello World! You entered: Hello World!```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac YOUR_CLASS_NAME.java`

*** To run the compiled program, simply type this command:

` java YOUR_CLASS_NAME`

## Java || Simple Math Using Int & Float

This page will display the use of int and float data types. Note: you can (obviously) add as many int’s together as you wish, not just two.

==== ADDING TWO NUMBERS TOGETHER ====

To add two numbers together, you will have to first declare your variables by doing something like this.

``` #1 - Adding 2 Numbers Together Java import java.util.Scanner; public class Add { public static void main(String[] args) { // declare variables int num1=0; int num2=0; int sum=0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextInt(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the sum of the two numbers sum = num1 + num2; // display results to the user System.out.println("The sum of "+num1+" and "+num2+" is: "+sum); }// end main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 import java.util.Scanner; public class Add{    public static void main(String[] args)     {        // declare variables        int num1=0;        int num2=0;        int sum=0;                     // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);             // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextInt();                System.out.print("Please enter the second number: ");        num2 = cin.nextInt();                // calculate the sum of the two numbers        sum = num1 + num2;                // display results to the user        System.out.println("The sum of "+num1+" and "+num2+" is: "+sum);                    }// end main    }// http://programmingnotes.org/ ```

Notice in lines 8-10, I declared my variables, giving them a name. You can name your variables anything you want, with a rule of thumb as naming them something meaningful to your code (i.e avoid giving your variables arbitrary names like “x” or “y”). In line 23 the actual math process is taking place, storing the sum of “num1” and “num2” in a variable called “sum.” I also initialized my variables to zero. You should always initialize your variables.

I obtained data from the user by using the Scanner Class.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Add.java`

*** To run the compiled program, simply type this command:

` java Add`

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The sum of 8 and 24 is: 32```

==== SUBTRACTING TWO NUMBERS ====

Subtracting two ints works the same way as the above code, and we would only need to edit the above code in one place to achieve that. In line 23, replace the addition symbol with a subtraction sign, and you should have something like this

``` #2 - Subtracting 2 Numbers Together Java import java.util.Scanner; public class Subtract { public static void main(String[] args) { // declare variables int num1=0; float num2=0; float sum=0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextInt(); System.out.print("Please enter the second number: "); num2 = cin.nextFloat(); // calculate the difference of the two numbers sum = num1 - num2; // display results to the user System.out.println("The difference between "+num1+" and "+num2+" is: "+sum); }// end main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 import java.util.Scanner; public class Subtract{    public static void main(String[] args)     {        // declare variables        int num1=0;        float num2=0;        float sum=0;                     // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);             // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextInt();                System.out.print("Please enter the second number: ");        num2 = cin.nextFloat();                // calculate the difference of the two numbers        sum = num1 - num2;                // display results to the user        System.out.println("The difference between "+num1+" and "+num2+" is: "+sum);                    }// end main    }// http://programmingnotes.org/ ```

Note: In the above example, “cin.nextFloat()” was used on line 20 in place of “nextInt.” The declaration “nextFloat” can be used in place of “nextInt” in case you want to obtain floating point data from the user.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Subtract.java`

*** To run the compiled program, simply type this command:

` java Subtract`

The above code should give you the following output

```Please enter the first number: 8 Please enter the second number: 23.99999 The difference between 8 and 23.99999 is: -15.99999```

==== MULTIPLYING TWO NUMBERS ====

This can be achieved the same way as the 2 previous methods, simply by editing line 23, and replacing the designated math operator with the star symbol “*.”

``` #3 - Multiplying 2 Numbers Together Java import java.util.Scanner; public class Multiply { public static void main(String[] args) { // declare variables float num1=0; int num2=0; float sum=0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextFloat(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the product of the two numbers sum = num1 * num2; // display results to the user System.out.println("The product of "+num1+" and "+num2+" is: "+sum); }// end main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 import java.util.Scanner; public class Multiply{    public static void main(String[] args)     {        // declare variables        float num1=0;        int num2=0;        float sum=0;                     // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);             // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextFloat();                System.out.print("Please enter the second number: ");        num2 = cin.nextInt();                // calculate the product of the two numbers        sum = num1 * num2;                // display results to the user        System.out.println("The product of "+num1+" and "+num2+" is: "+sum);                    }// end main    }// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Multiply.java`

*** To run the compiled program, simply type this command:

` java Multiply`

The above code should give you the following output

```Please enter the first number: 7.999999 Please enter the second number: 24 The product of 7.999999 and 24 is: 191.99997```

==== DIVIDING TWO NUMBERS TOGETHER ====

In division, when you divide numbers together, sometimes they end in decimals. Int data types can not store decimal data (try it yourself and see), so here is where the use of the float data type is mandatory (Note: You can also use the “double” data type here aswell).

``` #4 - Dividing 2 Numbers Together Java import java.util.Scanner; public class Divide { public static void main(String[] args) { // declare variables float num1=0; float num2=0; float sum=0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextFloat(); System.out.print("Please enter the second number: "); num2 = cin.nextFloat(); // calculate the quotient of the two numbers sum = num1 / num2; // display results to the user System.out.println("The quotient of "+num1+" and "+num2+" is: "+sum); }// end main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 import java.util.Scanner; public class Divide{    public static void main(String[] args)     {        // declare variables        float num1=0;        float num2=0;        float sum=0;                     // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);             // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextFloat();                System.out.print("Please enter the second number: ");        num2 = cin.nextFloat();                // calculate the quotient of the two numbers        sum = num1 / num2;                // display results to the user        System.out.println("The quotient of "+num1+" and "+num2+" is: "+sum);                    }// end main    }// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Divide.java`

*** To run the compiled program, simply type this command:

` java Divide`

The above code should give the following output

```Please enter the first number: 7.99999 Please enter the second number: 23.99999 The quotient of 7.99999 and 23.99999 is: 0.33333305```

==== MODULUS ====

If you wanted to capture the remainder of the quotient you calculated from the above code, you would use the modulus operator (%).

From the above code, you would only need to edit line 23, from division, to modulus.

``` #5 - Getting the Remainder of 2 Numbers Java import java.util.Scanner; public class Modulus { public static void main(String[] args) { // declare variables float num1=0; int num2=0; float remainder=0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextFloat(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the remainder of the two numbers remainder = num1 % num2; // display results to the user System.out.println("The remainder of "+num1+" and "+num2+" is: "+remainder); }// end main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 import java.util.Scanner; public class Modulus{    public static void main(String[] args)     {        // declare variables        float num1=0;        int num2=0;        float remainder=0;                     // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);             // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextFloat();                System.out.print("Please enter the second number: ");        num2 = cin.nextInt();                // calculate the remainder of the two numbers        remainder = num1 % num2;                // display results to the user        System.out.println("The remainder of "+num1+" and "+num2+" is: "+remainder);                    }// end main    }// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Modulus.java`

*** To run the compiled program, simply type this command:

` java Modulus`

The above code should give the following output

```Please enter the first number: 23.99999 Please enter the second number: 8 The remainder of 23.99999 and 8 is: 7.9999905```

## Java || Hello World!

This page will consist of creating the typical “hello world!” application. First, you will need to create a new project in whichever IDE you are using. I am using a simple text editor and the terminal, but any compiler will do.

When you have everything loaded up, you will start your code off by entering the headers like so into your HelloWorld.java file.

``` #1 - Add Class Header Java public class HelloWorld { // YOUR MAIN METHOD GOES HERE } 1234 public class HelloWorld{    // YOUR MAIN METHOD GOES HERE} ```

The most basic form of a class definition is shown above. The keyword “class” begins the class definition for the class named “HelloWorld.”

Next, you are going to add the main function. This will generally look something like this:

``` #2 - Add main method Java public static void main(String[] args) { // YOUR CODE GOES HERE } 1234 public static void main(String[] args) {    // YOUR CODE GOES HERE} ```

Every program in Java must contain a main method declaration as shown above. The declaration “public” and “static” can be written in any order (public static or static public), but the custom is to use “public static.”

We are halfway finished, now all we have to do is say hello to the world! You will do that by adding this line of code to your program, which basically outputs data to the screen

``` #3 - This outputs data to screen Java System.out.println("Hello World!"); 1 System.out.println("Hello World!"); ```

The above code uses the “System” class from the core library to print the “Hello World!” message to standard output.

So when you add everything together, your full code will look something like this

``` #4 - HelloWorld.java Java public class HelloWorld { public static void main(String[] args) { // Display message to screen System.out.println("Hello World!"); }// end of main }// http://programmingnotes.org/ 123456789 public class HelloWorld{    public static void main(String[] args)     {     // Display message to screen        System.out.println("Hello World!");     }// end of main    }// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

Once you have loaded the terminal, if you have your java source file saved in any directory other than the home folder, you will need to change directories to that specific folder where your source file resides. Many typically save their source files to the desktop.

*** If your files are located on the desktop, in the terminal, type this command:

`@ubuntu:~\$ cd Desktop`

*** Next we will compile the java source file, and this can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`@ubuntu:~/Desktop\$ javac HelloWorld.java`

*** To run the compiled program, simply type this command:

`@ubuntu:~/Desktop\$ java HelloWorld`

And there you have it! After you compile the above code, you should get this as your output

`Hello World!`

## Java || Which Compiler To Use?

A common question one may wonder is, which compiler should I use? There are a few choices, and your choice should probably be based on what you intend to write with it.

If you intend to program on Windows, a common choice is to download one of the many (free) Integrated Development Environment’s (IDE) which are currently available on the internet. The IDE’s I recommend are:

```* NetBeans * Eclipse```

Netbeans and Eclipse are the equivalent of Visual Studios and CodeBlocks for C++. (NOTE: Netbeans and Eclipse is also available for download on Linux).

You will also need to have Java installed on your computer in order to develop Java applications. If you are using Windows, then visit the Oracle website. and download and install either JDK7 or JDK7 with Netbeans. Don’t bother with JRE, as it merely runs Java programs, but does not compile them.

==== LINUX USERS ====

To install Java, open the terminal window and enter the command:

`sudo apt-get install openjdk-7-jdk`

If you want to add Netbeans to your computer, then use the same terminal window and enter the command below:

`sudo apt-get install netbeans`

Alternatively, if you want to add Eclipse to your computer, then use the same terminal window and enter the command below:

`sudo apt-get install eclipse-platform`

Personally, I use a simple text editor (gedit) and the terminal window in Ubuntu to program in Java, and all the source code which is presented on this site was created using that development environment.

## C++ || 8 Different Ways To Reverse A String/Character Array In C++

This page will consist of 8 different ways to reverse a character array, and a string literal (std::string).

REQUIRED KNOWLEDGE FOR THE PROGRAMS

```Character Arrays String Literals Cin.getline - Use For Char Arrays Getline - Use For std::string Length Strlen Strcpy While Loops For Loops Recursion - What is it? #include < algorithm> #include < stack> ```

The methods on this page will be broken up into sections. This page will list:

``` (3) methods which reverses string literals (std::string) (4) methods which reverses character arrays (1) method which utilizes the stack to "reverse" a character sequence ```

Some methods listed on this page demonstrates the use of reversing a character sequence without the use of strlen/length.

======= REVERSE AN STD::STRING =======

``` #1 - Reverse String Using STL Function C++ #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { // declare variable string name=""; cout << "Enter your name: "; getline(cin,name); // built in C++ function to reverse an std::string reverse(name.begin(), name.end()); cout <<"nYour name reversed is: " <<name << endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920 #include <iostream>#include <algorithm>#include <string>using namespace std; int main(){ // declare variable string name="";  cout << "Enter your name: "; getline(cin,name);  // built in C++ function to reverse an std::string reverse(name.begin(), name.end()); cout <<"nYour name reversed is: " <<name << endl;  return 0;}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

``` #2 - Reverse String Recursive Method, No Length() C++ #include <iostream> #include <string> using namespace std; // function prototypes void Reverse(string name); int main() { // declare variable string name=""; // get user data cout<<"Enter your name: "; getline(cin,name); cout<<"nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(string name) { if(name == "") // the base case { return; } else // the recursive step { Reverse(name.substr(1)); cout<<name.at(0); } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637 #include <iostream>#include <string>using namespace std; // function prototypesvoid Reverse(string name); int main(){ // declare variable string name="";  // get user data cout<<"Enter your name: "; getline(cin,name);  cout<<"nYour name reversed is: ";  // function declaration Reverse(name); cout<<endl;  return 0;}// end of main void Reverse(string name){ if(name == "") // the base case { return; } else // the recursive step { Reverse(name.substr(1)); cout<<name.at(0); }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

``` #3 - Reverse String Iterative Method, Using Length() C++ #include <iostream> #include <string> using namespace std; // function prototypes void Reverse(string name); int main() { // declare variable string name=""; // get user data cout<<"Enter your name: "; getline(cin,name); cout<<"nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(string name) { // get the length of the string int nameLength = name.length()-1; while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536 #include <iostream>#include <string>using namespace std; // function prototypesvoid Reverse(string name); int main(){ // declare variable string name="";  // get user data cout<<"Enter your name: "; getline(cin,name);  cout<<"nYour name reversed is: ";  // function declaration Reverse(name); cout<<endl;  return 0;}// end of main void Reverse(string name){ // get the length of the string int nameLength = name.length()-1;  while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

======= REVERSE A CHARACTER ARRAY =======

The following will demonstrate (4) methods which reverses a character array.

``` #4 - Reverse Char Array Recursive Method, No Strlen C++ #include <iostream> using namespace std; // function prototype void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); cout<<"nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(char name[]) { if(*name=='\0') // the base case { return; } else // the recursive step { Reverse(name+1); cout<<*(name); } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536 #include <iostream>using namespace std; // function prototypevoid Reverse(char name[]); int main(){ // declare variable char name[30];  // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name));  cout<<"nYour name reversed is: ";  // function declaration Reverse(name); cout<<endl;  return 0;}// end of main void Reverse(char name[]){ if(*name=='\0') // the base case { return; } else // the recursive step { Reverse(name+1); cout<<*(name); }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

``` #5 - Reverse Char Array Iterative Method, No Strlen C++ #include <iostream> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); cout<<"nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(char name[]) { int nameLength = 0; //get the length of array while(name[nameLength] != '\0') { ++nameLength; } //decrease the length of by 1 --nameLength; // display reversed string while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; } }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>using namespace std; // function prototypesvoid Reverse(char name[]); int main(){ // declare variable char name[30];  // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name));  cout<<"nYour name reversed is: ";  // function declaration Reverse(name); cout<<endl;  return 0;}// end of main void Reverse(char name[]){ int nameLength = 0;  //get the length of array while(name[nameLength] != '\0') { ++nameLength; }  //decrease the length of by 1 --nameLength;  // display reversed string while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

``` #6 - Reverse Char Array Iterative Method, No Strlen C++ #include <iostream> #include <cstring> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); // function declaration Reverse(name); cout<<"nYour name reversed is: "<< name<<endl; return 0; }// end of main void Reverse(char name[]) { // private variables int nameLength = 0; char copy[30]; strcpy(copy,name); //get lenght of array while(name[nameLength] != '\0') { ++nameLength; } //decrease the length of by 1 --nameLength; // reverse the array for(int x = 0; x <= nameLength; ++x) { // rearange the order of the two arrays name[nameLength - x] = copy[x]; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 #include <iostream>#include <cstring>using namespace std; // function prototypesvoid Reverse(char name[]); int main(){ // declare variable char name[30];  // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name));  // function declaration Reverse(name);  cout<<"nYour name reversed is: "<< name<<endl;  return 0;}// end of main void Reverse(char name[]){ // private variables int nameLength = 0; char copy[30];  strcpy(copy,name);  //get lenght of array while(name[nameLength] != '\0') { ++nameLength; }  //decrease the length of by 1 --nameLength;  // reverse the array for(int x = 0; x <= nameLength; ++x) { // rearange the order of the two arrays name[nameLength - x] = copy[x]; } }// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

``` #7 - Reverse Char Array Iterative Method, Using Strlen C++ #include <iostream> #include <cstring> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); // function declaration Reverse(name); cout<<"nYour name reversed is: "<< name<<endl; return 0; }// end of main void Reverse(char name[]) { // get the length of the current word in the array index int nameLength = strlen(name)-1; // increment thru each letter within the current char array index // reversing the order of the array for(int currentChar=0; currentChar < nameLength; --nameLength, ++currentChar) { // copy 1st letter in the array index into temp char temp = name[currentChar]; // copy last letter in the array index into the 1st array index name[currentChar] = name[nameLength]; // copy temp into last array index name[nameLength] = temp; } }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041 #include <iostream>#include <cstring>using namespace std; // function prototypesvoid Reverse(char name[]); int main(){ // declare variable char name[30];  // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name));  // function declaration Reverse(name);  cout<<"nYour name reversed is: "<< name<<endl;  return 0;}// end of main void Reverse(char name[]){ // get the length of the current word in the array index int nameLength = strlen(name)-1; // increment thru each letter within the current char array index // reversing the order of the array for(int currentChar=0; currentChar < nameLength; --nameLength, ++currentChar) { // copy 1st letter in the array index into temp char temp = name[currentChar]; // copy last letter in the array index into the 1st array index name[currentChar] = name[nameLength]; // copy temp into last array index name[nameLength] = temp; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```

======= REVERSE A CHARACTER SEQUENCE USING A STACK =======

The following will demonstrate (1) method which reverses a character sequence using the STL stack.

``` #8 - Reverse Char Sequence Using Stack C++ #include <iostream> #include <stack> using namespace std; // function prototypes void Reverse(stack<char> &name); int main() { // using the internal system stack stack<char> name; char singleChar; cout<<"Enter your name: "; while(cin.get(singleChar) && singleChar != 'n') { name.push(singleChar); } cout<<"nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(stack<char> &name) { while(!name.empty()) { cout << name.top(); name.pop(); } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637 #include <iostream>#include <stack>using namespace std; // function prototypesvoid Reverse(stack<char> &name); int main(){ // using the internal system stack stack<char> name; char singleChar; cout<<"Enter your name: "; while(cin.get(singleChar) && singleChar != 'n') { name.push(singleChar); } cout<<"nYour name reversed is: ";  // function declaration Reverse(name); cout<<endl;  return 0;}// end of main void Reverse(stack<char> &name){ while(!name.empty()) { cout << name.top(); name.pop(); }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT

``` Enter your name: My Programming Notes```

``` ```

```Your name reversed is: setoN gnimmargorP yM ```