## C++ || Cash Register Simulation – Display The Total Sales Amount In Dollars & Cents Using Modulus

The following is a simple program which demonstrates more use of the modulus (%) function to manipulate integer data.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Modulus Type Casting - Int The Value Of U.S Currency ```

This program first prompts the user to enter in a monetary amount into the system. This number can be a decimal number, or a whole number. Once the user enters in an amount, the program will use the modulus operator to determine exactly how many 1 dollar bills, quarters, dimes, nickles, and pennies consisted of the amount that the user entered into the program. So for example, if the user entered the value of 2.34, the program would display the result of 2 dollars, 1 quarters, 0 dimes, 1 nickels, and 4 pennies.

``` Cash Register Simulation C++ #include<iostream> using namespace std; int main() { // declare variables double initialAmount =0; int remainingAmount =0; int numberOfOneDollars =0; int numberOfQuarters =0; int numberOfDimes =0; int numberOfNickels =0; int numberOfPennies =0; // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount; // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100); // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount; // Display the results cout << "nThe amount of \$" <<initialAmount<< " consists of: n" << "t" << numberOfOneDollars << " dollar(s)n" << "t" << numberOfQuarters << " quarter(s)n" << "t" << numberOfDimes << " dime(s)n" << "t" << numberOfNickels << " nickel(s)n" << "t" << numberOfPennies << " pennie(s)n"; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 #include<iostream>using namespace std; int main(){     // declare variables double initialAmount =0; int remainingAmount =0; int numberOfOneDollars =0; int numberOfQuarters =0; int numberOfDimes =0; int numberOfNickels =0; int numberOfPennies =0;  // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount;      // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100);  // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100;  // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25;  // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10;  // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5;  // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount;  // Display the results cout << "nThe amount of \$" <<initialAmount<< " consists of: n" << "t" << numberOfOneDollars << " dollar(s)n" << "t" << numberOfQuarters << " quarter(s)n" << "t" << numberOfDimes << " dime(s)n" << "t" << numberOfNickels << " nickel(s)n" << "t" << numberOfPennies << " pennie(s)n";  return 0;}// http://programmingnotes.org/ ```

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

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

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

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

``` Enter the total sales amount in dollars & cents (for example 19.87): 19.87 The amount of \$19.87 consists of: 19 dollar(s) 3 quarter(s) 1 dime(s) 0 nickel(s) 2 pennie(s) ====== RUN 2 ====== Enter the total sales amount in dollars & cents (for example 19.87): 11.93 The amount of \$11.93 consists of: 11 dollar(s) 3 quarter(s) 1 dime(s) 1 nickel(s) 3 pennie(s) ====== RUN 3 ====== Enter the total sales amount in dollars & cents (for example 19.87): 3.00 ```

```The amount of \$3 consists of: 3 dollar(s) 0 quarter(s) 0 dime(s) 0 nickel(s) 0 pennie(s)```

## C++ || Char Array – Palindrome Checker Using A Character Array, ToUpper, Strlen, Strcpy, & Strcmp

The following is a palindrome checking program, which demonstrates more use of char array’s, ToUpper, Strlen, & Strcmp.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Character Arrays Cin.getline How to convert text in a char array from lower to uppercase How to reverse a character array Palindrome - What is it? Strlen Strcpy Strcmp While Loops For Loops Constant Variables Setw ```

Using a constant value, by default, this program first asks the user to enter 5 words and/or sentences that they want to compare for similarity. If the text which was entered into the program is a palindrome, the program will prompt a message to the user via cout. This program determines similarity by using the strcmp function, to compare two arrays together. This program also demonstrates how to reverse a character array, aswell as demonstrates how to convert all the text which was placed into the char array from lower to UPPERCASE.

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

``` Palindrome Checker Using A Char Array C++ #include <iostream> #include <iomanip> using namespace std; // constant value const int NUM_WORDS = 5; // function prototypes void ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]); void ReverseCharArray(char palindrome[][30]); void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]); int main() { // declare variable // this is a 2-D char array, which by default, has // the ability to hold 5 names, each 30 characters long char words[NUM_WORDS][30]; char wordsCopy[NUM_WORDS][30]; char palindrome[NUM_WORDS][30]; // get data from user cout << "tWelcome to the Palindrome Check System!"; cout << "nPlease enter "<<NUM_WORDS<<" word(s) to check for similarity:nt"; for(int index=0; index < NUM_WORDS; ++index) { cout<<"#"<< index+1 <<": "; cin.getline(words[index],30); cout<< "t"; } // copy the user input into the 'wordsCopy' & // 'palindrome' char array for(int index=0; index < NUM_WORDS; ++index) { strcpy(wordsCopy[index],words[index]); strcpy(palindrome[index],words[index]); } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // re-display the input to the screen cout << "nThis is what you entered into the system:nt"; for(int index=0; index < NUM_WORDS; ++index) { cout<<"Text #"<< index+1 <<": "<<words[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // function declaration // convert all the text contained in the 2 arrays to // UPPERCASE ConvertAllToUpper(wordsCopy, palindrome); // function declaration // reverses all the text contained inside the char array // to determine if it is a palindrome ReverseCharArray(palindrome); // display the palindrome's to the screen cout << "nHere are the palindrome's:nt"; // function declaration // checks to see if the text contained in the char // array is a palindrome or not CheckIfPalindrome(wordsCopy, palindrome, words); return 0; }// end of main void ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]) { int index=0; // increment thru the current char array index while(index < NUM_WORDS) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(wordsCopy[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(wordsCopy[index][currentChar])) { wordsCopy[index][currentChar] = toupper(wordsCopy[index][currentChar]); palindrome[index][currentChar] = toupper(palindrome[index][currentChar]); } } ++index; } }// end of ConvertAllToUpper void ReverseCharArray(char palindrome[][30]) { int index=0; // increment thru the current char array index while(index < NUM_WORDS) { // get the length of the current word in the array index int wordLength = strlen(palindrome[index])-1; // increment thru each letter within the current char array index // reversing the order of the array for (int currentChar=0; currentChar < wordLength; --wordLength, ++currentChar) { // copy 1st letter in the array index into temp char temp = palindrome[index][currentChar]; // copy last letter in the array index into the 1st array index palindrome[index][currentChar] = palindrome[index][wordLength]; // copy temp into last array index palindrome[index][wordLength] = temp; } ++index; } }// end of ReverseCharArray void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]) { int palindromeCount=0; // increment thru the current char array index for(int index =0; index < NUM_WORDS; ++index) { // if the contents in the 'wordsCopy' & 'palindrome' // are the same, then the word is a palindrome if(strcmp(wordsCopy[index],palindrome[index])==0) { cout<<"Text #"<< index+1 <<": "<<words[index]<<" is a palindrome"<<endl; cout<< "t"; ++palindromeCount; } } if(palindromeCount==0) { cout<<"There were no palindrome's found in the current list!n"; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 #include <iostream>#include <iomanip>using namespace std; // constant valueconst int NUM_WORDS = 5; // function prototypesvoid ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]);void ReverseCharArray(char palindrome[][30]);void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]); int main(){     // declare variable     // this is a 2-D char array, which by default, has      // the ability to hold 5 names, each 30 characters long     char words[NUM_WORDS][30];     char wordsCopy[NUM_WORDS][30];     char palindrome[NUM_WORDS][30];      // get data from user     cout << "tWelcome to the Palindrome Check System!";     cout << "nPlease enter "<<NUM_WORDS<<" word(s) to check for similarity:nt";     for(int index=0; index < NUM_WORDS; ++index)     {          cout<<"#"<< index+1 <<": ";          cin.getline(words[index],30);          cout<< "t";     }      // copy the user input into the 'wordsCopy' &     // 'palindrome' char array     for(int index=0; index < NUM_WORDS; ++index)     {          strcpy(wordsCopy[index],words[index]);          strcpy(palindrome[index],words[index]);     }      // create a line seperator     cout<<endl;     cout.fill('-');     cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;       // re-display the input to the screen     cout << "nThis is what you entered into the system:nt";     for(int index=0; index < NUM_WORDS; ++index)     {          cout<<"Text #"<< index+1 <<": "<<words[index]<<endl;          cout<< "t";     }       // create a line seperator     cout<<endl;     cout.fill('-');     cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;           // function declaration     // convert all the text contained in the 2 arrays to     // UPPERCASE     ConvertAllToUpper(wordsCopy, palindrome);      // function declaration     // reverses all the text contained inside the char array     // to determine if it is a palindrome     ReverseCharArray(palindrome);      // display the palindrome's  to the screen     cout << "nHere are the palindrome's:nt";      // function declaration     // checks to see if the text contained in the char     // array is a palindrome or not     CheckIfPalindrome(wordsCopy, palindrome, words);      return 0;}// end of main void ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]){     int index=0;      // increment thru the current char array index     while(index < NUM_WORDS)     {                  // increment thru each letter within the current char array index          for(int currentChar=0;  currentChar < strlen(wordsCopy[index]); ++currentChar)          {                   // checks each letter in the current array index               // to see if its lower or UPPERCASE               // if its lowercase, change to UPPERCASE               if (islower(wordsCopy[index][currentChar]))               {                    wordsCopy[index][currentChar] = toupper(wordsCopy[index][currentChar]);                    palindrome[index][currentChar] = toupper(palindrome[index][currentChar]);                                   }          }          ++index;     }}// end of ConvertAllToUpper void ReverseCharArray(char palindrome[][30]){     int index=0;      // increment thru the current char array index     while(index < NUM_WORDS)     {    // get the length of the current word in the array index     int wordLength = strlen(palindrome[index])-1;     // increment thru each letter within the current char array index     // reversing the order of the array     for (int currentChar=0; currentChar < wordLength; --wordLength, ++currentChar)     {     // copy 1st letter in the array index into temp     char temp = palindrome[index][currentChar];     // copy last letter in the array index into the 1st array index     palindrome[index][currentChar] = palindrome[index][wordLength];     // copy temp into last array index     palindrome[index][wordLength] = temp;     }     ++index;     }}// end of ReverseCharArray void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]){ int palindromeCount=0;      // increment thru the current char array index     for(int index =0; index < NUM_WORDS; ++index)     {     // if the contents in the 'wordsCopy' & 'palindrome'     // are the same, then the word is a palindrome     if(strcmp(wordsCopy[index],palindrome[index])==0)     {     cout<<"Text #"<< index+1 <<": "<<words[index]<<" is a palindrome"<<endl;     cout<< "t";     ++palindromeCount;     }      }      if(palindromeCount==0)      {     cout<<"There were no palindrome's found in the current list!n";      }}// http://programmingnotes.org/ ```

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

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

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

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

``` Welcome to the Palindrome Check System! Please enter 5 word(s) to check for similarity: #1: SteP oN nO PEts #2: My ProGramminG NoTeS #3: RaTs liVE ON No eViL StaR #4: ABLe wAs I ErE I sAw ElBa #5: LiVE Non Evil ------------------------------------------------------------ This is what you entered into the system: Text #1: SteP oN nO PEts Text #2: My ProGramminG NoTeS Text #3: RaTs liVE ON No eViL StaR Text #4: ABLe wAs I ErE I sAw ElBa Text #5: LiVE Non Evil ------------------------------------------------------------ Here are the palindrome's: Text #1: SteP oN nO PEts is a palindrome Text #3: RaTs liVE ON No eViL StaR is a palindrome Text #4: ABLe wAs I ErE I sAw ElBa is a palindrome Text #5: LiVE Non Evil is a palindrome ====== RUN 2 ====== Welcome to the Palindrome Check System! Please enter 5 word(s) to check for similarity: #1: today Is Great #2: Tomorrow is Foriegn #3: Sunday Brunch #4: Hello SkiPper #5: Mayday Ship DowN! ------------------------------------------------------------ This is what you entered into the system: Text #1: today Is Great Text #2: Tomorrow is Foriegn Text #3: Sunday Brunch Text #4: Hello SkiPper Text #5: Mayday Ship DowN! ```

