Tag Archives: if/else
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Feb 11, 2012 //    Taken From: http://programmingnotes.org/ //    File:  bubbleSort.cpp //    Description: Demonstrates how to sort an array using bubble sort // ============================================================================ #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;     cin.get();     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:
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 ======
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Feb 11, 2012 //    Taken From: http://programmingnotes.org/ //    File:  selectionSort.cpp //    Description: Demonstrates how to sort an array using selection sort // ============================================================================ #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;     cin.get();     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 < arraySize; ++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:
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 ======
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Feb 11, 2012 //    Taken From: http://programmingnotes.org/ //    File:  insertionSort.cpp //    Description: Demonstrates how to sort an array using insertion sort // ============================================================================ #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;     cin.get();     return 0; }// end of main void InsertionSort(int arry[], int arraySize) {     int previousIndex = 0;     int currentValue = 0;     // iterate through entire list     for (int index = 1; index < arraySize; ++index)     {         currentValue = arry[index];         previousIndex = index - 1;         while (previousIndex >= 0 && arry[previousIndex] > currentValue)         {             arry[previousIndex + 1] = arry[previousIndex];             previousIndex = previousIndex - 1;         }// end while loop         arry[previousIndex + 1] = currentValue;     }// end for loop }// http://programmingnotes.org/  | 
					
SAMPLE OUTPUT:
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.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Feb 11, 2012 //    Taken From: http://programmingnotes.org/ //    File:  quickSort.cpp //    Description: Demonstrates how to sort an array using quick sort // ============================================================================ #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); void QuickSort(int arry[], int start, int end); int Partition(int arry[], int start, int end); 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;     cin.get();     return 0; }// end of main // the initial function call and initiates the sort void QuickSort(int arry[], int arraySize) {     QuickSort(arry, 0, arraySize - 1); }// end of QuickSort // recursive call that carries out the sort void QuickSort(int arry[], int start, int end) {     if (start < end)     {         // partition the arry and get the new pivot position         int newPiviotIndex = Partition(arry, start, end);         // quick sort the first part         QuickSort(arry, start, newPiviotIndex);         // quick sort the second part         QuickSort(arry, newPiviotIndex + 1, end);     } }// end of QuickSort int Partition(int arry[], int start, int end) {     // choose a random pivot     int pivotIndex = start + rand() % (end - start + 1);     std::swap(arry[end], arry[pivotIndex]); // swap pivot with last element     int left = start; // left index     int right = end; // right index     // compare and select smallest from the subarray     for (int index = start; index <= right; ++index)     {         if (arry[index] < arry[right])         {             std::swap(arry[index], arry[left]);             ++left;         }     }     // move pivot to its final place     std::swap(arry[right], arry[left]);     return left; // return the position of the new pivot }// http://programmingnotes.org/  | 
					
SAMPLE OUTPUT:
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.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Feb 11, 2012 //    Taken From: http://programmingnotes.org/ //    File:  mergeSort.cpp //    Description: Demonstrates how to sort an array using merge sort // ============================================================================ #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 arraySize); void MergeSort(int arry[], int start, int end); void Merge(int arry[], int start, int midPt, int end); 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, NUM_INTS);     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;     cin.get();     return 0; }// end of main // the initial function call and initiates the sort void MergeSort(int arry[], int arraySize) {     MergeSort(arry, 0, arraySize - 1); }// end of MergeSort // recursive call that carries out the sort 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, end);     } }// end of MergeSort // sorts the sub array void Merge(int arry[], int start, int midPt, int end) {     int leftFirst = start;     int leftLast = midPt;     int rightFirst = midPt + 1;     int rightLast = end;     int* tempArray = new int[rightLast + 1];     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];     }     delete[] tempArray; }// http://programmingnotes.org/  | 
					
SAMPLE OUTPUT:
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 Store 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:
| 
					 1 2 3 4 5 6 7 8 9  | 
						                                My Programming Notes Record Company                                     Sales Report for 2/9/2012 Artist        Title   SalesPrice        Genre        DiscountRate     SubTotal      SalesTax   GrandTotal Name1            CD1        12.99        Jazz         18.00%          10.65            1.26      11.91 Name2            CD2        12.99        Rap           7.00%          12.08            1.26      13.34 -------------------------------------------------------------------------------------------------------- Total (2 transactions)                                                  22.73           2.52    25.25  | 
					
NOTE: On some compilers, you may have to add #include < cstdlib> and #include < cstring> in order for the code to compile.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406  | 
						// ============================================================================= // 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/  | 
					
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 optionE - 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 optionE - 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 optionE - 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 optionE - 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 optionE - 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 optionE - 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 optionE - 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 optionE - 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
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  | 
						                                My Programming Notes Record Company                                     Sales Report for 2/9/2012 Artist        Title   SalesPrice        Genre        DiscountRate     SubTotal      SalesTax   GrandTotal Nm1            CD1        12.99            Rap         7.00%          12.08            1.27        13.35 Nm2            CD2        10.99  International        11.00%           9.78            1.02        10.80 Nm3            CD3        11.45      Classical         9.00%          10.42            0.89        11.31 Nm4            CD4        12.99          Other         0.00%          12.99            1.22        14.21 Nm5            CD5        12.24           Jazz        18.00%          10.04            0.55        10.59 Nm6            CD6        11.50            Pop         0.00%          11.50            0.77        12.27 Nm7            CD7        10.99        Country         3.00%          10.66            0.86        11.52 Nm8            CD8        12.99           Rock        10.00%          11.69            1.27        12.96 -------------------------------------------------------------------------------------------------------- Total (8 transactions)                                                  89.16           7.85    97.01  | 
					
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.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  | 
						#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/  | 
					
