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

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

REQUIRED KNOWLEDGE FOR THIS PROGRAM

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

``` Convert Seconds Into HH::MM::SS Format C++ // ============================================================================ // Author: Kenneth Perkins // Date: May 30, 2012 // Taken From: http://programmingnotes.org/ // File: Convert-Time.cpp // Description: Demonstrates how to convert time from -seconds- into // HH::MM::SS (hours, minutes, seconds) format // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 30, 2012//    Taken From: http://programmingnotes.org///    File:  Convert-Time.cpp//    Description: Demonstrates how to convert time from -seconds- into//      HH::MM::SS (hours, minutes, seconds) format// ============================================================================#include <iostream>using namespace std; int main(){    // declare variables    int time = 0;    int hour = 0;    int min = 0;    int sec = 0;     // obtain data from user    cout << "Enter a time in seconds: ";    cin >> time;     // using the time from ^ above, convert    // secs to HH:MM:SS format using division    // and modulus    hour = time/3600;    time = time%3600;    min = time/60;    time = time%60;    sec = time;     // display data to user    cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, "        <<min<<" minutes, and "<<sec<<" seconds!\n";     return 0;}// http://programmingnotes.org/ ```

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

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

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

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

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

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

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

REQUIRED KNOWLEDGE FOR THIS PROGRAM

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

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

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

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

``` Determine If A String Is A Number Or Not C++ // ============================================================================ // Author: Kenneth Perkins // Date: May 24, 2012 // Taken From: http://programmingnotes.org/ // File: isNumber.cpp // Description: Demonstrates checking if a char array is a number // ============================================================================ #include <iostream> #include <cstring> #include <cctype> using namespace std; // function prototype void IsArryANum(char arry[]); int main() { // declare & initialize variables char arry; // obtain data from user cout << "Enter some text to see if its a number or not: "; cin.getline(arry, sizeof(arry)); // getting line cout<<endl; IsArryANum(arry); return 0; }// end of main void IsArryANum(char arry[]) { int notANumber = 0; int length = strlen(arry); // 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 arry[length] = ' '; arry[length + 1] = '\0'; // increment the length to account for the space we just added ++length; for(int x = 0; x < length; ++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/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 24, 2012//    Taken From: http://programmingnotes.org///    File:  isNumber.cpp//    Description: Demonstrates checking if a char array is a number// ============================================================================#include <iostream>#include <cstring>#include <cctype>using namespace std; // function prototypevoid IsArryANum(char arry[]); int main(){    // declare & initialize variables    char arry;     // obtain data from user    cout << "Enter some text to see if its a number or not: ";     cin.getline(arry, sizeof(arry)); // getting line        cout<<endl;             IsArryANum(arry);     return 0;}// end of main void IsArryANum(char arry[]){    int notANumber = 0;    int length = strlen(arry);        // 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        arry[length] = ' ';    arry[length + 1] = '\0';        // increment the length to account for the space we just added    ++length;        for(int x = 0; x < length; ++x)    {               cout <<arry[x]; // display the char at the current index         // if the current char isnt a number, increment counter        if(isalpha(arry[x]))         {            ++notANumber;        }        // if curerent char is a space, that indicates we are         // at the end of the current word, so we         // display the results to the user        else if(isspace(arry[x]))         {            if (notANumber > 0)            {                               cout <<"is NOT a number!"                    <<" There are "<<notANumber<<" letters"                    <<" in that word...\n";            }                       else            {                cout <<"is a number..\n";            }            notANumber = 0;        }    }}// http://programmingnotes.org/ ```

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

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

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

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

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

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

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

REQUIRED KNOWLEDGE FOR THIS SNIPPET

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

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

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

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

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

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

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

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

Once compiled, you should get this as your output

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

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

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