```------------------------------------------------------------ Here are the palindrome's: There were no palindrome's found in the current list!```

## C++ || Char Array – Convert Text Contained In A Character Array From Lower To UPPERCASE

This program demonstrates how to switch text which is contained in a char array from lower to UPPERCASE. This program also demonstrates how to convert all of the text contained in a char array to lower/UPPERCASE.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Character Arrays Cin.getline Islower Isupper Tolower Toupper Strlen While Loops For Loops Constant Variables Setw```

Using a constant integer value, this program first asks the user to enter in 3 lines of text they wish to convert from lower to UPPERCASE. Upon obtaining the information from the user, the program then converts all the text which was placed into the character array from lower to uppercase in the following order:

```(1) Switches the text from lower to UPPERCASE (2) Converts all the text to UPPERCASE (3) Converts all the text to lowercase```

After each conversion is complete, the program displays the updated information to the screen via cout.

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

``` Convert Text From Lower To UPPERCASE C++ #include <iostream> #include <iomanip> using namespace std; // constant value const int NUM_NAMES = 3; // function prototype void ConvertLowerToUpper(char names[][30]); void ConvertAllToUpper(char names[][30]); void ConvertAllToLower(char names[][30]); int main() { // declare variable // this is a 2-D char array, which by default, has // the ability to hold 3 names, each 30 characters long char names[NUM_NAMES][30]; // get data from user cout << "Please enter "<<NUM_NAMES<<" line(s) of text you wish to convert from lower to UPPERCASE:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"#"<< index+1 <<": "; cin.getline(names[index],30); cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // re-display the input to the screen cout << "nThis is what you entered into the system:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the switched lower to UPPERCASE text to the user cout << "nThis is the information switched from lower to UPPERCASE:nt"; // function declaration ConvertLowerToUpper(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the 'all UPPERCASE' converted text to the user cout << "nThis is the information converted to all UPPERCASE:nt"; // function declaration ConvertAllToUpper(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the 'all lowercase' converted text to the user cout << "nThis is the information converted to all lowercase:nt"; // function declaration ConvertAllToLower(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } return 0; }// end of main void ConvertLowerToUpper(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } else // if its UPPERCASE, change to lowercase { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; } }// end of ConvertLowerToUpper void ConvertAllToUpper(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } } ++index; } }// end of ConvertAllToUpper void ConvertAllToLower(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its UPPERCASE, change to lowercase if (isupper(names[index][currentChar])) { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 #include <iostream>#include <iomanip>using namespace std; // constant valueconst int NUM_NAMES = 3; // function prototypevoid ConvertLowerToUpper(char names[][30]);void ConvertAllToUpper(char names[][30]);void ConvertAllToLower(char names[][30]); int main(){ // declare variable // this is a 2-D char array, which by default, has // the ability to hold 3 names, each 30 characters long char names[NUM_NAMES][30];  // get data from user cout << "Please enter "<<NUM_NAMES<<" line(s) of text you wish to convert from lower to UPPERCASE:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"#"<< index+1 <<": "; cin.getline(names[index],30); cout<< "t"; }  // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;   // re-display the input to the screen cout << "nThis is what you entered into the system:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;   // display the switched lower to UPPERCASE text to the user cout << "nThis is the information switched from lower to UPPERCASE:nt"; // function declaration ConvertLowerToUpper(names);  for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; }  // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;   // display the 'all UPPERCASE' converted text to the user cout << "nThis is the information converted to all UPPERCASE:nt"; // function declaration ConvertAllToUpper(names);  for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; }  // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;   // display the 'all lowercase' converted text to the user cout << "nThis is the information converted to all lowercase:nt"; // function declaration ConvertAllToLower(names);  for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; }  return 0;}// end of main void ConvertLowerToUpper(char names[][30]){ int index=0;  // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0;  currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } else  // if its UPPERCASE, change to lowercase { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; }}// end of ConvertLowerToUpper void ConvertAllToUpper(char names[][30]){ int index=0;  // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0;  currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } } ++index; }}// end of ConvertAllToUpper void ConvertAllToLower(char names[][30]){ int index=0;  // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0;  currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its UPPERCASE, change to lowercase if (isupper(names[index][currentChar])) { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; }}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

```Please enter 3 line(s) of text you wish to convert from lower to UPPERCASE: #1: I StriKe hiM a heAVy bloW. #2: When cAn the neRve ShinE? #3: My Programming Notes.```

``` ------------------------------------------------------------ This is what you entered into the system: Text #1: I StriKe hiM a heAVy bloW. Text #2: When cAn the neRve ShinE? Text #3: My Programming Notes. ------------------------------------------------------------ This is the information switched from lower to UPPERCASE: Text #1: i sTRIkE HIm A HEavY BLOw. Text #2: wHEN CaN THE NErVE sHINe? Text #3: mY pROGRAMMING nOTES. ------------------------------------------------------------ This is the information converted to all UPPERCASE: Text #1: I STRIKE HIM A HEAVY BLOW. Text #2: WHEN CAN THE NERVE SHINE? Text #3: MY PROGRAMMING NOTES. ```

```------------------------------------------------------------ This is the information converted to all lowercase: Text #1: i strike him a heavy blow. Text #2: when can the nerve shine? Text #3: my programming notes.```

## C++ || Snippet – How To Display The Current System Time & Date In C++

This page consists of a simple program which demonstrates the process of displaying the current system time and date in C++.

This program utilizes the use of a “struct” data structure to obtain the necessary information to display the current system date and time. Knowledge of how this process works would be beneficial, but is not necessary. Click here for more information on how structs work.

``` Display The Current Date/Time C++ #include <iostream> #include <ctime> // used for time #include <iomanip> // used for setw using namespace std; int main() { // variable declaration for the current time time_t t = time(0); struct tm * now = localtime(&t); // display the current date in MM/DD/YYYY format cout<<"Today's Date is: " << (now->tm_mon + 1) << "/" << (now->tm_mday) << "/" << (now->tm_year + 1900) << endl; // display the current system time in HH:MM:SS, AM/PM format cout<<"nThe current system time is: "; // display the hours. // if hours > 12, reset back to 1, // and we must be in 'PM' time if(now->tm_hour > 12) { cout<<(now ->tm_hour)-12<<":"; } // 12 midnight 'AM' else if(now->tm_hour == 0) { cout<<12<<":"; } // we are in 'AM' time else { cout<<(now->tm_hour)<<":"; } // display the current mins/secs cout.fill('0'); cout << setw(2) << (now->tm_min)<<":" << setw(2) << (now->tm_sec); // display AM/PM if(now->tm_hour >= 12) { cout<<" PM"; } else { cout<<" AM"; } cout <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 #include <iostream>#include <ctime>  // used for time#include <iomanip> // used for setwusing namespace std; int main() {    // variable declaration for the current time    time_t t = time(0);     struct tm * now = localtime(&t);  // display the current date in MM/DD/YYYY format cout<<"Today's Date is: " << (now->tm_mon + 1) << "/" << (now->tm_mday) << "/" << (now->tm_year + 1900) << endl;  // display the current system time in HH:MM:SS, AM/PM format cout<<"nThe current system time is: ";  // display the hours. // if hours > 12, reset back to 1, // and we must be in 'PM' time if(now->tm_hour > 12) { cout<<(now ->tm_hour)-12<<":"; } // 12 midnight 'AM' else if(now->tm_hour == 0) { cout<<12<<":"; } // we are in 'AM' time else { cout<<(now->tm_hour)<<":"; }  // display the current mins/secs cout.fill('0'); cout << setw(2) << (now->tm_min)<<":" << setw(2) << (now->tm_sec);  // display AM/PM if(now->tm_hour >= 12) { cout<<" PM"; } else { cout<<" AM"; } cout <<endl;  return 0;}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

`Today's Date is: 2/23/2012`

``` ```

`The current system time is: 1:05:43 PM`

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

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

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Assignment Operators - Simple Math Operations Setw```

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

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

``` #1 - Addition Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalSum =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe sum of the items in the array is: "; // Find the sum of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalSum = totalSum + arry[i] totalSum += arry[i]; } // after the calculations are complete, display the total to the user cout<< totalSum <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalSum =0;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe sum of the items in the array is: ";     // Find the sum of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalSum = totalSum + arry[i]         totalSum += arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalSum <<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.

SAMPLE OUTPUT

```Original array values 64 85 44 31 35 2 94 67 12 80 97 10 -------------------------------------------------------- The sum of the items in the array is: 621```

===== SUBTRACTION =====

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

``` #2 - Subtraction Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalDiffetence =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe difference of the items in the array is: "; // Find the difference of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalDiffetence = totalDiffetence - arry[i] totalDiffetence -= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalDiffetence <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalDiffetence =0;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe difference of the items in the array is: ";     // Find the difference of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalDiffetence = totalDiffetence - arry[i]         totalDiffetence -= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalDiffetence <<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.

SAMPLE OUTPUT

```Original array values 10 43 77 10 2 17 87 67 6 95 57 18 -------------------------------------------------------- The difference of the items in the array is: -489```

===== MULTIPLICATION =====

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

``` #3 - Multiplication Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalProduct =1; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe product of the items in the array is: "; // Find the product of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalProduct = totalProduct * arry[i]; totalProduct *= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalProduct <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalProduct =1;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe product of the items in the array is: ";     // Find the product of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalProduct = totalProduct * arry[i];         totalProduct *= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalProduct <<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.

SAMPLE OUTPUT

```Original array values 33 36 52 28 4 99 97 17 42 81 83 33 -------------------------------------------------------- The product of the items in the array is: 1803759104```

===== DIVISION =====

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

``` #4 - Division Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable float totalQuotient =1; // need to save the variable as a float, not an int srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe quotient of the items in the array is: "; // Find the quotient of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalQuotient = totalQuotient / arry[i]; totalQuotient /= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalQuotient <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     float totalQuotient =1; // need to save the variable as a float, not an int     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe quotient of the items in the array is: ";     // Find the quotient of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalQuotient = totalQuotient / arry[i];         totalQuotient /= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalQuotient <<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.

SAMPLE OUTPUT

```Original array values 75 38 59 14 53 42 29 88 92 27 69 16 -------------------------------------------------------- The quotient of the items in the array is: 2.72677e-020```

## C++ || Snippet – How To Read & Write Data From A File

This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Fstream Ifstream Ofstream Working With Files```

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

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

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