The above program determines if number ‘A’ is divisible be number ‘B’ via modulus. Unlike the division operator, which does not return the remainder of a number, the modulus operator does, thus we are able to find divisibility between two numbers.
To demonstrate the above code, here is a sample run:
Please enter a value: 21
Please enter a factor of 21: 5Incorrect, 21 is not divisible by 5.
Please enter a new multiple integer for that value: 7Correct! 21 is divisible by 7
(21/7) = 3
===== CELSIUS TO FAHRENHEIT CONVERSION =====
Now that we understand how modulus works, the second program shouldn’t be too difficult. This function first prompts  the user to enter in an initial (low) value. After the program obtains the low value from the user, the program will ask for another (high) value. After it obtains the needed information, it displays all the degrees, from the range of the low number to the high number, which are divisible by 10. So if the user enters a low value of 3 and a high value of 303, the program will display all of the Celsius to Fahrenheit degrees within that range which are divisible by 10.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58  | 
						#include <iostream> using namespace std; // function prototype double ConvertCelsiusToFahrenheit(int degree); int main() { 	// declare variables 	int low=0; 	int high=0; 	double degreeFahrenhiet =0; 	double multiple =0; 	// get data from user 	cout << "Enter a low number: "; 	cin >> low; 	cout << "nEnter a high number: "; 	cin >> high; 	// displays data back to user in table form 	cout <<"nCelsius Fahrenheit:n"; 	cout << low << "t" << ConvertCelsiusToFahrenheit(low)<<endl; 	++low; 	// this loop displays all the degrees that are divisible by 10 	do{  		// this converts the current number from celsius to fahrenhiet 		degreeFahrenhiet = ConvertCelsiusToFahrenheit(low); 		// this is the modulus operation which finds the  		// numbers which are divisible by 10 		multiple = low % 10;		 		// the program will only display the degrees to the user via 		// cout which are divisible by 10 		if(multiple ==0) 		{ 			cout << low << "t" << degreeFahrenhiet<<endl; 		} 		// this increments the current degree number by 1 		++low; 	}while(low < high); 	// ^ loop stops once the 'low' variable reaches the 'high' variable 	// displays the 'high' converted degrees to the user 	cout << high << "t" << ConvertCelsiusToFahrenheit(high)<<endl; 	return 0; }// end of main // function declaration which returns the converted celsius to fahrenhiet value double ConvertCelsiusToFahrenheit(int degree) { 	return ((1.8 * degree) + 32.0); }// http://programmingnotes.org/  | 
					
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Enter a low number: 3
Enter a high number: 303Celsius Fahrenheit:
3..........37.4
10.........50
20.........68
30.........86
40........104
50........122
60........140
70........158
80........176
90........194
100.......212
110.......230
120.......248
130.......266
140.......284
150.......302
160.......320
170.......338
180.......356
190.......374
200.......392
210.......410
220.......428
230.......446
240.......464
250.......482
260.......500
270.......518
280.......536
290.......554
300.......572
303.......577.4
C++ || Input/Output – Using An Array, Sort Names From a Text File & Save The Sorted Names To A New Text File
            
            Since we previously discussed how to sort numbers which is contained in an integer array, it is only fitting that we display a program which sorts characters that are stored in a character array.