## C++ || 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++ // ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2012 // Taken From: http://programmingnotes.org/ // File: wellFormed.cpp // Description: Demonstrates how to check if an expression is well formed // ============================================================================ #include <iostream> #include "ClassStackListType.h" using namespace std; // function prototypes bool IsOpen(char symbol); bool IsClosed(char symbol); bool IsWellFormed(char openSymbol, char closeSymbol); int main() { // declare variables char expression; 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]!='\0' && 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(openSymbol, expression[index]); } } ++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 openSymbol, char closeSymbol) { return (((openSymbol == '(') && closeSymbol == ')') || ((openSymbol == '{') && closeSymbol == '}') || ((openSymbol == '[') && closeSymbol == ']')); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 14, 2012//    Taken From: http://programmingnotes.org///    File:  wellFormed.cpp//    Description: Demonstrates how to check if an expression is well formed// ============================================================================#include <iostream>#include "ClassStackListType.h"using namespace std; // function prototypesbool IsOpen(char symbol);bool IsClosed(char symbol);bool IsWellFormed(char openSymbol, char closeSymbol); int main(){    // declare variables    char expression;    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]!='\0' && 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(openSymbol, expression[index]);            }        }        ++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 openSymbol, char closeSymbol){    return (((openSymbol == '(') && closeSymbol == ')') || ((openSymbol == '{') && closeSymbol == '}')        || ((openSymbol == '[') && closeSymbol == ']'));}// 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++ || FizzBuzz – Tackling The Fizz Buzz Test In C++ What is Fizz Buzz?

Simply put, a “Fizz-Buzz test” is a programming interview question designed to help filter out potential job prospects – those who can’t seem to program if their life depended on it.

An example of a typical Fizz-Buzz question is the following:

Write a program which prints the numbers from 1 to 100. But for multiples of three, print the word “Fizz” instead of the number, and for the multiples of five, print the word “Buzz”. For numbers which are multiples of both three and five, print the word “FizzBuzz”.

This seems easy enough, and many should be able to complete a program which carries out a solution in a few minutes. Though, after doing a little research, apparently that is not the case. This page will present one way to carry out a solution to this Fizz-Buzz problem.

There is a small “catch” that some may encounter when trying to solve this problem, and that is the fact that the conditional statement for the number divisible by 15 should come before each sequential conditional statement. Consider this pseudocode:

``` // A simple Fizz-Buzz algorithm using a while loop 'currentNumber' = 1 while('currentNumber' is less than or equal to 100) { if('currentNumber' is divisible by 3) AND ('currentNumber' is divisible by 5) print "FizzBuzz" else if('currentNumber' is divisible by 3) print "Fizz" else if('currentNumber' is divisible by 5) print "Buzz" else // 'currentNumber' is not divisible by 3 or 5 print 'currentNumber' increment 'currentNumber' by one }// http://programmingnotes.org/ 123456789101112131415 // A simple Fizz-Buzz algorithm using a while loop 'currentNumber' = 1while('currentNumber' is less than or equal to 100){    if('currentNumber' is divisible by 3) AND ('currentNumber' is divisible by 5)        print "FizzBuzz"    else if('currentNumber' is divisible by 3)        print "Fizz"    else if('currentNumber' is divisible by 5)        print "Buzz"    else // 'currentNumber' is not divisible by 3 or 5         print 'currentNumber'    increment 'currentNumber' by one}// http://programmingnotes.org/ ```

The portion that may make this problem tricky for some is the fact that the conditional statement for the number divisible by 15 must be checked -before- the conditional statements which checks for numbers divisible by 3 and 5. If the conditional statements are placed in any other order, the end result will not be correct, which is what can make the problem difficult for many.

======= THE FIZZ BUZZ TEST =======

So building upon the pseudocode found from above, utilizing the modulus operator, here is a simple solution to the Fizz Buzz Test