``` Input/Output Manipulation C++ #include <iostream> #include <fstream> #include <cstdlib> // used for the 'exit' command #include <cmath> using namespace std; int main () { // declare variables ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0; // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile.open("INPUT_Quadratic_programmingnotes_freeweq_com.txt"); // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"nError, the input file could not be found!n"; exit(1); // exits the program } // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt"); // this loop reads in data until there is no more // data contained in the file while(infile.good()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile>> a >> b>> c; // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // infile>> a[counter] >> b[counter] >> c[counter]; // ++counter; } // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via cout cout <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; cout <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; outfile <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // close the input/output files once you are done using them infile.close(); outfile.close(); // stops the program from automatically closing cin.get(); return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 #include <iostream>#include <fstream>#include <cstdlib> // used for the 'exit' command#include <cmath>using namespace std; int main (){ // declare variables ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0;  // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile.open("INPUT_Quadratic_programmingnotes_freeweq_com.txt");  // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"nError, the input file could not be found!n"; exit(1); // exits the program }  // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt");  // this loop reads in data until there is no more // data contained in the file while(infile.good()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile>> a >> b>> c;  // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // infile>> a[counter] >> b[counter] >> c[counter]; // ++counter; }  // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a);  // this displays the numbers to screen via cout cout <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; cout <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbersna = "<<a<<"nb = "<<b<<"nc = "<<c<<endl; outfile <<"nroot 1 = "<<root1<<"nroot 2 = "<<root2<<endl;  // close the input/output files once you are done using them infile.close(); outfile.close();  // stops the program from automatically closing cin.get();  return 0;}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

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

``` ```

```root 1 = 2 root 2 = -4```

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

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

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Setw```

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

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

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

``` Find The Highest/Lowest Numbers In An Array C++ #include <iostream> #include <iomanip> #include <ctime> using namespace std; const int NUM_INTS = 14; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int highestScore = -999999; int lowestScore = 999999; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // Output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line separator cout << "n--------------------------------------------------------"; // use a for loop to go thru the array checking to see the highest/lowest element cout<<"nThese are the highest and lowest array values: "; for(int index=0; index < NUM_INTS; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(arry[index] > highestScore) { highestScore = arry[index]; } // if current score in the array is smaller than the current 'lowestScore' // element, then set 'lowestScore' equal to the current array element if(arry[index] < lowestScore) { lowestScore = arry[index]; } }// end for loop // display the results to the user cout << "ntHighest: "<< highestScore; cout << "ntLowest: "<< lowestScore; cout<<endl; return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 #include <iostream>#include <iomanip>#include <ctime> using namespace std; const int NUM_INTS = 14; int main(){ // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int highestScore = -999999;     int lowestScore = 999999;     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // Output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }      // creates a line separator      cout << "n--------------------------------------------------------";      // use a for loop to go thru the array checking to see the highest/lowest element     cout<<"nThese are the highest and lowest array values: ";     for(int index=0; index < NUM_INTS; ++index)     {          // if current score in the array is bigger than the current 'highestScore'          // element, then set 'highestScore' equal to the current array element          if(arry[index] > highestScore)          {               highestScore = arry[index];          }                    // if current score in the array is smaller than the current 'lowestScore'          // element, then set 'lowestScore' equal to the current array element          if(arry[index] < lowestScore)          {               lowestScore = arry[index];          }     }// end for loop      // display the results to the user     cout << "ntHighest: "<< highestScore;     cout << "ntLowest: "<< lowestScore;     cout<<endl;      return 0;}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

```Original array values 10 14 1 94 29 25 7 95 11 17 6 71 100 59 -------------------------------------------------------- These are the highest and lowest array values: Highest: 100 Lowest: 1```

## C++ || Class – A Simple Calculator Implementation Using A Class, Enum List, Typedef & Header Files

The following is another homework assignment which was presented in a programming class, that was used to introduce the concept of the class data structure, which is very similar to the struct data structure.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Header Files - How To Use Them Class - Data Structure Enumerated List Typedef Do/While Loop Passing a Value By Reference Constant Variables Atoi - Convert String To Int Value```

This is an interactive program which simulates a basic arithmetic calculator, where the user has the option of selecting from 9 modes of operation. Of those modes, the user has the option of adding, subtracting, multiplying, and dividing two numbers together. Also included in the calculator is a mode which deducts percentages from any given variable the user desires, so for example, if the user wanted to deduct 23% from the number 87, the program would display the reduced value of 66.99.

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

``` Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8) Percentage Calculator 9) Quit Please enter a selection: 123456789101112 Calculator Options:  1) Clear Calculator  2) Set Initial Calculator Value  3) Display The Current Value  4) Add  5) Subtract  6) Divide  7) Multiply  8) Percentage Calculator  9) Quit Please enter a selection: ```

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

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

======== File #1 Main.cpp ========

``` File #1 - main.cpp C++ // ============================================================================ // This program tests the CCalc class. A loop is entered where the user is // prompted for a simple mathematical operation to be performed by the CCalc // class. The user is allowed to manipulate the calculator until they // indicate they wish to quit. // ============================================================================ #include <iostream> #include <iomanip> #include "CCalc.h" using namespace std; // defined constants const int LENGTH = 81; // function prototypes void DisplayMenu(); void HandleMenuSelection(CCalc &calcObject, int menuItem); // enumerated list enum MenuChoice { ITEM_CLEAR = 1 , ITEM_SET_VALUE = 2 , ITEM_DISPLAY_VALUE = 3 , ITEM_ADD = 4 , ITEM_SUBTRACT = 5 , ITEM_DIVIDE = 6 , ITEM_MULTIPLY = 7 , ITEM_PERCENT = 8 , ITEM_QUIT = 9}; // ==== main ================================================================== // // ============================================================================ int main() { // variable declarations CCalc calculator; // 'calculator' is an accessor to the 'CCalc' class char myString[LENGTH]; int menuItem=0; // initialize the calculator calculator.SetCurrentValue(0); // loop and let the user manipulate the calculator do{ // display the menu and get the user selection DisplayMenu(); cout << "nPlease enter a selection: "; cin.getline(myString, LENGTH); // convert the ascii string into an integer menuItem = atoi(myString); // creates a line seperator after each task is executed cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // handle the menu selection HandleMenuSelection(calculator, menuItem); cout <<endl; // creates a line seperator after each task is executed cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // ensures the menu isnt displayed twice on the screen if(menuItem!=1 && menuItem!=3 && menuItem!=9) { cin.ignore(); } }while(menuItem!=ITEM_QUIT); cout << "nBye....n"; return 0; } // end of "main" // ==== DisplayMenu =========================================================== // // This function displays the menu of options to stdout. // // Input: nothing // // Output: nothing // // ============================================================================ void DisplayMenu() { cout << "Calculator Options:" << endl; cout << " 1) Clear Calculator" << endl; cout << " 2) Set Initial Calculator Value" << endl; cout << " 3) Display The Current Value" << endl; cout << " 4) Add" << endl; cout << " 5) Subtract" << endl; cout << " 6) Divide" << endl; cout << " 7) Multiply" << endl; cout << " 8) Percentage Calculator" << endl; cout << " 9) Quit" << endl; } // end of "DisplayMenu" // ==== HandleMenuSelection =================================================== // // This function handles the menu selection by examining the input integer // value and calling the appropriate function. // // Input: // calculator -- a reference to the CCalc class // // menuItem -- an integer representing the current menu selection // // Output: // The desired user selection // // ============================================================================ void HandleMenuSelection(CCalc &calculator, int menuItem) { double currentValue = 0; double prevNum = calculator.GetPreviousValue(); // checks to see which user defined selection the calculator will execute // as defined in the enum list located above the main function. // A switch would be more practical to be used here, but i wasnt // comfortable yet using switches when this program was initially made if (menuItem == ITEM_CLEAR) { cout << "nThe current value is " << calculator.Clear() << endl; } // set a initial value else if (menuItem == ITEM_SET_VALUE) { cout << "nPlease enter a new value to assign: "; cin >> currentValue; calculator.SetCurrentValue(currentValue); } // display current value else if (menuItem == ITEM_DISPLAY_VALUE) { cout << "nThe current value is: "<< calculator.DisplayCurrentValue() <<endl; } // add current number by another number else if (menuItem == ITEM_ADD) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be added to "<<prevNum<<": "; cin >> currentValue; calculator.Add(currentValue); cout << "n"<<prevNum<<" + "<<currentValue<<" = "<< calculator.DisplayCurrentValue() <<endl; } // subtract current number by another number else if (menuItem == ITEM_SUBTRACT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be subtracted from "<<prevNum<<": "; cin >> currentValue; calculator.Subtract(currentValue); cout << "n"<<prevNum<<" - "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // divide current value by another number else if (menuItem == ITEM_DIVIDE) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a divisor to be divided by "<<prevNum<<": "; cin >> currentValue; if (currentValue == 0) { cout << "nSorry, division by zero is not allowed...nPlease press ENTER to continue..."; cin.get(); } else { calculator.Divide(currentValue); cout << "n"<<prevNum<<" "<<char(246)<<" "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } } // multiply current value by another number else if (menuItem == ITEM_MULTIPLY) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be multiplied by "<<prevNum<<": "; cin >> currentValue; calculator.Multiply(currentValue); cout << "n"<<prevNum<<" x "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // convert value to decimal percent else if (menuItem == ITEM_PERCENT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a percentage to be deducted from "<<prevNum<<": "; cin >> currentValue; cout << "n"<<currentValue<<"% off of "<<prevNum<<" is " << calculator.GetPercentage(currentValue) <<endl; } // quit program else if (menuItem == ITEM_QUIT) { cout << "nCalculator will now quit"; } // user entered an invalid choice else { cout << "nYou have entered an invalid command...nPlease press ENTER to try again."; } } // http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211 // ============================================================================// This program tests the CCalc class. A loop is entered where the user is// prompted for a simple mathematical operation to be performed by the CCalc// class. The user is allowed to manipulate the calculator until they// indicate they wish to quit.// ============================================================================#include <iostream>#include <iomanip>#include "CCalc.h"using namespace std;  // defined constantsconst   int         LENGTH = 81; // function prototypesvoid    DisplayMenu();void    HandleMenuSelection(CCalc  &calcObject, int  menuItem); // enumerated listenum    MenuChoice  { ITEM_CLEAR = 1                    , ITEM_SET_VALUE = 2                    , ITEM_DISPLAY_VALUE = 3                    , ITEM_ADD = 4                    , ITEM_SUBTRACT = 5                    , ITEM_DIVIDE = 6                    , ITEM_MULTIPLY = 7                    , ITEM_PERCENT = 8                    , ITEM_QUIT = 9}; // ==== main ==================================================================//// ============================================================================ int  main(){    // variable declarations    CCalc       calculator;  // 'calculator' is an accessor to the 'CCalc' class    char        myString[LENGTH];    int         menuItem=0;     // initialize the calculator    calculator.SetCurrentValue(0);     // loop and let the user manipulate the calculator    do{        // display the menu and get the user selection        DisplayMenu();        cout << "nPlease enter a selection: ";        cin.getline(myString, LENGTH);         // convert the ascii string into an integer        menuItem = atoi(myString);         // creates a line seperator after each task is executed        cout<<setfill('-');        cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;         // handle the menu selection        HandleMenuSelection(calculator, menuItem);        cout <<endl;         // creates a line seperator after each task is executed        cout<<setfill('-');        cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;          // ensures the menu isnt displayed twice on the screen        if(menuItem!=1 && menuItem!=3 && menuItem!=9)        {    cin.ignore();        } }while(menuItem!=ITEM_QUIT);  cout << "nBye....n";  return 0;}  // end of "main" // ==== DisplayMenu ===========================================================//// This function displays the menu of options to stdout.//// Input:  nothing//// Output: nothing//// ============================================================================void    DisplayMenu(){    cout << "Calculator Options:" << endl;    cout << "  1) Clear Calculator" << endl;    cout << "  2) Set Initial Calculator Value" << endl;    cout << "  3) Display The Current Value" << endl;    cout << "  4) Add" << endl;    cout << "  5) Subtract" << endl;    cout << "  6) Divide" << endl;    cout << "  7) Multiply" << endl;    cout << "  8) Percentage Calculator" << endl;    cout << "  9) Quit" << endl;}  // end of "DisplayMenu" // ==== HandleMenuSelection ===================================================//// This function handles the menu selection by examining the input integer// value and calling the appropriate function.//// Input://      calculator      -- a reference to the CCalc class////      menuItem        -- an integer representing the current menu selection//// Output://      The desired user selection//// ============================================================================void   HandleMenuSelection(CCalc  &calculator, int  menuItem){ double currentValue = 0; double prevNum = calculator.GetPreviousValue();  // checks to see which user defined selection the calculator will execute // as defined in the enum list located above the main function. // A switch would be more practical to be used here, but i wasnt // comfortable yet using switches when this program was initially made if (menuItem == ITEM_CLEAR) { cout << "nThe current value is " << calculator.Clear() << endl; } // set a initial value else if (menuItem == ITEM_SET_VALUE) { cout << "nPlease enter a new value to assign: "; cin >> currentValue; calculator.SetCurrentValue(currentValue); } // display current value else if (menuItem == ITEM_DISPLAY_VALUE) { cout << "nThe current value is: "<< calculator.DisplayCurrentValue() <<endl; } // add current number by another number else if (menuItem == ITEM_ADD) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be added to "<<prevNum<<": "; cin >> currentValue;   calculator.Add(currentValue); cout << "n"<<prevNum<<" + "<<currentValue<<" = "<< calculator.DisplayCurrentValue() <<endl; } // subtract current number by another number else if (menuItem == ITEM_SUBTRACT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be subtracted from "<<prevNum<<": "; cin >> currentValue;  calculator.Subtract(currentValue); cout << "n"<<prevNum<<" - "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // divide current value by another number else if (menuItem == ITEM_DIVIDE) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a divisor to be divided by "<<prevNum<<": "; cin >> currentValue; if (currentValue == 0) { cout << "nSorry, division by zero is not allowed...nPlease press ENTER to continue..."; cin.get(); } else { calculator.Divide(currentValue); cout << "n"<<prevNum<<" "<<char(246)<<" "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } }     // multiply current value by another number else if (menuItem == ITEM_MULTIPLY) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be multiplied by "<<prevNum<<": "; cin >> currentValue; calculator.Multiply(currentValue); cout << "n"<<prevNum<<" x "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // convert value to decimal percent else if (menuItem == ITEM_PERCENT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a percentage to be deducted from "<<prevNum<<": "; cin >> currentValue; cout << "n"<<currentValue<<"% off of "<<prevNum<<" is " << calculator.GetPercentage(currentValue) <<endl; } // quit program else if (menuItem == ITEM_QUIT) { cout << "nCalculator will now quit"; } // user entered an invalid choice else { cout << "nYou have entered an invalid command...nPlease press ENTER to try again."; }}  // http://programmingnotes.org/ ```