This is an interactive program which first displays a menu to the user, allowing them to choose from 6 different modes of operation. The 6 options are described as followed:
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit
From the available choices, the user has the option of reading in names from a file, manually entering in names themselves, displaying the current names in the array, sorting the current names in the array, clearing the current names in the array, and finally quitting the program. When the user chooses to quit the program, whatever data which is currently stored within the array will automatically be saved to the output text file.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Fstream
Ifstream
Ofstream
Character Arrays
2D Arrays
Working With Files
Pass By Reference
While Loops
For Loops
Bubble Sort
Functions
Switch Statements
Boolean Expressions
Toupper
Strcpy
Strcmp
The data file that is used in this example can be downloaded here.
Note: 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]
NOTE: On some compilers, you may have to add #include < cstdlib> and #include < cstring> in order for the code to compile.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250  | 
						#include <iostream> #include <fstream> #include <iomanip> using namespace std; // const variable indicating how many names the array can hold const int TOTALNAMES = 100; // function prototypes void DisplayMenu(); int ReadInData(char names[][50], ifstream &infile); void GetUserData(char names[][50], int numberOfNames); void ClearArray(char names[][50], int numberOfNames); void SortArray(char names[][50], int numNames); void DisplayArray(char names[][50], int numNames); void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile); int main() { 	// declare variables 	ifstream infile; 	ofstream outfile;      char names[TOTALNAMES][50]; 	char userResponse = 'Q';      int numberOfNames = 0; 	// display menu to user 	DisplayMenu(); 	cin >> userResponse; 	// keep looping thru the menu until the user 	// selects Q (Quit) 	while(toupper(userResponse)!='Q') 	{ 		// switch statement indicating the available choices 		// the user has to make 		switch(toupper(userResponse)) 		{ 		case 'R':  			numberOfNames = ReadInData(names, infile); 			break; 		case 'E':  			cout << "nPlease enter the number of names you want to sort: "; 			cin >> numberOfNames; 			GetUserData(names,numberOfNames); 			break; 		case 'D':  			DisplayArray(names, numberOfNames); 			break; 		case 'C':  			ClearArray(names,numberOfNames); 			numberOfNames=0; 			break; 		case 'S':  			SortArray(names, numberOfNames); 			break; 		case 'Q': 			break; 		default: cout << "nThe selected option is not apart of the list!nPlease try again.."; 			break; 		} 		// creates a line seperator after each task is executed 		cout<<endl; 		cout.fill('-');           cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;  		// re-display's the menu to the user 		DisplayMenu(); 		cin >> userResponse; 	} 	// after the user is finished manipulating the  	// data, save the names to the output file 	SaveArrayToFile(names, numberOfNames, outfile);     return 0; }// end of main // ============================================================================ // displays options to user void DisplayMenu() { 	cout<<"   Welcome to the name sorting program..."; 	cout<<"nFrom the following menu, select an option"; 	cout<<"nR - Read in names from a file for sorting"; 	cout<<"nE - Enter in names manually for sorting"; 	cout<<"nD - Display the current names in the array"; 	cout<<"nS - Sort the current names in the array"; 	cout<<"nC - Clear the current names in the array"; 	cout<<"nQ - Quitn";      cout<<"n>> "; }// end of DisplayMenu // ============================================================================ // reads in data from a file int ReadInData(char names[][50], ifstream &infile) { 	int numberOfNames=0; 	// open input file 	infile.open("INPUT_UNSORTED_NAMES_programmingnotes_freeweq_com.txt"); 	if(infile.fail()) 	{ 		cout<<"Input file could not be found!n" 			<<"Please place the input file in the correct directory.."; 		return 0; 	} 	else 	{ 		cout << "nReading in data from the file..."; 		while(infile.good()) 		{ 			infile >> names[numberOfNames]; 			++numberOfNames; 		} 		cout << "nSuccess!"; 	} 	infile.close(); // close the infile once we are done using it 	return numberOfNames; }// end of ReadInData // ============================================================================ // gets data from user (names) for direct input void GetUserData(char names[][50], int numberOfNames) {     cout << "nPlease enter "<<numberOfNames<<" names" << endl; 	for(int index=0; index < numberOfNames; ++index) 	{ 		cout<<"nName #"<<index+1<<": "; 		cin >> names[index];     } }// end of GetUserData // ============================================================================ // clears the data contained in the array void ClearArray(char names[][50], int numNames) { 	if(numNames==0) 	{ 		cout<<"nThe array is currently empty!n"; 	} 	else 	{ 		cout<<"nDeleting the data contained in the array..."; 		for(int index=0; index < numNames; ++index) 		{ 			strcpy(names[index],""); 		} 		cout << "nClearing Complete!"; 	} }// end of ClearArray // ============================================================================ // sorts the array via 'bubble sort' void SortArray(char names[][50],int numNames) { 	bool sorted = false; 	char temp[50]; 	if(numNames==0) 	{ 		cout<<"nThe array is currently empty!n"; 	} 	else 	{ 		cout << "nSorting the names contained in the array..."; 		// this is the 'bubble sort' and will execute only 		// if there is more than 1 name contained within the array 		// If there is only one name contained in the array,  		// there is no need to sort anything 		while((sorted == false) && (numNames > 1)) 		{ 			sorted = true; 			for (int index=0; index < numNames-1; ++index) 			{ 				if (strcmp(names[index], names[index+1]) > 0) 				{ 					strcpy(temp,names[index]); 					strcpy(names[index], names[index+1]); 					strcpy(names[index+1], temp); 					sorted = false; 				} 			} 		} 		cout << "nSuccess!"; 	} }// end of SortArray // ============================================================================ // saves the current data which is in the arrya to the output file void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile) { 	// open output file 	outfile.open("OUTPUT_SORTED_NAMES_programmingnotes_freeweq_com.txt"); 	if(outfile.fail()) 	{ 		cout<<"Error creating output file!"; 		return; 	} 	else 	{ 		if(numberOfNames==0) 		{ 			cout<<"nThe array contained no names.nThere was no data to save to the output file...n"; 			outfile<<"The array contained no names.nThere was no data to save to the output file...n"; 		} 		else 		{ 			cout<<"nSaving the current contents of the array to the ouptut file.."; 			outfile<<"Sorted items which were contained within the array..n"; 			for(int index=0; index < numberOfNames; ++index) 			{ 				outfile <<"Name #"<<index+1<<": " 					<< names[index]<<endl; 			} 			cout << "nSuccess!n"; 		} 	} 	outfile.close(); }// end of SaveArrayToFile // ============================================================================ // displays the current contents of the array to the user // via cout void DisplayArray(char names[][50], int numNames) { 	if(numNames==0) 	{ 		cout<<"nThe array is currently empty!n"; 	} 	else 	{ 		cout << "nThe values in the array are:n"; 		for (int index=0; index < numNames; ++index) 		{ 			cout << names[index] << endl; 		} 		cout<<"nThere is currently "<<numNames<<" names in the array!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