``` The Fizz Buzz Test C++ // ============================================================================ // Author: Kenneth Perkins // Date: May 10, 2012 // Taken From: http://programmingnotes.org/ // File: fizzbuzz.cpp // Description: Demonstrates the fizz buzz test // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int fizz = 3; int buzz = 5; int endNumber = 100; int fizzBuzz = fizz * buzz; // ^ numbers divisible by 3 and 5 are also divisible by 3 * 5 // start the loop, continue until the counter // reaches the 'end' for (int currentNumber = 1; currentNumber <= endNumber; ++currentNumber) { if (currentNumber % fizzBuzz == 0) // divisible by 3 and 5 { cout<<"FIZZ BUZZ!!\n"; } else if (currentNumber % fizz == 0) // divisible by 3 { cout<<"FIZZ\n"; } else if (currentNumber % buzz == 0)// divisible by 5 { cout<<"BUZZ\n"; } else // not divisible by 3 or 5 { cout<<currentNumber<<endl; } } return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 10, 2012//    Taken From: http://programmingnotes.org///    File:  fizzbuzz.cpp//    Description: Demonstrates the fizz buzz test// ============================================================================#include <iostream>using namespace std; int main(){    // declare variables    int fizz = 3;    int buzz = 5;    int endNumber = 100;    int fizzBuzz = fizz * buzz;     // ^ numbers divisible by 3 and 5 are also divisible by 3 * 5     // start the loop, continue until the counter     // reaches the 'end'    for (int currentNumber = 1; currentNumber <= endNumber; ++currentNumber)    {        if (currentNumber % fizzBuzz == 0) // divisible by 3 and 5        {            cout<<"FIZZ BUZZ!!\n";        }        else if (currentNumber % fizz == 0) // divisible by 3        {            cout<<"FIZZ\n";        }        else if (currentNumber % buzz == 0)// divisible by 5        {            cout<<"BUZZ\n";        }        else // not divisible by 3 or 5        {            cout<<currentNumber<<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

```1 2 FIZZ 4 BUZZ FIZZ 7 8 FIZZ BUZZ 11 FIZZ 13 14 FIZZ BUZZ!! 16 17 FIZZ 19 BUZZ FIZZ 22 23 FIZZ BUZZ 26 FIZZ 28 29 FIZZ BUZZ!! 31 32 FIZZ 34 BUZZ FIZZ 37 38 FIZZ BUZZ 41 FIZZ 43 44 FIZZ BUZZ!! 46 47 FIZZ 49 BUZZ FIZZ 52 53 FIZZ BUZZ 56 FIZZ 58 59 FIZZ BUZZ!! 61 62 FIZZ 64 BUZZ FIZZ 67 68 FIZZ BUZZ 71 FIZZ 73 74 FIZZ BUZZ!! 76 77 FIZZ 79 BUZZ FIZZ 82 83 FIZZ BUZZ 86 FIZZ 88 89 FIZZ BUZZ!! 91 92 FIZZ 94 BUZZ FIZZ 97 98 FIZZ BUZZ ```

## C++ || Snippet – Round A Number To The Nearest Whole Number This page will display a simple implementation of a function which rounds a floating point number to the nearest whole number. So for example, if the number 12.34542 was sent to the function, it would return the rounded value of 12.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Modf - Modulus For Float Data How To Round A Number ```

``` Round A Number To The Nearest Whole Number C++ #include <iostream> #include <cmath> using namespace std; // function prototype double RoundNumber(double floatNumber); int main() { // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber; cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl; return 0; } double RoundNumber(double floatNumber) { // declare variables double intNumber = 0; // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber); // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637 #include <iostream>#include <cmath>using namespace std; // function prototypedouble RoundNumber(double floatNumber); int main(){ // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber;  cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl;  return 0;} double RoundNumber(double floatNumber){ // declare variables double intNumber = 0;  // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber);  // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber;}// 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 three separate times to display different output)

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

``` Enter in a floating point number to round: 1.3333 1.3333 rounded to the nearest whole number is: 1 ====== RUN 2 ====== Enter in a floating point number to round: 35.56 35.56 rounded to the nearest whole number is: 36 ====== RUN 3 ====== Enter in a floating point number to round: 19.8728 ```

```19.8728 rounded to the nearest whole number is: 20 ```