======== File #2 CCalc.h. ========

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

``` File #2 - CCalc.h C++ // ============================================================================ // File: CCalc.h // ============================================================================ // This is the header file for the CCalc class. // ============================================================================ #ifndef CCALC_HEADER #define CCALC_HEADER // a typedef statement to create a synonym for // the 'double' data type named "CCalcType" typedef double CCalcType; class CCalc // this is the 'CCalc' class declaration { public: // constructor CCalc(); // initializes variables // member functions void Add(CCalcType value); // adds numbers together CCalcType Clear(); // clears the current number in the calculator void Divide(CCalcType value); // divides numbers together CCalcType DisplayCurrentValue(); // displays the current value in the calculator CCalcType GetPreviousValue(); // returns the previous value in the calculator CCalcType GetPercentage(CCalcType value); // deducts a user specified percentage of a given value void Multiply(CCalcType value); // multiplies numbers together void SetCurrentValue(CCalcType value); // set a current value in the calculator void Subtract(CCalcType value); // subtracts two numbers together // destructor ~CCalc(); // deletes any variables contained in the class private: CCalcType m_total; // private variable used within the program }; #endif // CCALC_HEADER -- http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637 // ============================================================================// File: CCalc.h// ============================================================================// This is the header file for the CCalc class.// ============================================================================ #ifndef CCALC_HEADER#define CCALC_HEADER // a typedef statement to create a synonym for // the 'double' data type named "CCalcType"typedef double CCalcType; class   CCalc    // this is the 'CCalc' class declaration{public:    // constructor    CCalc(); // initializes variables     // member functions    void        Add(CCalcType  value); // adds numbers together    CCalcType   Clear();  // clears the current number in the calculator    void        Divide(CCalcType  value); // divides numbers together    CCalcType   DisplayCurrentValue(); // displays the current value in the calculator    CCalcType   GetPreviousValue(); // returns the previous value in the calculator    CCalcType   GetPercentage(CCalcType  value); // deducts a user specified percentage of a given value    void        Multiply(CCalcType  value); // multiplies numbers together    void        SetCurrentValue(CCalcType  value); // set a current value in the calculator    void        Subtract(CCalcType  value); // subtracts two numbers together      // destructor     ~CCalc();  // deletes any variables contained in the class private:    CCalcType   m_total; // private variable used within the program};#endif  // CCALC_HEADER -- http://programmingnotes.org/ ```

======== File #3 CCalc.cpp. ========

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

``` File #3 - CCalc.cpp C++ // ============================================================================ // File: CCalc.cpp // ============================================================================ // This is the function implementation file for the CCalc.h class. // ============================================================================ #include <iostream> #include "CCalc.h" using namespace std; CCalc::CCalc() // this is the constructor { m_total = 0; }// end of CCalc void CCalc::Add(CCalcType value) { m_total += value; }// end of Add CCalcType CCalc::Clear() { m_total = 0; return m_total; }// end of Clear void CCalc::Divide(CCalcType value) { m_total /= value; }// end of Divide CCalcType CCalc::DisplayCurrentValue() { return m_total; }// end of DisplayCurrentValue CCalcType CCalc::GetPreviousValue() { return m_total; }// end of GetPreviousValue void CCalc::Multiply(CCalcType value) { m_total *= value; }// end if Multiply void CCalc::SetCurrentValue(CCalcType value) { m_total = value; }// end of SetValue void CCalc::Subtract(CCalcType value) { m_total -= value; }// end of Subtract CCalcType CCalc::GetPercentage(CCalcType value) { CCalcType percent= value/100; CCalcType tempTotal = m_total; tempTotal *= percent; m_total -= tempTotal; return m_total; }// end of GetPercentage CCalc::~CCalc() // this is the destructor { m_total = 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 // ============================================================================// File: CCalc.cpp// ============================================================================// This is the function implementation file for the CCalc.h class.// ============================================================================#include <iostream>#include "CCalc.h"using namespace std; CCalc::CCalc() // this is the constructor{ m_total = 0;}// end of CCalc void CCalc::Add(CCalcType  value){ m_total += value;}// end of Add CCalcType CCalc::Clear(){ m_total = 0; return m_total;}// end of Clear void CCalc::Divide(CCalcType  value){ m_total /= value;}// end of Divide CCalcType CCalc::DisplayCurrentValue(){ return m_total;}// end of DisplayCurrentValue CCalcType CCalc::GetPreviousValue(){ return m_total;}// end of GetPreviousValue void CCalc::Multiply(CCalcType  value){ m_total *= value;}// end if Multiply void CCalc::SetCurrentValue(CCalcType  value){ m_total = value;}// end of SetValue void CCalc::Subtract(CCalcType  value){ m_total -= value;}// end of Subtract CCalcType CCalc::GetPercentage(CCalcType  value){ CCalcType percent= value/100; CCalcType tempTotal = m_total;   tempTotal *= percent; m_total -= tempTotal;  return m_total;}// end of GetPercentage CCalc::~CCalc() // this is the destructor{ m_total = 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

```Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit```

``` Please enter a selection: 0 ------------------------------------------------------------ You have entered an invalid command... Please ENTER to try again. ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 2 ------------------------------------------------------------ Please enter a new value to assign: 2 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 3 ------------------------------------------------------------ The current value is: 2 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 4 ------------------------------------------------------------ The current value is: 2 Please enter a number to be added to 2: 2 2 + 2 = 4 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 5 ------------------------------------------------------------ The current value is: 4 Please enter a number to be subtracted from 4: 6 4 - 6 = -2 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 6 ------------------------------------------------------------ The current value is: -2 Please enter a divisor to be divided by -2: -2 -2 ÷ -2 = 1 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 7 ------------------------------------------------------------ The current value is: 1 Please enter a number to be multiplied by 1: 87 1 x 87 = 87 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 8 ------------------------------------------------------------ The current value is: 87 Please enter a percentage to be deducted from 87: 23 23% off of 87 is 66.99 ------------------------------------------------------------ Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8.) Percentage Calculator 9) Quit Please enter a selection: 9 ------------------------------------------------------------ Calculator will now quit ------------------------------------------------------------ ```

`Bye....`

## C++ || Snippet – Bubble Sort, Selection Sort, Insertion Sort, Quick Sort & Merge Sort Sample Code For Integer Arrays

This page consists of algorithms for sorting integer arrays. Highlighted on this page are Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, and Merge Sort.

In terms of performance and speed, the sorting algorithms on this page will be listed from the (on average) worst, to best case implementations.

Selection sort and Insertion sort are two simple sorting algorithms which are often more efficient than Bubble Sort, though all three techniques aren’t the top of the class algorithmically for sorting large data sets.

====== BUBBLE SORT ======

``` #1 - Modified Bubble Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void BubbleSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; BubbleSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void BubbleSort(int arry[], int arraySize) { bool sorted = false; do{ sorted = true; for(int x = 0; x < arraySize-1; ++x) { if(arry[x] > arry[x+1]) { int temp = arry[x]; arry[x] = arry[x+1]; arry[x+1] = temp; sorted = false; } }// end of for loop --arraySize; }while(!sorted); }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid BubbleSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      BubbleSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void BubbleSort(int arry[], int arraySize){     bool sorted = false;          do{          sorted = true;          for(int x = 0; x < arraySize-1; ++x)          {               if(arry[x] > arry[x+1])               {                    int temp = arry[x];                    arry[x] = arry[x+1];                    arry[x+1] = temp;                    sorted = false;               }           }// end of for loop          --arraySize;     }while(!sorted);}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 66 loop iterations/comparisons to sort)

```Original array values 91 65 53 93 54 41 69 76 55 90 10 62 -------------------------------------------------------- The current sorted array 10 41 53 54 55 62 65 69 76 90 91 93```

====== SELECTION SORT ======