(Remember to include the input file)
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The array is currently empty!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
The array contained no names.
There was no data to save to the output file...------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> e
Please enter the number of names you want to sort: 3
Please enter 3 names
Name #1: My
Name #2: Programming
Name #3: Notes------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
NotesThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Notes
ProgrammingThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> c
Deleting the data contained in the array...
Clearing Complete!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> r
Reading in data from the file...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
Notes
C++
Java
Assembly
Lemon
Dark
Light
Black
High
Low
Cellphone
Cat
Dog
Penguin
Japan
Peace
Love
Color
White
One
Brain
Eggplant
Phalanx
Countenance
Crayons
Ben
Dover
Eileen
Bob
Downe
Justin
Elizebeth
Rick
Rolled
Sam
Widge
Liza
Destruction
Grove
Aardvark
Primal
Sushi
Victoria
Ostrich
Zebra
Scrumptious
Carbohydrate
Sulk
Ecstatic
Acrobat
Pneumonoultramicroscopicsilicovolcanoconiosis
English
Kenneth
Jessica
Pills
Pencil
Dragon
Mint
Chocolate
Temperature
Cheese
Rondo
Silicon
Scabbiest
Palpitate
Invariable
Henpecked
Titmouse
Canoodle
Boobies
Pressure
Density
Cards
Twiat
Tony
Pink
Green
Yellow
Duck
Dodge
Movie
Zoo
Xiomara
Eggs
Marshmallows
Umbrella
Apple
Panda
Brush
Handle
Door
Knob
Mask
Knife
Speaker
Wood
Orient
LoveThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
Aardvark
Acrobat
Apple
Assembly
Ben
Black
Bob
Boobies
Brain
Brush
C++
Canoodle
Carbohydrate
Cards
Cat
Cellphone
Cheese
Chocolate
Color
Countenance
Crayons
Dark
Density
Destruction
Dodge
Dog
Door
Dover
Downe
Dragon
Duck
Ecstatic
Eggplant
Eggs
Eileen
Elizebeth
English
Green
Grove
Handle
Henpecked
High
Invariable
Japan
Java
Jessica
Justin
Kenneth
Knife
Knob
Lemon
Light
Liza
Love
Love
Low
Marshmallows
Mask
Mint
Movie
My
Notes
One
Orient
Ostrich
Palpitate
Panda
Peace
Pencil
Penguin
Phalanx
Pills
Pink
Pneumonoultramicroscopicsilicovolcanoconiosis
Pressure
Primal
Programming
Rick
Rolled
Rondo
Sam
Scabbiest
Scrumptious
Silicon
Speaker
Sulk
Sushi
Temperature
Titmouse
Tony
Twiat
Umbrella
Victoria
White
Widge
Wood
Xiomara
Yellow
Zebra
ZooThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
Saving the current contents of the array to the ouptut file..
Success!
C++ || Random Number Guessing Game Using Srand, Rand, & Do/While Loop
            
            This is a simple guessing game, which demonstrates the use of srand and rand to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will then check to see if the user inputted number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Jan 20, 2012 //    Taken From: http://programmingnotes.org/ //    File:  guessingGame.cpp //    Description: Demonstrates a simple random number guessing game // ============================================================================ #include <iostream> #include <ctime> #include <iomanip> using namespace std; int main()  { 	// declare & initialize variables 	char playAgain = 'y'; 	int userInput = 0; 	int numGuesses = 0; 	// Seed the random number generator with the current time so      // the numbers will be different every time the program runs 	srand(time(NULL)); 	int randomNumber = rand() % 1000+1; 	// display directions to user 	cout << "I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.\n\n"; 	do{ // this is the start of the do/while loop 		// get data from user 		cin >> userInput; 		// increments the 'numGuesses' variable each time the user  		// gets the guess wrong 		++numGuesses; 		// if user guess is too high, do this code 		if(userInput > randomNumber)  		{ 			cout << "Too high! Think lower.\n"; 		} 		// if user guess is too low, do this code 		else if(userInput < randomNumber)  		{ 			cout << "Too low! Think higher.\n"; 		} 		// if user guess is correct, do this code 		else  		{    // display data to user, prompt if user wants to play again 			cout << "You got it, and it only took you " << numGuesses  				        <<" trys!\nWould you like to play again (y/n)? "; 			cin >> playAgain; 			// if user wants to play again then re initialize the variables  			if(playAgain == 'y'|| playAgain =='Y')  			{ 				// creates a line seperator if user wants to enter new data 				cout<<endl; 				cout.fill('-'); 				cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; 				numGuesses = 0; 				cout << "\n\nMake a guess (between 1-1000):\n\n"; 				// generate a new random number for the user to try & guess 				randomNumber = rand() % 1000+1; 			} 		} 	}while(playAgain =='y' || playAgain =='Y');      // ^ do/while loop ends when user doesnt select 'Y'  	// display data to user 	cout<<"\n\nThanks for playing!!"<<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:
I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.67
Too low! Think higher.
500
Too low! Think higher.
700
Too high! Think lower.
600
Too low! Think higher.
680
Too high! Think lower.
650
Too low! Think higher.
660
Too low! Think higher.
670
You got it, and it only took you 8 trys!
Would you like to play again (y/n)? y------------------------------------------------------------
Make a guess (between 1-1000):
500
Too low! Think higher.
600
Too low! Think higher.
700
Too low! Think higher.
900
Too high! Think lower.
800
Too high! Think lower.
760
Too high! Think lower.
740
Too high! Think lower.
720
Too high! Think lower.
700
Too low! Think higher.
710
Too high! Think lower.
705
Too high! Think lower.
701
Too low! Think higher.
702
Too low! Think higher.
703
Too low! Think higher.
704
You got it, and it only took you 15 trys!
Would you like to play again (y/n)? nThanks for playing!!
C++ || Struct – Add One Day To Today’s Date Using A Struct
            
            This program displays more practice using the structure data type, and is very similar to another program which was previously discussed here.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Passing a Value By Reference
Integer Arrays
Structures
Constant Variables
Boolean Expressions
This program utilizes a struct, which is very similar to the class concept. This program first prompts the user to enter the current date in mm/dd/yyyy format. Upon obtaining the date from the user, the program then uses a struct implementation to simply add one day to the date which was entered by the user. If the day that was entered into the program by the user falls on the end of the month, the program will”roll over” the incremented date into the next month. If the user enters 12/31/2012, the program will “roll over” the incremented date into the next calendar year.
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106  | 
						#include <iostream>  using namespace std; // struct declaration struct Date { 	int month; 	int day; 	int year; }; // constants which do not change // specifies the max values for each variable const int MAX_DAYS = 31; const int MAX_MONTHS = 12;  // function prototypes bool IsDateValid(Date dateVal); void CalcNextDay(Date &dateVal); int main() { 	// initialize the structure: month, day, year 	Date dateVal = {1,18,2012}; 	char backSlash = '/'; // this is a 'placeholder' variable 	// obtain information from user 	cout << "Please enter today's date in mm/dd/yyyy format: "; 	cin >> dateVal.month >> backSlash >> dateVal.day >> backSlash >> dateVal.year; 	// Checks to see if user entered valid data 	if (IsDateValid(dateVal) == false) 	{ 		cout << "Invalid input...nProgram exiting...." << endl; 		exit(EXIT_FAILURE); 	}  	// function declaration which calculates the next day 	CalcNextDay(dateVal); 	// display updated data to user 	cout << "The next day is " << dateVal.month << "/" << dateVal.day << "/" << dateVal.year <<endl;  	return 0; }// end of main 	// this function checks to see if the user inputted valid data bool IsDateValid(Date dateVal) {      // checks to see if user inputted data falls between the specified      // const variables as declared above      if ((dateVal.day >= 1 && dateVal.day <= MAX_DAYS)           &&(dateVal.month >= 1 && dateVal.month <= MAX_MONTHS))      {           return true;      }      else      {           return false;      } }// end of IsDateValid  	// this calculates the next day & updates values via reference void CalcNextDay(Date &dateVal) { 	// int array which holds the max date each month has 	// from January to December 	int maxDays[12]={31,28,31,30,31,30,31,31,30,31,30,31}; 	// bool which lets the program know if the month the 	// user entered is a max month for the specific month 	// the user inputted 	bool maxDay = false; 	// checks to see if user inputted day is a max date from the  	// above array for the currently selected month which  	// was entered by the user 	if(dateVal.day == maxDays[dateVal.month-1]) 	{ 		dateVal.day = 1; 		++dateVal.month; 		maxDay = true; 	} 	// checks to see if user inputted a valid date 	// for the currently selected month 	else if (dateVal.day > maxDays[dateVal.month-1]) 	{ 		cout << "Invalid day input - There is no such date for the selected month.nProgram exiting...." << endl; 		exit(EXIT_FAILURE); 	}  	// if user didnt enter a max date, and the date is valid, increment the day 	else 	{ 		++dateVal.day; 	} 	// if the date is 12/31/yyyy 	// increment to the next year 	if ((dateVal.month > 12)  && maxDay == true) 	{ 		dateVal.month = 1; 		++dateVal.year; 	} }// 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 6 separate times to display the different outputs its able to produce
Please enter today's date in mm/dd/yyyy format: 1/18/2012
The next day is 1/19/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 7/31/2012
The next day is 8/1/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 2/28/2012
The next day is 3/1/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 13/5/2012
Invalid input...
Program exiting....
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 2/31/2012
Invalid day input - There is no such date for the selected month.
Program exiting....
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 12/31/2012
The next day is 1/1/2013
C++ || Find The Day Of The Week You Were Born Using Functions, String, Modulus, If/Else, & Switch
            
            
This program displays more practice using functions, modulus, if and switch statements.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Strings
Modulus
If/Else Statements
Switch Statements
Knowledge of Leap Years
A Calendar
This program prompts the user for their name, date of birth (month, day, year), and then displays information back to them via cout. Once the program obtains selected information from the user, it will use simple math to determine the day of the week in which the user was born, and determine the day of the week their current birthday will be for the current calendar year. The program will also display to the user their current age, along with re-displaying their name back to them.
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233  | 
						#include <iostream> #include <string> using namespace std; // a const variable containing the current year const int CURRENT_YEAR = 2012; // function prototypes string GetNameOfMonth(int numOfMonth); int GetLastTwoDigits(int fourDigitYear); string GetDayOfWeek(int numOfMonth, int lastTwoDigits, int numOfDay, int fourDigitYear); int main () { 	// declare variables 	string nameOfMonth = " ", dayOfWeek = " ", userName = " ", dayOfWeekCurrentYear = " " ; 	int numOfMonth=0, numOfDay=0, fourDigitYear=0, lastTwoDigits=0, lastTwoDigitsCurrentYear; 	// user inputs data 	cout << "Please enter your name: "; 	cin >> userName; 	cout << "nPlease enter the month in which you were born (between 1 and 12): "; 	cin >> numOfMonth; 	// converts the number the user inputted from above ^  	// into a literal month name (i.e month #1 = January) 	nameOfMonth = GetNameOfMonth(numOfMonth); 	// user inputs data 	cout << "nPlease enter the day you were born (between 1 and 31): "; 	cin >> numOfDay; 	// checks to see if user entered valid data  	if (numOfDay < 1 || numOfDay > 31) 	{ 		cout << "nYou have entered an invalid number of day. " 			<< "Please enter a valid number." << endl << endl; 		exit(1); 	} 	// user inputs data 	cout << "nPlease enter the year you were born (between 1900 and 2099): "; 	cin >>  fourDigitYear; 	cout << endl << endl; 	// checks to see if user entered valid data  	if (fourDigitYear < 1900 || fourDigitYear > 2099) 	{ 		cout << "You have entered an invalid year. " 			<< "Please enter a valid year." << endl << endl; 		exit(1); 	} 	// gets the las two digits in which the user was born 	// (i.e 1999: last two digits = 99) 	lastTwoDigits = GetLastTwoDigits(fourDigitYear); 	// gets the las two digits of the current year 	// (i.e 2012: last two digits = 12) 	lastTwoDigitsCurrentYear = GetLastTwoDigits(CURRENT_YEAR); 	// finds the day of the week in which the user was born 	dayOfWeek = GetDayOfWeek(numOfMonth, lastTwoDigits, numOfDay, fourDigitYear); 	// finds the day of the week the users current birthday will be this year 	dayOfWeekCurrentYear = GetDayOfWeek(numOfMonth, lastTwoDigitsCurrentYear, numOfDay, CURRENT_YEAR); 	// display data to user 	cout << "Hello " << userName <<". Here are some facts about you!" <<endl; 	cout << "You were born "<< nameOfMonth << numOfDay << " "<< fourDigitYear << endl; 	cout << "Your birth took place on a " << dayOfWeek << endl; 	cout << "This year your birthday will take place on a " << dayOfWeekCurrentYear << endl; 	cout << "You currently are, or will be " << (CURRENT_YEAR - fourDigitYear) << " years old this year!"<<endl; 	return 0; }// end of main 	// converts the number the user inputted from above ^  	// into a literal month name (i.e month #1 = January) string GetNameOfMonth(int numOfMonth) { 	string nameOfMonth = " "; 	// a switch determining what month the user was born 	switch(numOfMonth) 	{ 	case 1: 			nameOfMonth = "January "; 			break; 	case 2: 			nameOfMonth = "February "; 			break; 	case 3: 			nameOfMonth = "March "; 			break; 	case 4: 			nameOfMonth = "April "; 			break; 	case 5: 			nameOfMonth = "May "; 			break; 	case 6: 			nameOfMonth = "June "; 			break; 	case 7:  			nameOfMonth = "July "; 			break; 	case 8: 			nameOfMonth = "August "; 			break; 	case 9: 			nameOfMonth = "September "; 			break; 	case 10: 			nameOfMonth = "October "; 			break; 	case 11: 			nameOfMonth = "November "; 			break; 	case 12: 			nameOfMonth = "December "; 			break; 	default: 			cout << "You have entered an invalid number of month. nPlease enter a valid number.n" 				<< "Program Terminating.."; 			exit(1); 			break; 	}// end of switch 	return nameOfMonth ; }// end of GetNamOfMonth 	// gets the las two digits in which the user was born/current year int GetLastTwoDigits(int fourDigitYear) { 	if (fourDigitYear >= 1900 && fourDigitYear <= 1999) 	{  		return (fourDigitYear - 1900); 	} 	else 	{ 		return (fourDigitYear - 2000); 	} }// end of GetLastTwoDigits 	// finds the day of the week in which the user was born/current year string GetDayOfWeek(int numOfMonth, int lastTwoDigits, int numOfDay, int fourDigitYear) { 	string dayOfWeek = " "; 	int Total = 0, valueOfMonth = 0; 	if (numOfMonth == 1)                 valueOfMonth = 1; 	else if (numOfMonth == 2)                 valueOfMonth = 4; 	else if (numOfMonth == 3)                 valueOfMonth = 4; 	else if (numOfMonth == 4)                 valueOfMonth = 0; 	else if (numOfMonth == 5)                 valueOfMonth = 2; 	else if (numOfMonth == 6)                 valueOfMonth = 5; 	else if (numOfMonth == 7)                 valueOfMonth = 0; 	else if (numOfMonth == 8)                 valueOfMonth = 3; 	else if (numOfMonth == 9)                 valueOfMonth = 6; 	else if (numOfMonth == 10)                 valueOfMonth = 1; 	else if (numOfMonth == 11)                 valueOfMonth = 4; 	else if (numOfMonth == 12)                 valueOfMonth = 6; 	else 		cout <<"nError"; 	Total = lastTwoDigits / 4; 	Total += lastTwoDigits; 	Total += numOfDay; 	Total += valueOfMonth; 	// uses the 'Total' variable from above to determine the day  	// of the week in which you were born 	if ((fourDigitYear > 2000)&&((numOfMonth != 1)&&(numOfMonth != 2))&&(fourDigitYear != 2004)) 	{  		Total = Total + 6; 	} 	else  if ((fourDigitYear < 2000) && ((numOfMonth == 1) || (numOfMonth == 2))) 	{  		Total = Total + 7; 	} 	else if ((fourDigitYear == 2000) && ((numOfMonth == 1) || (numOfMonth == 2))) 	{ 		Total = Total -2; 	} 	else if ((fourDigitYear == 2004||fourDigitYear == 2000)&&((numOfMonth != 1)&&(numOfMonth != 2))) 	{ 		Total = Total -1; 	} 	else if ((fourDigitYear % 4 == 0) && (fourDigitYear % 100 == lastTwoDigits) && (fourDigitYear % 400 == lastTwoDigits)) 	{ 		Total = Total-2; 	} 	else if ((fourDigitYear > 2000)&&((numOfMonth == 1)||(numOfMonth == 2))&&(fourDigitYear != 2004)) 	{ 		Total = Total + 6; 	} 	// uses the 'Total' variable from above to determine the day  	// of the week in which you were born/when you birthday will be this year 	if (Total % 7 == 1)                 dayOfWeek = "Sunday"; 	else if (Total % 7 == 2)                 dayOfWeek = "Monday"; 	else if (Total % 7 == 3)                 dayOfWeek = "Tuesday"; 	else  if (Total % 7 == 4)                 dayOfWeek = "Wednesday"; 	else if (Total % 7 == 5)                 dayOfWeek = "Thursday"; 	else if (Total % 7 == 6)                 dayOfWeek = "Friday"; 	else if (Total % 7 == 0)                 dayOfWeek = "Saturday"; 	else 		cout<< "nError"; 	return dayOfWeek; }// http://programmingnotes.org/  | 
					