``` #2 - Selection Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void SelectionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; SelectionSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void SelectionSort(int arry[], int arraySize) { for(int currentNumber = 0; currentNumber < arraySize; ++currentNumber) { int index_of_min = currentNumber; for(int previousNumber = currentNumber+1; previousNumber < NUM_INTS; ++previousNumber) { if(arry[index_of_min]>arry[previousNumber]) { index_of_min = previousNumber; } } int temp = arry[currentNumber]; arry[currentNumber] = arry[index_of_min]; arry[index_of_min] = temp; } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid SelectionSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      SelectionSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void SelectionSort(int arry[], int arraySize){ for(int currentNumber = 0; currentNumber < arraySize; ++currentNumber) { int index_of_min = currentNumber; for(int previousNumber = currentNumber+1; previousNumber < NUM_INTS; ++previousNumber) { if(arry[index_of_min]>arry[previousNumber]) { index_of_min = previousNumber; } } int temp = arry[currentNumber]; arry[currentNumber] = arry[index_of_min]; arry[index_of_min] = temp; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 78 loop iterations/comparisons to sort)

```Original array values 87 74 58 64 4 43 23 16 3 93 9 80 -------------------------------------------------------- The current sorted array 3 4 9 16 23 43 58 64 74 80 87 93```

====== INSERTION SORT ======

``` #3 - Insertion Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void InsertionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } // output the original array values cout << "Original array values" << endl; for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; InsertionSort(arry, NUM_INTS); // display sorted values cout<<"The current sorted array"<<endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) <<arry[x]; } cout<<endl; return 0; }// end of main void InsertionSort(int arry[], int arraySize) { int previousNumber = 0; int currentNumber = 0; // iterate through entire list for(int index = 1; index < arraySize; ++index) { currentNumber = arry[index]; previousNumber = index - 1; while(previousNumber >= 0 && arry[previousNumber] > currentNumber) { arry[previousNumber + 1] = arry[previousNumber]; previousNumber = previousNumber - 1; }// end while loop arry[previousNumber + 1] = currentNumber; }// end for loop }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid InsertionSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }           // output the original array values     cout << "Original array values" << endl;     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }      // creates a line seperator      cout << "n--------------------------------------------------------n";      InsertionSort(arry, NUM_INTS);      // display sorted values     cout<<"The current sorted array"<<endl;      // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     { cout << setw(4) <<arry[x];     }     cout<<endl;      return 0;}// end of main void InsertionSort(int arry[], int arraySize){ int previousNumber = 0; int currentNumber = 0; // iterate through entire list for(int index = 1; index < arraySize; ++index) { currentNumber = arry[index]; previousNumber = index - 1; while(previousNumber >= 0 && arry[previousNumber] > currentNumber) { arry[previousNumber + 1] = arry[previousNumber]; previousNumber = previousNumber - 1; }// end while loop arry[previousNumber + 1] = currentNumber; }// end for loop}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 41 loop iterations/comparisons to sort)

```Original array values 97 80 94 74 10 38 87 7 87 14 3 97 -------------------------------------------------------- The current sorted array 3 7 10 14 38 74 80 87 87 94 97 97```

====== QUICK SORT ======

Quicksort is one of the fastest sorting algorithms, and is often the best practical choice for sorting, as its average expected running time for large data sets is more efficient than the previously discussed methods.

``` #4 - Quick Sort C++ #include <iostream> #include <ctime> #include <iomanip> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void QuickSort(int arry[], int arraySize); int Partition(int arry[], int arraySize, int pivotIndex); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; QuickSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void QuickSort(int arry[], int arraySize) { if(arraySize > 1) { // choose pivot int pivotIndex = rand()%(arraySize-1); // partition the arry and get the new pivot position int newPiviotIndex = Partition(arry, arraySize, pivotIndex); // quick sort the first part QuickSort(arry, newPiviotIndex); // quick sort the second part QuickSort(arry+newPiviotIndex+1, arraySize-newPiviotIndex-1); } }// end of QuickSort int Partition(int arry[], int arraySize, int pivotIndex) { int pivotValue = arry[pivotIndex]; arry[pivotIndex] = arry[arraySize-1]; // swap pivot with last element arry[arraySize-1] = pivotValue; int left = 0; // left index int right = arraySize-2; // right index while(left < right) { // ( < pivot ), pivot, ( >= pivot) while((arry[left] < pivotValue) && (left < right)) { ++left; } while((arry[right] >= pivotValue) && (left < right)) { --right; } if(left < right) { std::swap(arry[left],arry[right]); ++left; --right; } } if(left == right) { if(arry[left] < pivotValue) { ++left; } } arry[arraySize-1] = arry[left]; // move pivot to its final place arry[left] = pivotValue; return left; // return the position of the pivot }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 #include <iostream>#include <ctime>#include <iomanip>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypesvoid QuickSort(int arry[], int arraySize);int Partition(int arry[], int arraySize, int pivotIndex); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      QuickSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void QuickSort(int arry[], int arraySize) {    if(arraySize > 1)     {        // choose pivot        int pivotIndex = rand()%(arraySize-1);         // partition the arry and get the new pivot position        int newPiviotIndex = Partition(arry, arraySize, pivotIndex);         // quick sort the first part        QuickSort(arry, newPiviotIndex);         // quick sort the second part        QuickSort(arry+newPiviotIndex+1, arraySize-newPiviotIndex-1);     }}// end of QuickSort int Partition(int arry[], int arraySize, int pivotIndex) {    int pivotValue = arry[pivotIndex];    arry[pivotIndex] = arry[arraySize-1]; // swap pivot with last element    arry[arraySize-1] = pivotValue;    int left = 0; // left index    int right = arraySize-2; // right index     while(left < right)     { // ( < pivot ), pivot, ( >= pivot)        while((arry[left] < pivotValue) && (left < right))        {            ++left;        }        while((arry[right] >= pivotValue) && (left < right))        {            --right;        }        if(left < right)         {            std::swap(arry[left],arry[right]);            ++left;            --right;        }    }    if(left == right)    {        if(arry[left] < pivotValue)        {            ++left;        }    }    arry[arraySize-1] = arry[left]; // move pivot to its final place    arry[left] = pivotValue;    return left; // return the position of the pivot}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 38 loop iterations/comparisons to sort)

```Original array values 50 94 1 16 51 63 41 17 70 28 6 34 -------------------------------------------------------- The current sorted array 1 6 16 17 28 34 41 50 51 63 70 94```

====== MERGE SORT ======

Merge sort is a fast, stable sorting routine which, in the worst case, does about (on average) 39% fewer comparisons than quick sort.

``` #5 - Merge Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void MergeSort(int arry[], int start, int end); void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; MergeSort(arry, 0, NUM_INTS-1); cout << "The current sorted array" << endl; // output the current sorted for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void MergeSort(int arry[], int start, int end) { // no significant comparisons are done during splitting if(start < end) { int midPt = (start+end)/2; MergeSort(arry,start, midPt); MergeSort(arry,midPt+1,end); Merge(arry, start,midPt, midPt+1, end); } }// end of MergeSort void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast) { int* tempArray = new int [rightLast]; int index = leftFirst; int saveFirst = leftFirst; while((leftFirst <= leftLast) && (rightFirst <= rightLast)) {// compare and select smallest from two subarrays if(arry[leftFirst] < arry[rightFirst]) { tempArray[index] = arry[leftFirst]; // smallest assigned to temp ++leftFirst; } else { tempArray[index] = arry[rightFirst]; ++rightFirst; } ++index; } while(leftFirst <= leftLast) { tempArray[index] = arry[leftFirst]; ++leftFirst; ++index; } while(rightFirst <= rightLast) { tempArray[index] = arry[rightFirst]; ++rightFirst; ++index; } for(index = saveFirst; index <= rightLast; ++index) {// copies from temp array to the initial array arry[index] = tempArray[index]; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypesvoid MergeSort(int arry[], int start, int end);void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast); int main(){ // variable declarations int arry[NUM_INTS]; srand(time(NULL));  // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n";  MergeSort(arry, 0, NUM_INTS-1); cout << "The current sorted array" << endl; // output the current sorted for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl;  return 0;}// end of main void MergeSort(int arry[], int start, int end){  // no significant comparisons are done during splitting    if(start < end)    {        int midPt = (start+end)/2;           MergeSort(arry,start, midPt);        MergeSort(arry,midPt+1,end);        Merge(arry, start,midPt, midPt+1, end);    }}// end of MergeSort void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast){ int* tempArray = new int [rightLast]; int index = leftFirst; int saveFirst = leftFirst; while((leftFirst <= leftLast)  && (rightFirst <= rightLast)) {// compare and select smallest from two subarrays if(arry[leftFirst] < arry[rightFirst]) { tempArray[index]  = arry[leftFirst]; // smallest assigned to temp ++leftFirst; } else { tempArray[index]  = arry[rightFirst]; ++rightFirst; } ++index; } while(leftFirst <= leftLast) { tempArray[index] = arry[leftFirst]; ++leftFirst; ++index; } while(rightFirst <= rightLast) { tempArray[index] = arry[rightFirst]; ++rightFirst; ++index; } for(index = saveFirst; index <= rightLast; ++index) {// copies from temp array to the initial array arry[index] = tempArray[index]; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 29 loop iterations/comparisons to sort)

```Original array values 18 46 41 30 84 97 54 49 19 32 70 30 -------------------------------------------------------- The current sorted array 18 19 30 30 32 41 46 49 54 70 84 97```

## C++ || Dynamic Arrays – Create A Music Strore Database Which Sorts CD Information & Display Grand Total