QUICK NOTES:
The highlighted lines are sections of interest to look out for. 
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
Note: The code was compiled five separate times to display the different outputs its able to produce
Please enter your name: MyProgrammingNotes
Please enter the month in which you were born (between 1 and 12): 1
Please enter the day you were born (between 1 and 31): 1
Please enter the year you were born (between 1900 and 2099): 2012Hello MyProgrammingNotes. Here are some facts about you!
You were born January 1 2012
Your birth took place on a Sunday
This year your birthday will take place on a Sunday
You currently are, or will be 0 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 4
Please enter the day you were born (between 1 and 31): 2
Please enter the year you were born (between 1900 and 2099): 1957Hello Name. Here are some facts about you!
You were born April 2 1957
Your birth took place on a Tuesday
This year your birthday will take place on a Monday
You currently are, or will be 55 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 5
Please enter the day you were born (between 1 and 31): 7
Please enter the year you were born (between 1900 and 2099): 1999Hello Name. Here are some facts about you!
You were born May 7 1999
Your birth took place on a Friday
This year your birthday will take place on a Monday
You currently are, or will be 13 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 8
Please enter the day you were born (between 1 and 31): 4
Please enter the year you were born (between 1900 and 2099): 1983Hello Name. Here are some facts about you!
You were born August 4 1983
Your birth took place on a Thursday
This year your birthday will take place on a Saturday
You currently are, or will be 29 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 6
Please enter the day you were born (between 1 and 31): 7
Please enter the year you were born (between 1900 and 2099): 2987You have entered an invalid year. Please enter a valid year.
Press any key to continue . . .
C++ || Display Today’s Date Using a Switch
            
            If statements, char’s and strings have been previously discussed, and this page will be more of the same. This program will demonstrate how to use a switch to display today’s date, converting from mm/dd/yyyy format to formal format (i.e January 5th, 2012).