This program was presented as a homework assignment in a programming class to demonstrate the use of dynamic arrays, and pointer variables. The pointer variables which are displayed in this program are very excessive; and many are not needed, but it was good practice when trying to understand the logic behind it all.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Pointer Variables Dynamic Arrays 2-D Dynamic Arrays - How To Declare Bubble Sort While Loops For Loops Constant Variables Functions Switch Statements Toupper Strcpy Strcmp```

This is an interactive program, which simulates a database for a music store, in which the user inputs data into the program (artist, CD title, genre, sales price, tax) and stores that information into multiple dynamic arrays (2-D and/or one dimensional dynamic arrays). The program will also apply any discounts that may currently be available for the selected CD genre, and applies that discount to the current CD information. When the user chooses to quit, the program will sort any data which is currently stored inside the array (by artist) in ascending order, and output the subtotal, tax applied, and grand total for all of the CD information which is entered into the array to the user.

After the program is complete, it will display a summary of the data which was stored into the array like so:

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

``` Music Store Database C++ // ============================================================================= // This is an interactive program, which simulates a database for a music store // in which the user inputs data into the program (atrist, CD title, genre, // sales price, tax) and stores the data into a dynamic array. The program will // also apply any discounts that may currently be available to the selected CD // genre, and applies that discount to the current CD. When the user choses // to quit, the program will sort any data that is stored inside the array // (by artist) in ascending order and it will output the subtotal, tax applied, // and grand total for all of the CD information which is entered into the array // ============================================================================= #include <iostream> #include <iomanip> #include <string> #include <ctime> using namespace std; // function prototypes double* GetDiscounts(); void DisplayMenu(); void GetCDInfo(char** &artist, char** &CDTitle, char** &genre,double* &salesPrice, double* &taxRate, int* numItems); void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent,double* discountRate); void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal); void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax); void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal); void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems); void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems); // constant discount values // these values are defines within the // 'GetDiscounts' function const double* discounts = GetDiscounts(); // ============================================================================= // main // ============================================================================= int main() { //-- Declare Variables START ---// // numItems for artist array int* numItems = new int(0); // 2-D Dynamic array for music genres char** musicGenre = new char*[7]; for(int index=0; index < 7; ++index) {musicGenre[index] = new char[13];} musicGenre[0]= "Classical"; musicGenre[1]= "Country"; musicGenre[2]= "International"; musicGenre[3]= "Jazz"; musicGenre[4]= "Pop"; musicGenre[5]= "Rock"; musicGenre[6]= "Rap"; // 2-D Dynamic Array for artist name char** artist = new char*[50]; for(int index=0; index < 50; ++index) {artist[index] = new char[20];} // 2-D Dynamic array for CD titles char** CDTitle = new char*[50]; for(int index=0; index < 50; ++index) {CDTitle[index] = new char[20];} // 2-D Dynamic array of music genre char** genre = new char*[50]; for(int index=0; index < 50; ++index) {genre[index] = new char[20];} // array for list price double* salesPrice = new double[20]; // array for tax rate double* taxRate = new double[20]; // array for discount amount double* discountRate= new double[20]; // array for sales price double* subTotal = new double[20]; // array for taxamount double* salesTax= new double[20]; // array for grandTotal double* grandTotal = new double[20]; // array for discount percent double* discountPercent = new double[20]; // variable for the while loop menu char* userInput = new char('n'); // variable if the user wants to enter more data char* enterMoreData = new char('y'); //-- Declare Variables END ---// // display menu DisplayMenu(); cin >> userInput; // loop thru menu options while((toupper(*userInput) !='Q')) { switch(toupper(*userInput)) { case 'E': // get artist info GetCDInfo(artist, CDTitle, genre, salesPrice, taxRate, numItems); // get discount GetDiscountRate(salesPrice, musicGenre, genre, numItems,discountPercent, discountRate); // get sub total GetSubTotal(salesPrice, discountRate, numItems,subTotal); // get tax amount GetTaxAmount(salesPrice, taxRate, numItems,salesTax); // get cash price GetGrandTotal(subTotal, salesTax, numItems,grandTotal); // ask if they want to enter more data cout << "nDo you want to enter more CD's? (y/n): "; cin >> *enterMoreData; if(toupper(*enterMoreData)=='Y') { (++*numItems); } else { (++*numItems); *userInput='q'; } break; case 'D': DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); break; default: cout<<"nYou have selected an invalid command"; break; } //creates a line separator cout<<endl; cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // if user wants to enter more data, display menu to screen if(toupper(*enterMoreData)=='Y') { DisplayMenu(); cin >> userInput; } }// end of while loop // sort the current data inside the array SortData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); // display the current data inside the array DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); return 0; }// End of Main // ============================================================================= // DisplayMenu // displays the menu to the user // ============================================================================= void DisplayMenu() { cout<<"Welcome to the CD Management System!"; cout<<"nFrom the following menu, select an option"; cout<<"nnE - Enter new CD information into the database"; cout<<"nD - Display the current information in the database"; cout<<"nQ - Quit"; cout<<"nn>> "; }// End of DisplayMenu // ============================================================================= // DisplayData // displays the current contents in the array. If there is nothing in the array // the program promts a message to the user // ============================================================================= void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre, double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems) { double* totSalePrice = new double(0); double* totSalesTax = new double(0); double* totgrandTotal = new double(0); // variables which will get the current date time_t t = time(0); // get current CPU time struct tm * now = localtime(& t); // if array is empty, display message if(*numItems ==0) { cout<<"nThe database is currently empty!n"; } else { // displays the company header to the user cout<<setfill(' '); cout << "nttttMy Programming Notes Record Company" << "ntttt Sales Report for "<<now->tm_mon + 1<<"/"<<now->tm_mday<<"/"<<now->tm_year + 1900<<"nn"; // displays the categories which will be shown to the user cout <<setw(1)<<right<<"Artist"<<setw(13)<<"Title"<<setw(13)<<"SalesPrice" <<setw(13)<<"Genre"<<setw(20)<<"DiscountRate"<<setw(13)<<"SubTotal" <<setw(13)<<"SalesTax"<<setw(13)<<"GrandTotal"; // displays the data which is currently inside the array's cout<<fixed<<setprecision(2); for(int* index = new int(0); *index < *numItems; ++*index) { cout << endl; cout <<setw(1)<<right<<artist[*index]<<setw(15)<<CDTitle[*index] <<setw(13)<<salesPrice[*index]<<setw(15)<<genre[*index]<<setw(13) <<discountPercent[*index]*100<<"%"<<setw(15)<<subTotal[*index]<<setw(16) <<salesTax[*index]<<setw(13)<<grandTotal[*index]; } // finds the total prices for the entire list of CD's for(int* index = new int(0); *index < *numItems; ++*index) { *totSalePrice+= subTotal[*index]; *totSalesTax+= salesTax[*index]; *totgrandTotal+= grandTotal[*index]; } // creates a line separator cout<<setfill('-'); cout<<endl<<endl<<left<<setw(52)<<""<<right<<setw(52)<<""<<endl; // displays the total to the user cout<< "Total ("<<*numItems<<" transactions)ttttttt" <<*totSalePrice<<"tt"<<*totSalesTax<<"t"<<*totgrandTotal<<endl; } }// End of DisplayData // ============================================================================= // SortData // sorts all the data which is currently present in the arrays via bubble sort // this function does not display any data to the user // ============================================================================= void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems) { // bool which will tell us if sorting is complete bool sorted = false; // temporary variables for sorting purposes only char* tempArtist = new char[20]; char* tempCDTitle= new char[20]; char* tempGenre= new char[20]; double* tempListPrice= new double[20]; double* tempDiscountPercent = new double[20]; double* tempsubTotal = new double[20]; double* tempTaxAmt = new double[20]; double* tempgrandTotal = new double[20]; // this is the bubble sort // which sorts the entries by artist in ascending order while (sorted==false) { sorted=true; for(int* index= new int(0); *index < *numItems-1; ++*index) { // checks the artist to see if they are in the correct order if (strcmp(artist[*index],artist[*index+1]) > 0) { // swaps artist places strcpy(tempArtist, artist[*index]); strcpy(artist[*index], artist[*index+1]); strcpy(artist[*index+1], tempArtist); // swaps CD title strcpy(tempCDTitle, CDTitle[*index]); strcpy(CDTitle[*index], CDTitle[*index+1]); strcpy(CDTitle[*index+1], tempCDTitle); // swaps music genre strcpy(tempGenre, genre[*index]); strcpy(genre[*index], genre[*index+1]); strcpy(genre[*index+1], tempGenre); // swaps the CD price *tempgrandTotal = grandTotal[*index]; grandTotal[*index] = grandTotal[*index+1]; grandTotal[*index+1] = *tempgrandTotal; // swaps the tax amount *tempTaxAmt = salesTax[*index]; salesTax[*index] = salesTax[*index+1]; salesTax[*index+1] = *tempTaxAmt; // swaps the sales price *tempsubTotal = subTotal[*index]; subTotal[*index] = subTotal[*index+1]; subTotal[*index+1] = *tempsubTotal; // swaps the discount percent *tempDiscountPercent = discountPercent[*index]; discountPercent[*index] = discountPercent[*index+1]; discountPercent[*index+1] = *tempDiscountPercent; // swaps the list price *tempListPrice = salesPrice[*index]; salesPrice[*index] = salesPrice[*index+1]; salesPrice[*index+1] = *tempListPrice; // sets the 'sorted' variable to false sorted=false; }// end of if statement }// end for loop }// end while loop }// End of SortData // ============================================================================= // GetGrandTotal // calculates the grand total for the current transaction // ============================================================================= void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal) { grandTotal[*numItems]= (subTotal[*numItems])+(salesTax[*numItems]); }// End of GetgrandTotal // ============================================================================= // GetTaxAmount // calculates the sales tax for the current transaction // ============================================================================= void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax) { salesTax[*numItems] = (salesPrice[*numItems])* (taxRate[*numItems]); }// End of GetTaxAmount // ============================================================================= // GetSubTotal // gets the subtotal for the current transaction // ============================================================================= void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal) { subTotal[*numItems] = (salesPrice[*numItems]) - (discountRate[*numItems]); }// End of GetsubTotal // ============================================================================= // GetDiscountRate // gets the discount rate for the currently selected CD // ============================================================================= void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent, double* discountRate) { // comapres the user inputted current genre to the pre-defined // genres as defined in the main function, then assigns a // discount to the current CD if(strcmp(genre[*numItems],musicGenre[0]) == 0) // if music genre is Classical {discountPercent[*numItems] = discounts[0];} else if(strcmp(genre[*numItems],musicGenre[1]) == 0) // if music genre is Country {discountPercent[*numItems] = discounts[1];} else if(strcmp(genre[*numItems],musicGenre[2]) == 0) // if music genre is International {discountPercent[*numItems] = discounts[2];} else if(strcmp(genre[*numItems],musicGenre[3]) == 0) // if music genre is Jazz {discountPercent[*numItems] = discounts[3];} else if(strcmp(genre[*numItems],musicGenre[4]) == 0) // if music genre is Pop {discountPercent[*numItems] = discounts[4];} else if(strcmp(genre[*numItems],musicGenre[5]) == 0) // if music genre is Rock {discountPercent[*numItems] = discounts[5];} else if(strcmp(genre[*numItems],musicGenre[6]) == 0) // if music genre is Rap {discountPercent[*numItems] = discounts[6];} else{discountPercent[*numItems] = discounts[4];} // if music genre is not any of these ^, then there is no discount // assign the discount rate to the current CD discountRate[*numItems] = (discountPercent[*numItems]) * (salesPrice[*numItems]); }// End of GetDiscountRate // ============================================================================= // GetCDInfo // obtains the CD information from the user // ============================================================================= void GetCDInfo(char** &artist, char** &CDTitle, char** &genre, double* &salesPrice, double* &taxRate, int* numItems) { cin.ignore(); cout << "nEnter the name of the artist: "; cin.getline(artist[*numItems],50, 'n'); cout << "nEnter the title of the CD: "; cin.getline(CDTitle[*numItems],50, 'n'); cout << "nEnter the genre: "; cin.getline(genre[*numItems], 20); cout << "nEnter the sales price \$"; cin >> salesPrice[*numItems]; cout << "nEnter the sales tax: "; cin >> taxRate[*numItems]; }// End of GetInfo // ============================================================================= // GetDiscounts // returns the discount rate for the selected genre // ============================================================================= double* GetDiscounts() { double* temp = new double[7]; temp[0] = .09; // discount rate for Classical temp[1] = .03; // discount rate for Country temp[2] = .11; // discount rate for International temp[3] = .18; // discount rate for Jazz temp[4] = .00; // discount rate for Pop temp[5] = .10; // discount rate for Rock temp[6] = .07; // discount rate for Rap return temp; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 // =============================================================================// This is an interactive program, which simulates a database for a music store // in which the user inputs data into the program (atrist, CD title, genre, // sales price, tax) and stores the data into a dynamic array. The program will // also apply any discounts that may currently be available to the selected CD // genre, and applies that   discount to the current CD. When the user choses // to quit, the program will  sort any data that is stored inside the array // (by artist) in ascending order and it will output the subtotal, tax applied, // and grand total for all of the CD information which is entered into the array// =============================================================================#include <iostream>#include <iomanip>#include <string>#include <ctime>using namespace std; // function prototypesdouble* GetDiscounts();void DisplayMenu();void GetCDInfo(char** &artist, char** &CDTitle, char** &genre,double* &salesPrice, double* &taxRate, int* numItems);void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent,double* discountRate);void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal);void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax);void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal);void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax,  double*grandTotal, int* numItems);void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems); // constant discount values // these values are defines within the// 'GetDiscounts' functionconst double* discounts = GetDiscounts(); // =============================================================================// main// =============================================================================int main(){ //-- Declare Variables START ---// // numItems for artist array int* numItems = new int(0);  // 2-D Dynamic array for music genres char** musicGenre = new char*[7]; for(int index=0; index < 7; ++index) {musicGenre[index] = new char[13];} musicGenre[0]= "Classical"; musicGenre[1]= "Country"; musicGenre[2]= "International"; musicGenre[3]= "Jazz"; musicGenre[4]= "Pop"; musicGenre[5]= "Rock"; musicGenre[6]= "Rap";  // 2-D Dynamic Array for artist name char** artist = new char*[50]; for(int index=0; index < 50; ++index) {artist[index] = new char[20];}  // 2-D Dynamic array for CD titles char** CDTitle = new char*[50]; for(int index=0; index < 50; ++index) {CDTitle[index] = new char[20];}  // 2-D Dynamic array of music genre char** genre = new char*[50]; for(int index=0; index < 50; ++index) {genre[index] = new char[20];}  // array for list price double* salesPrice = new double[20];  // array for tax rate double* taxRate = new double[20];  // array for discount amount double* discountRate= new double[20];  // array for sales price double* subTotal = new double[20];  // array for taxamount double* salesTax= new double[20];  // array for grandTotal double* grandTotal = new double[20];  // array for discount percent double* discountPercent = new double[20];  // variable for the while loop menu char* userInput = new char('n');  // variable if the user wants to enter more data char* enterMoreData = new char('y');  //-- Declare Variables END ---//  // display menu DisplayMenu(); cin >> userInput;  // loop thru menu options while((toupper(*userInput) !='Q')) { switch(toupper(*userInput)) { case 'E': // get artist info GetCDInfo(artist, CDTitle, genre, salesPrice, taxRate, numItems); // get discount GetDiscountRate(salesPrice, musicGenre, genre, numItems,discountPercent, discountRate); // get sub total GetSubTotal(salesPrice, discountRate, numItems,subTotal); // get tax amount GetTaxAmount(salesPrice, taxRate, numItems,salesTax); // get cash price GetGrandTotal(subTotal, salesTax, numItems,grandTotal); // ask if they want to enter more data cout << "nDo you want to enter more CD's? (y/n): "; cin >> *enterMoreData; if(toupper(*enterMoreData)=='Y') { (++*numItems); } else { (++*numItems); *userInput='q'; } break; case 'D': DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); break; default: cout<<"nYou have selected an invalid command"; break; } //creates a line separator cout<<endl; cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;   // if user wants to enter more data, display menu to screen if(toupper(*enterMoreData)=='Y') { DisplayMenu(); cin >> userInput; } }// end of while loop // sort the current data inside the array SortData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems);  // display the current data inside the array DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems);  return 0;}// End of Main // =============================================================================// DisplayMenu// displays the menu to the user// =============================================================================void DisplayMenu(){ cout<<"Welcome to the CD Management System!"; cout<<"nFrom the following menu, select an option"; cout<<"nnE - Enter new CD information into the database"; cout<<"nD - Display the current information in the database"; cout<<"nQ - Quit"; cout<<"nn>> ";}// End of DisplayMenu // =============================================================================// DisplayData// displays the current contents in the array. If there is nothing in the array// the program promts a message to the user// =============================================================================void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre,   double*discountPercent, double*subTotal, double*salesTax,   double*grandTotal, int* numItems){ double* totSalePrice = new double(0); double* totSalesTax = new double(0); double* totgrandTotal = new double(0);  // variables which will get the current date    time_t t = time(0);   // get current CPU time     struct tm * now = localtime(& t);  // if array is empty, display message if(*numItems ==0) { cout<<"nThe database is currently empty!n"; } else { // displays the company header to the user cout<<setfill(' '); cout << "nttttMy Programming Notes Record Company" << "ntttt    Sales Report for "<<now->tm_mon + 1<<"/"<<now->tm_mday<<"/"<<now->tm_year + 1900<<"nn";  // displays the categories which will be shown to the user cout <<setw(1)<<right<<"Artist"<<setw(13)<<"Title"<<setw(13)<<"SalesPrice" <<setw(13)<<"Genre"<<setw(20)<<"DiscountRate"<<setw(13)<<"SubTotal" <<setw(13)<<"SalesTax"<<setw(13)<<"GrandTotal"; // displays the data which is currently inside the array's cout<<fixed<<setprecision(2); for(int* index = new int(0); *index < *numItems; ++*index) { cout << endl; cout <<setw(1)<<right<<artist[*index]<<setw(15)<<CDTitle[*index] <<setw(13)<<salesPrice[*index]<<setw(15)<<genre[*index]<<setw(13) <<discountPercent[*index]*100<<"%"<<setw(15)<<subTotal[*index]<<setw(16) <<salesTax[*index]<<setw(13)<<grandTotal[*index]; }  // finds the total prices for the entire list of CD's for(int* index = new int(0); *index < *numItems; ++*index) { *totSalePrice+= subTotal[*index]; *totSalesTax+= salesTax[*index]; *totgrandTotal+= grandTotal[*index]; }  // creates a line separator cout<<setfill('-'); cout<<endl<<endl<<left<<setw(52)<<""<<right<<setw(52)<<""<<endl;  // displays the total to the user cout<< "Total ("<<*numItems<<" transactions)ttttttt" <<*totSalePrice<<"tt"<<*totSalesTax<<"t"<<*totgrandTotal<<endl; }}// End of DisplayData // =============================================================================// SortData// sorts all the data which is currently present in the arrays via bubble sort// this function does not display any data to the user// =============================================================================void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax,   double*grandTotal, int* numItems){ // bool which will tell us if sorting is complete bool sorted = false;  // temporary variables for sorting purposes only char* tempArtist = new char[20]; char* tempCDTitle= new char[20]; char* tempGenre= new char[20]; double* tempListPrice= new double[20]; double* tempDiscountPercent = new double[20]; double* tempsubTotal = new double[20]; double* tempTaxAmt = new double[20]; double* tempgrandTotal = new double[20]; // this is the bubble sort // which sorts the entries by artist in ascending order while (sorted==false) { sorted=true; for(int* index= new int(0); *index < *numItems-1; ++*index) { // checks the artist to see if they are in the correct order if (strcmp(artist[*index],artist[*index+1]) > 0) { // swaps artist places strcpy(tempArtist, artist[*index]); strcpy(artist[*index], artist[*index+1]); strcpy(artist[*index+1], tempArtist);  // swaps CD title strcpy(tempCDTitle, CDTitle[*index]); strcpy(CDTitle[*index], CDTitle[*index+1]); strcpy(CDTitle[*index+1], tempCDTitle); // swaps music genre strcpy(tempGenre, genre[*index]); strcpy(genre[*index], genre[*index+1]); strcpy(genre[*index+1], tempGenre); // swaps the CD price *tempgrandTotal = grandTotal[*index]; grandTotal[*index] = grandTotal[*index+1]; grandTotal[*index+1] = *tempgrandTotal; // swaps the tax amount *tempTaxAmt = salesTax[*index]; salesTax[*index] = salesTax[*index+1]; salesTax[*index+1] = *tempTaxAmt; // swaps the sales price *tempsubTotal = subTotal[*index]; subTotal[*index] = subTotal[*index+1]; subTotal[*index+1] = *tempsubTotal; // swaps the discount percent *tempDiscountPercent = discountPercent[*index]; discountPercent[*index] = discountPercent[*index+1]; discountPercent[*index+1] = *tempDiscountPercent; // swaps the list price *tempListPrice = salesPrice[*index]; salesPrice[*index] = salesPrice[*index+1]; salesPrice[*index+1] = *tempListPrice;  // sets the 'sorted' variable to false sorted=false; }// end of if statement }// end for loop }// end while loop}// End of SortData // =============================================================================// GetGrandTotal// calculates the grand total for the current transaction// =============================================================================void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal){ grandTotal[*numItems]= (subTotal[*numItems])+(salesTax[*numItems]); }// End of GetgrandTotal // =============================================================================// GetTaxAmount// calculates the sales tax for the current transaction// =============================================================================void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax){ salesTax[*numItems] = (salesPrice[*numItems])* (taxRate[*numItems]);}// End of GetTaxAmount // =============================================================================// GetSubTotal// gets the subtotal for the current transaction// =============================================================================void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal){ subTotal[*numItems] = (salesPrice[*numItems]) - (discountRate[*numItems]);}// End of GetsubTotal // =============================================================================// GetDiscountRate// gets the discount rate for the currently selected CD// =============================================================================void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent, double* discountRate){ // comapres the user inputted current genre to the pre-defined // genres as defined in the main function, then assigns a // discount to the current CD if(strcmp(genre[*numItems],musicGenre[0]) == 0) // if music genre is Classical {discountPercent[*numItems] = discounts[0];} else if(strcmp(genre[*numItems],musicGenre[1]) == 0) // if music genre is Country {discountPercent[*numItems] = discounts[1];} else if(strcmp(genre[*numItems],musicGenre[2]) == 0) // if music genre is International {discountPercent[*numItems] = discounts[2];} else if(strcmp(genre[*numItems],musicGenre[3]) == 0) // if music genre is Jazz {discountPercent[*numItems] = discounts[3];} else if(strcmp(genre[*numItems],musicGenre[4]) == 0) // if music genre is Pop {discountPercent[*numItems] = discounts[4];} else if(strcmp(genre[*numItems],musicGenre[5]) == 0) // if music genre is Rock {discountPercent[*numItems] = discounts[5];} else if(strcmp(genre[*numItems],musicGenre[6]) == 0) // if music genre is Rap {discountPercent[*numItems] = discounts[6];} else{discountPercent[*numItems] = discounts[4];} // if music genre is not any of these ^, then there is no discount // assign the discount rate to the current CD discountRate[*numItems] = (discountPercent[*numItems]) * (salesPrice[*numItems]);}// End of GetDiscountRate // =============================================================================// GetCDInfo// obtains the CD information from the user// =============================================================================void GetCDInfo(char** &artist, char** &CDTitle, char** &genre, double* &salesPrice, double* &taxRate, int* numItems){ cin.ignore(); cout << "nEnter the name of the artist: "; cin.getline(artist[*numItems],50, 'n'); cout << "nEnter the title of the CD: "; cin.getline(CDTitle[*numItems],50, 'n'); cout << "nEnter the genre: "; cin.getline(genre[*numItems], 20); cout << "nEnter the sales price \$"; cin >> salesPrice[*numItems]; cout << "nEnter the sales tax: "; cin >> taxRate[*numItems];}// End of GetInfo // =============================================================================// GetDiscounts// returns the discount rate for the selected genre// =============================================================================double* GetDiscounts(){ double* temp =  new double[7]; temp[0] = .09; // discount rate for Classical temp[1] = .03; // discount rate for Country temp[2] = .11; // discount rate for International temp[3] = .18; // discount rate for Jazz temp[4] = .00; // discount rate for Pop temp[5] = .10; // discount rate for Rock temp[6] = .07; // discount rate for Rap return temp;}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

```Welcome to the CD Management System! From the following menu, select an option```

``` E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm8 Enter the title of the CD: CD8 Enter the genre: Rock Enter the sales price \$12.99 Enter the sales tax: .098 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm7 Enter the title of the CD: CD7 Enter the genre: Country Enter the sales price \$10.99 Enter the sales tax: .078 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm6 Enter the title of the CD: CD6 Enter the genre: Pop Enter the sales price \$11.50 Enter the sales tax: .067 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm5 Enter the title of the CD: CD5 Enter the genre: Jazz Enter the sales price \$12.24 Enter the sales tax: .045 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm4 Enter the title of the CD: CD4 Enter the genre: Other Enter the sales price \$12.99 Enter the sales tax: .094 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm3 Enter the title of the CD: CD3 Enter the genre: Classical Enter the sales price \$11.45 Enter the sales tax: .078 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e Enter the name of the artist: Nm2 Enter the title of the CD: CD2 Enter the genre: International Enter the sales price \$10.99 Enter the sales tax: .093 Do you want to enter more CD's? (y/n): y ------------------------------------------------------------ Welcome to the CD Management System! From the following menu, select an option E - Enter new CD information into the database D - Display the current information in the database Q - Quit >> e ```

```Enter the name of the artist: Nm1 Enter the title of the CD: CD1 Enter the genre: Rap Enter the sales price \$12.99 Enter the sales tax: .0975 Do you want to enter more CD's? (y/n): n```

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

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

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Constants```

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

``` Insert & Display Items In An Array C++ #include <iostream> using namespace std; // const int allocating space for the array const int ARRAY_SIZE = 100; int main() { // declare variables int numElems = 0; int myArray[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements // ask user how many items they want to place in array cout << "How many items do you want to place into the array?: "; cin >> numElems; // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { cout << "nEnter item #" << index +1<< " : "; cin >> myArray[index]; } // display data to user cout << "nThe current items inside the array are: "; // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { cout << "nItem #" << index +1<< " : "; cout << myArray[index]; } cout<<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738 #include <iostream>using namespace std; // const int allocating space for the arrayconst int ARRAY_SIZE = 100; int main(){     // declare variables     int numElems = 0;     int myArray[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements      // ask user how many items they want to place in array     cout << "How many items do you want to place into the array?: ";     cin >> numElems;      // user enters data into array using a for loop     // you can also use a while loop, but for loops are more common     // when dealing with arrays     for(int index=0; index < numElems; ++index)     {          cout << "nEnter item #" << index +1<< " : ";          cin >> myArray[index];     }       // display data to user     cout << "nThe current items inside the array are: ";      // display contents inside array using a for loop     for(int index=0; index < numElems; ++index)     {          cout << "nItem #" << index +1<< " : ";          cout << myArray[index];     }     cout<<endl;      return 0;}// http://programmingnotes.org/ ```

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

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