This same program can easily be done using if statements, but sometimes that is not always the fastest programming method. Switch statements are like literal light switches because the code “goes down a line” to check to see which case is valid or not, just like if statements. You will see why switches are very effective when used right by examining this program.
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
====== TODAY’S DATE USING A SWITCH ========
So to start our program out, lets define the variables.
| 
					 1 2 3 4 5 6 7 8 9 10  | 
						#include <iostream> using namespace std; int main() { 	// Declare Variables 	int	month; 	int	day; 	int	year; 	char	backSlash; }  | 
					
Notice on line 9 there is a variable named “backslah.” This program was designed to display the date in this format.
Enter today's date: 10/7/2008
October 7th, 2008
So the only way to achieve that was to add a “place holder” variable during the user input process, which is demonstrated below.
| 
					 1 2 3  | 
							// Collect Data 	cout << "Enter today's date: "; 	cin >> month >> backSlash >> day >> backSlash >> year;  | 
					
In line 3, you can see the format that the user will input the data in. They will input data in mm/dd/yyyy format, and having the “backslash” placeholder there will make that possible.
After the user enters in data, how will the program convert numbers into actual text? Next comes the switch statements.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69  | 
							// Check month 	switch(month) 	{ 	case 1: 		{ 			cout << "tJanuary "; 			break; 		} 	case 2: 		{ 			cout << "tFebruary "; 			break; 		} 	case 3: 		{ 			cout << "tMarch "; 			break; 		} 	case 4: 		{ 			cout << "tApril "; 			break; 		} 	case 5: 		{ 			cout << "May "; 			break; 		} 	case 6: 		{ 			cout << "tJune "; 			break; 		} 	case 7:  		{ 			cout << "tJuly "; 			break; 		} 	case 8: 		{ 			cout << "tAugust "; 			break; 		} 	case 9: 		{ 			cout << "tSeptember "; 			break; 		} 	case 10: 		{ 			cout << "tOctober "; 			break; 		} 	case 11: 		{ 			cout << "tNovember "; 			break; 		} 	case 12: 		{ 			cout << "tDecember "; 			break; 		} 	default: 		{ 			cout << "t" << month <<" is not a valid monthn"; 			exit(1);  // this forces the program to quit 		} 	}  | 
					
Line 2 contains the switch declaration, and its comparing the variable of “month” to the 12 different cases that is defined within the switch statement. So this piece of code will “go down the line” comparing to see if the user inputted data is any of the numbers, from 1 to 12. If the user inputted a number which does not fall between 1 thru 12, the “default” case will be executed, prompting the user that the data they inputted was invalid, which can be seen in line 64. Notice line 67 has an exit code. This program will force an exit whenever the user enters invalid data. 
Line 7 is very important, because that forces the computer to “break” away from the selected case whenever it is done examining the piece of code. It is important to add the break in there to avoid errors, which may result in the program giving you wrong output as the answer.
Next we will add another switch statement to convert the day of the month to have a number suffix (i.e displaying the number in 1st, 2nd, 3rd format). This is very similar to the previous switch statement
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  | 
							// Check Day 	switch(day) 	{ 	case 1: case 21: case 31: 		{ 			cout << day << "st, "; 			break; 		} 	case 2: case 22: 		{ 			cout << day << "nd, "; 			break; 		} 	case 3: case 23: 		{ 			cout << day << "rd, "; 			break; 		} 	default: 		{ 			cout << day << "th, "; 			break; 		} 	}  | 
					
This block of code is very similar to the previous one. Line 2 is declaring the variable ‘day’ to be compared with the base cases, line 7 and so forth has the break lines, but line 4, 9 and 14 are different. If you notice, line 4, 9 and 14 are comparing multiple cases in one line. Yes with switch statements, you can do that. Just like you can compare multiple values in if statements, the same cane be done here. So this switch is comparing the number the user inputted, with the base cases, adding a suffix to the end of the number.
So far we have obtained data from the user, compared the month and day using switch statements and displayed that to the screen. Now all we have to do is output the year to the user. This is fairly simple, because the year is not being compared, you are just simply using a cout to display data to the user.
| 
					 1 2  | 
							// Display Year 	cout << year << endl;  | 
					
Adding all the code together should give us this
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115  | 
						#include <iostream> using namespace std; int main() { 	// Declare Variables 	int		month; 	int		day; 	int		year; 	char	backSlash; 	// Collect Data 	cout << "Enter today's date: "; 	cin >> month >> backSlash >> day >> backSlash >> year; 	// Check month 	switch(month) 	{ 	case 1: 		{ 			cout << "tJanuary "; 			break; 		} 	case 2: 		{ 			cout << "tFebruary "; 			break; 		} 	case 3: 		{ 			cout << "tMarch "; 			break; 		} 	case 4: 		{ 			cout << "tApril "; 			break; 		} 	case 5: 		{ 			cout << "May "; 			break; 		} 	case 6: 		{ 			cout << "tJune "; 			break; 		} 	case 7:  		{ 			cout << "tJuly "; 			break; 		} 	case 8: 		{ 			cout << "tAugust "; 			break; 		} 	case 9: 		{ 			cout << "tSeptember "; 			break; 		} 	case 10: 		{ 			cout << "tOctober "; 			break; 		} 	case 11: 		{ 			cout << "tNovember "; 			break; 		} 	case 12: 		{ 			cout << "tDecember "; 			break; 		} 	default: 		{ 			cout << "t" << month <<" is not a valid monthn"; 			exit(1); 		} 	} 	// Check Day 	switch(day) 	{ 	case 1: case 21: case 31: 		{ 			cout << day << "st, "; 			break; 		} 	case 2: case 22: 		{ 			cout << day << "nd, "; 			break; 		} 	case 3: case 23: 		{ 			cout << day << "rd, "; 			break; 		} 	default: 		{ 			cout << day << "th, "; 			break; 		} 	} 	// Display Year 	cout << year << endl; 	// Terminate 	return 0; } // http://programmingnotes.freeweq.com  | 
					
Once compiled, you should get this as your output
Enter today's date: 1/5/2012
January 5th, 2012
C++ || Using If Statements, Char & String Variables
            
            As previously mentioned, you can use the “int/float/double” data type to store numbers. But what if you want to store letters? Char and Strings help you do that.
==== SINGLE CHAR ====
This example will demonstrate a simple program using char, which checks to see if you entered the correctly predefined letter.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Jan 4, 2012 //    Updated: Feb 8, 2021 //    Taken From: http://programmingnotes.org/ //    File:  char.cpp //    Description: Demonstrates using char variables // ============================================================================ #include <iostream> int main() {     // Declare empty variable     char userInput = ' ';     std::cout << "Please try to guess the letter I am thinking of: ";     std::cin >> userInput;     // Use an If Statement to check equality     if (userInput == 'a' || userInput == 'A')     {         std::cout <<"\nYou have Guessed correctly!"<< std::endl;     }     else     {         std::cout <<"\nSorry, that was not the correct letter I was thinking of"<< std::endl;     }     return 0; }// http://programmingnotes.org/  | 
					
Notice in line 13 I declare the char data type, naming it “userInput.” I also initialized it as an empty variable. In line 19 I used an “If/Else Statement” to determine if the user inputted value matches the predefined letter within the program. I also used the “OR” operator in line 19 to determine if the letter the user inputted was lower or uppercase. Try compiling the program simply using this
if (userInput == 'a') as your if statement, and notice the difference.
The resulting code should give this as output
Please try to guess the letter I am thinking of: K
Sorry, that was not the correct letter I was thinking of
==== CHECK IF LETTER IS UPPER CASE ====
This example is similar to the previous one, and will check if a letter is uppercase.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Jan 4, 2012 //    Updated: Feb 8, 2021 //    Taken From: http://programmingnotes.org/ //    File:  uppercase.cpp //    Description: Demonstrates checking if a char variable is uppercase // ============================================================================ #include <iostream> int main() {     // Declare empty variable     char userInput = ' ';     std::cout << "Please enter an UPPERCASE letter: ";     std::cin >> userInput;     // Checks to see if entered data falls between uppercase values     if ((userInput >= 'A') && (userInput <= 'Z'))     {         std::cout << "\n" << userInput << " is an uppercase letter"<< std::endl;     }     else     {         std::cout <<"\nSorry, "<< userInput <<" is not an uppercase letter"<< std::endl;     }     return 0; }// http://programmingnotes.org/  | 
					
Notice in line 19, an If statement was used, which checked to see if the user entered data fell between letter A and letter Z. We did that by using the “AND” operator. So that IF statement is basically saying (in plain english)
IF ('userInput' is equal to or greater than 'A') AND ('userInput' is equal to or less than 'Z')THEN it is an uppercase letter
C++ uses ASCII codes to determine letters, so from looking at the table, the letter ‘A’ would equal ASCII code number 65, letter ‘B’ would equal ASCII code number 66 and so forth, until you reach letter Z, which would equal ASCII code number 90. So in literal terms, the program is checking to see if the user input is between ASCII code number 65 thru 90. If it is, then the number is an uppercase letter, otherwise it is not.
The resulting code should give this as output
Please enter an UPPERCASE letter: G
G is an uppercase letter
==== CHECK IF LETTER IS A VOWEL ====
This example will utilize more if statements, checking to see if the user inputted data is a vowel or not. This will be very similar to the previous example, utilizing the OR operator once again.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Jan 4, 2012 //    Updated: Feb 8, 2021 //    Taken From: http://programmingnotes.org/ //    File:  vowel.cpp //    Description: Demonstrates checking if a char variable is a vowel // ============================================================================ #include <iostream> int main() {     // Declare empty variable     char userInput = ' ';     std::cout << "Please enter a vowel: ";     std::cin >> userInput;     // Checks to see if inputted data is A,E,I,O,U,Y     if ((userInput == 'a')||(userInput == 'A')||(userInput == 'e')||         (userInput == 'E')||(userInput == 'i')||(userInput == 'I')||         (userInput == 'o')||(userInput == 'O')||(userInput == 'u')||         (userInput == 'U')||(userInput == 'y')||(userInput == 'Y'))     {         std::cout <<"\nCorrect, "<< userInput <<" is a vowel!"<< std::endl;     }     else     {         std::cout <<"\nSorry, "<< userInput <<" is not a vowel"<< std::endl;     }     return 0; }// http://programmingnotes.org/  | 
					
This program should be very straight forward, and its basically checking to see if the user inputted data is the letter A, E, I, O, U or Y.
The resulting code should give the following output
Please enter a vowel: O
Correct, O is a vowel!
==== HELLO WORLD v2 ====
This last example will demonstrate using the string data type to print the line “Hello World!” to the screen.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  | 
						// ============================================================================ //    Author: Kenneth Perkins //    Date:   Jan 4, 2012 //    Updated: Feb 8, 2021 //    Taken From: http://programmingnotes.org/ //    File:  string.cpp //    Description: Demonstrates using string variables // ============================================================================ #include <iostream> #include <string> int main() {     // Declare empty variable     std::string userInput = " ";     std::cout << "Please enter a sentence: ";     std::getline(std::cin, userInput);     std::cout << "\nYou Entered: "<<userInput << std::endl;     return 0; }// http://programmingnotes.com  | 
					
Notice in line 10 we have to add “#include string” in order to use the getline function, which is used on line 17. Rather than just simply using the “cin” function, we used the getline function instead to read in data. That is because cin is unable to read entire sentences as input. So in line 17, the following code reads a line from the user input until a newline is entered.
The resulting code should give following output
Please enter a sentence: Hello World!
You Entered: Hello World!