Once compiled, you should get this as your output

```How many items do you want to place into the array?: 5 Enter item #1 : 45```

``` Enter item #2 : 7 Enter item #3 : 34 Enter item #4 : 8 ```

```Enter item #5 : 2 The current items inside the array are: Item #1 : 45 Item #2 : 7 Item #3 : 34 Item #4 : 8 Item #5 : 2```

## C++ || Snippet – Sort An Integer Array Using Bubble Sort – Print Each Pass & Total Number Of Swaps

This is a program which has no functionality, but displays the sorting of an integer array through the use of the bubble sort algorithm.

This program sorts the values of a one-dimensional array in ascending order using bubble sort. It also prints the total number of passes thru each iteration

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays Bubble Sort Setw```

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

``` Bubble Sort - Int Array C++ //============================================================================= // This program sorts the values of a one-dimensional array // in ascending order using the Bubble Sort Algorithm. // It also prints the total number of passes thru each iteration //============================================================================= #include <iostream> #include <iomanip> using namespace std; // const int const int NUM_INTS = 12; // function prototype void BubbleSort(int arry[], int &totalSwaps, int &totalPasses); int main() { // Declarations int arry[NUM_INTS] = { 0, 1, 3, 95, 2, 4, 6, 10, 15, 4, 17, 35}; int totalSwaps=0; int totalPasses=0; cout << "Original array values" << endl; // Output the original array values for( int i = 0; i < NUM_INTS; i++ ) { cout << setw( 4 ) << arry[ i ]; } // creates a line separator cout << "n---------------------------------------------------------------nn"; BubbleSort(arry,totalSwaps,totalPasses); // creates a line separator cout << "---------------------------------------------------------------n"; cout << "The current sorted array" << endl; // Output the current sorted for( int i = 0; i < NUM_INTS; i++ ) { cout << setw( 4 ) << arry[ i ]; } // creates a line separator cout << "n---------------------------------------------------------------n"; // Display some statistics to the user cout << "Total Swaps: " << totalSwaps << endl; cout << "Total Passes: " << totalPasses << "nn"; return 0; }// end of main void BubbleSort(int arry[], int &totalSwaps, int &totalPasses) { int currentSwaps = 0; // Loop to determine amount of passes for( int iteration = 1; iteration < NUM_INTS; iteration++ ) { // Reset variable swaps to zero currentSwaps = 0; // Bubble Sort Algorithm // Sort numbers in ascending order for( int p = 0; p < NUM_INTS - iteration; p++ ) { // if the previous value is bigger than the next // then swap places if(arry[p]> arry[p+1]) { int temp = arry[p]; arry[p] = arry[p+1]; arry[p+1]= temp; currentSwaps++; } } cout << "Array after bubble sort pass #" << iteration << endl; // Display values after each pass for( int x = 0; x < NUM_INTS; x++ ) { cout << setw(4) << arry[x]; } cout << "nn"; // Keeps track of the amount of swaps and passes totalSwaps += currentSwaps; totalPasses++; // If no swaps were made in the last pass, // no need to continue the loop. Sorting complete. if( currentSwaps == 0 ) { break; } }// end of for loop }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 //=============================================================================//  This program sorts the values of a one-dimensional array     //  in ascending order using the Bubble Sort Algorithm.    // It also prints the total number of passes thru each iteration//=============================================================================#include <iostream>#include <iomanip>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid BubbleSort(int arry[], int &totalSwaps, int &totalPasses); int main(){     // Declarations     int arry[NUM_INTS] = { 0, 1, 3, 95, 2, 4, 6, 10, 15, 4, 17, 35};     int totalSwaps=0;      int totalPasses=0;      cout << "Original array values" << endl;      // Output the original array values     for( int i = 0; i < NUM_INTS; i++ )     {          cout << setw( 4 ) << arry[ i ];     }     // creates a line separator      cout << "n---------------------------------------------------------------nn";      BubbleSort(arry,totalSwaps,totalPasses);      // creates a line separator     cout << "---------------------------------------------------------------n";     cout << "The current sorted array" << endl;      // Output the current sorted     for( int i = 0; i < NUM_INTS; i++ )     {          cout << setw( 4 ) << arry[ i ];     }      // creates a line separator     cout << "n---------------------------------------------------------------n";     // Display some statistics to the user     cout << "Total Swaps: " << totalSwaps << endl;     cout << "Total Passes: " << totalPasses << "nn";      return 0;}// end of main void BubbleSort(int arry[], int &totalSwaps, int &totalPasses){     int currentSwaps = 0;      // Loop to determine amount of passes     for( int iteration = 1; iteration < NUM_INTS; iteration++ )     {          // Reset variable swaps to zero          currentSwaps = 0;           // Bubble Sort Algorithm          // Sort numbers in ascending order          for( int p = 0; p < NUM_INTS - iteration; p++ )          {               // if the previous value is bigger than the next               // then swap places               if(arry[p]> arry[p+1])               {                    int temp = arry[p];                    arry[p] = arry[p+1];                    arry[p+1]= temp;                    currentSwaps++;               }          }           cout << "Array after bubble sort pass #" << iteration << endl;           // Display values after each pass          for( int x = 0; x < NUM_INTS; x++ )          {               cout << setw(4) << arry[x];          }           cout << "nn";           // Keeps track of the amount of swaps and passes          totalSwaps += currentSwaps;          totalPasses++;           // If no swaps were made in the last pass,          // no need to continue the loop. Sorting complete.          if( currentSwaps == 0 )          {               break;          }     }// end of for loop}// 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

```Original array values 0 1 3 95 2 4 6 10 15 4 17 35 --------------------------------------------------------------- Array after bubble sort pass #1 0 1 3 2 4 6 10 15 4 17 35 95```

``` Array after bubble sort pass #2 0 1 2 3 4 6 10 4 15 17 35 95 Array after bubble sort pass #3 0 1 2 3 4 6 4 10 15 17 35 95 Array after bubble sort pass #4 0 1 2 3 4 4 6 10 15 17 35 95 ```

```Array after bubble sort pass #5 0 1 2 3 4 4 6 10 15 17 35 95 --------------------------------------------------------------- The current sorted array 0 1 2 3 4 4 6 10 15 17 35 95 --------------------------------------------------------------- Total Swaps: 12 Total Passes: 5 ```

## C++ || Modulus – Celsius To Fahrenheit Conversion Displaying Degrees Divisible By 10 Using Modulus

This page will consist of two simple programs which demonstrate the use of the modulus operator (%).

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Modulus Do/While Loop Functions Simple Math - Divisibility Celsius to Fahrenheit Conversion```

===== FINDING THE DIVISIBILITY OF A NUMBER =====

Take a simple arithmetic problem: what’s left over when you divide an odd number by an even number? The answer may not be easy to compute, but we know that it will most likely result in an answer which has a decimal remainder. How would we determine the divisibility of a number in a programming language like C++? That’s where the modulus operator comes in handy.

To have divisibility means that when you divide the first number by another number, the quotient (answer) is a whole number (i.e – no decimal values). Unlike the division operator, the modulus operator (‘%’), has the ability to give us the remainder of a given mathematical operation that results from performing integer division.

To illustrate this, here is a simple program which prompts the user to enter a number. Once the user enters a number, they are asked to enter in a divisor for the previous number. Using modulus, the program will determine if the second number is divisible by the first number. If the modulus result returns 0, the two numbers are divisible. If the modulus result does not return 0, the two numbers are not divisible. The program will keep re-prompting the user to enter in a correct choice until a correct result is obtained.

``` Is It Divisible? C++ #include <iostream> using namespace std; int main() { // declare variables int base=0; int userInput=0; double multiple =0; // get first number cout <<"Please enter a value: "; cin >> base; // get second number cout << "nPlease enter a factor of "<<base<<": "; cin >> userInput; do{ // loop will keep going until the user enters a correct answer // this is the modulus declaration, which will find the // remainder between the 2 numbers multiple = base % userInput; // if the modulus result returns 0, the 2 numbers // are divisible if (multiple == 0) { cout <<"nCorrect! " << base << " is divisible by " << userInput <<endl; cout <<"n("<< base << "/" << userInput <<") = "<<(base/userInput)<<endl; } // if the user entered an incorrect choice, promt an error message else { cout << "nIncorrect, " << base <<" is not divisible by " << userInput <<".nPlease enter a new multiple integer for that value: "; cin >> userInput; } }while(multiple != 0); // ^ loop stops once user enters correct choice return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445 #include <iostream>using namespace std; int main(){ // declare variables int base=0; int userInput=0; double multiple =0;  // get first number cout <<"Please enter a value: "; cin >> base```