Tag Archives: Add
C++ || Cash Register Simulation – Display The Total Sales Amount In Dollars & Cents Using Modulus
The following is a simple program which demonstrates more use of the modulus (%) function to manipulate integer data.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
This program first prompts the user to enter in a monetary amount into the system. This number can be a decimal number, or a whole number. Once the user enters in an amount, the program will use the modulus operator to determine exactly how many 1 dollar bills, quarters, dimes, nickles, and pennies consisted of the amount that the user entered into the program. So for example, if the user entered the value of 2.34, the program would display the result of 2 dollars, 1 quarters, 0 dimes, 1 nickels, and 4 pennies.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 28, 2012 // Taken From: http://programmingnotes.org/ // File: MakeChange.cpp // Description: The following is a simple program which demonstrates // how to make change. // ============================================================================ #include<iostream> using namespace std; int main() { // declare variables double initialAmount = 0; int remainingAmount = 0; int numberOfOneDollars = 0; int numberOfQuarters = 0; int numberOfDimes = 0; int numberOfNickels = 0; int numberOfPennies = 0; // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount; // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100); // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount; // Display the results cout << "\nThe amount of $" << initialAmount << " consists of: \n" << "\t" << numberOfOneDollars << " dollar(s)\n" << "\t" << numberOfQuarters << " quarter(s)\n" << "\t" << numberOfDimes << " dime(s)\n" << "\t" << numberOfNickels << " nickel(s)\n" << "\t" << numberOfPennies << " pennie(s)\n"; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)
====== RUN 1 ======
Enter the total sales amount in dollars & cents (for example 19.87): 19.87
The amount of $19.87 consists of:
19 dollar(s)
3 quarter(s)
1 dime(s)
0 nickel(s)
2 pennie(s)====== RUN 2 ======
Enter the total sales amount in dollars & cents (for example 19.87): 11.93
The amount of $11.93 consists of:
11 dollar(s)
3 quarter(s)
1 dime(s)
1 nickel(s)
3 pennie(s)====== RUN 3 ======
Enter the total sales amount in dollars & cents (for example 19.87): 3.00
The amount of $3 consists of:
3 dollar(s)
0 quarter(s)
0 dime(s)
0 nickel(s)
0 pennie(s)
C++ || Find The Average Using an Array – Omit Highest And Lowest Scores
This page will consist of two programs which calculates the average of a specific amount of numbers using an array.
REQUIRED KNOWLEDGE FOR BOTH PROGRAMS
Float Data Type
Constant Values
Arrays
For Loops
Assignment Operators
Basic Math
====== FIND THE AVERAGE USING AN ARRAY ======
The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via cout.
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 |
#include <iostream> using namespace std; int main() { // declare variables float total = 0; int numElems = 0; float average[100]; // declare array which has the ability to hold 100 elements cout << "How many numbers do you want to find the average for?: "; cin >> numElems; // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { cout << "nEnter #" << index +1<< " : "; cin >> average[index]; total += average[index]; } // find the average. Note: // the expression below literally // means: total = total / numElems; total /= numElems; cout << "nThe average of the " << numElems << " numbers is " << total <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
ARRAY
Notice the array declaration on line #9. The type of array being used in this program is a static array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.
FOR LOOP
Notice line 17-22 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different cout statements into your code asking the user to input data. Line 21 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.
Once compiled, you should get this as your output:
How many numbers do you want to find the average for?: 5
Enter #1 : 23
Enter #2 : 17
Enter #3 : 29
Enter #4 : 14
Enter #5 : 16
The average of the 5 numbers is 19.8
====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======
The second program is really practical in a real world setting, specifically when a teacher records test scores into the computer. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via cout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.
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 |
#include <iostream> using namespace std; const int NUM_JUDGES = 6; int main() { int scores[NUM_JUDGES]; // array is initialized using a const variable int highestScore = -999999; int lowestScore = 999999; float sumOfScores = 0; float avgScores = 0; // use a for loop to obtain data from user using the const variable cout<< "Judges, enter one score each for the current competitor: "; for(int counter=0; counter < NUM_JUDGES; ++counter) { cin >> scores[counter]; } // use another for loop to redisplay the data back to the user via cout cout<<"nThese are the scores from the " << NUM_JUDGES << " judges: "; for(int index=0; index < NUM_JUDGES; ++index) { cout<<"nThe score for judge #"<<(index+1)<<" is: "<<scores[index]; } // use a for loop to go thru the array checking to see the highes/lowest element cout<<"nnThese are the highest and lowest scores: "; for(int index=0; index < NUM_JUDGES; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(scores[index] > highestScore) { highestScore = scores[index]; } // if current 'lowestScore' element is bigger than the current array element, // then set 'lowestScore' equal to the current array element if(lowestScore > scores[index]) { lowestScore = scores[index]; } } cout << "ntHighest: "<< highestScore; cout << "ntLowest: "<< lowestScore; cout << "nThe average score is: "; // this calculates a running total, adding each element in the array together for(int counter=0; counter < NUM_JUDGES; ++counter) { sumOfScores += scores[counter]; } avgScores = sumOfScores/NUM_JUDGES; cout<< avgScores; // reset data back to 0 so we dont get wrong answers sumOfScores = 0; avgScores = 0; cout<<"nThe average adjusted score omitting the highest and lowest result is: "; // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest elements for(int counter=0; counter < NUM_JUDGES; ++counter) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if ((scores[counter] != highestScore) && (scores[counter] != lowestScore)) { sumOfScores += scores[counter]; } } avgScores = sumOfScores/(NUM_JUDGES-2); cout<< avgScores <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
CONST
A constant variable was declared and used to initialize the array (line 8). Note, when using static arrays, the program has to know how many elements to initialize the program with before the program starts, so creating a constant variable to do that for us is convenient.
FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 16, 23, 30, 53, and 70. The const variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.
HIGHEST/LOWEST SCORES
This is noted on lines 34-44, and it is really simple to understand the process once you see the code.
OMITTING HIGHEST/LOWEST SCORE
Lines 70-78 highlight this process, and the loop basically traverses the array, skipping over the highest/lowest elements
Once compiled, you should get this as your output:
Judges, enter one score each for
the current competitor: 123 453 -789 2 23345 987These are the scores from the 6 judges:
The score for judge #1 is: 123
The score for judge #2 is: 453
The score for judge #3 is: -789
The score for judge #4 is: 2
The score for judge #5 is: 23345
The score for judge #6 is: 987These are the highest and lowest scores:
Highest: 23345
Lowest: -789
The average score is: 4020.17
The average adjusted score omitting the highest and lowest result is: 391.25
C++ || Struct – Add One Second To The Clock Using A Struct
Here is another actual homework assignment which was presented in an intro to programming class. This program utilizes a struct, which is very similar to the class concept. For this assignment, the class was asked to make a program which prompted the user to enter a time in HH:MM:SS (Hours:Minutes:Seconds) format. Upon obtaining the time from the user, our class was asked to use a struct implementation which was to simply add one second to the time that was entered by the user. Seems easy enough, though I initially had afew problems when starting the program.
This page will be very brief in its breakdown of the program’s code, as it is already heavily commented. The code is basically unchanged from the code which was turned in for grading.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Passing a Value By Reference
Structures
Constant Variables
Boolean Expressions
Setw
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 |
// ============================================================================ // File: AddOneSecond.cpp // ============================================================================ // Description: // This program prompts the user for the input time, then adds // one second to the time -- if any of the time structure fields need to // "rollover" (e.g., the hours, minutes or seconds need to be reset to zero), // this function will handle that. Finally, the incremented time will be // displayed to stdout. // ============================================================================ #include <iostream> #include <iomanip> using namespace std; // structure declaration struct Time { int hours; int min; int sec; }; // defined constants which do not change // specifies the max values for each variable const int MAX_HOURS = 23; const int MAX_MINS = 59; const int MAX_SECS = 59; // function prototypes bool IsTimeValid(Time timeParam); void AddOneSecond(Time &timeParam); void DisplayTime(Time timeParam); // ==== main ================================================================== // // ============================================================================ int main() { Time userTime = {0,0,0}; // Initialize struct members: hrs, min, sec to 0 char colon = ':'; cout << "Please enter the time in HH:MM:SS format: "; cin >> userTime.hours >> colon >> userTime.min >> colon >> userTime.sec; // Checks to see if user entered correct data if (IsTimeValid(userTime) == false) { cout << "Invalid input...n" << endl; exit(EXIT_FAILURE); } cout << "nThe incremented time is "; AddOneSecond(userTime); DisplayTime(userTime); return 0; } // end of main // ==== IsTimeValid =========================================================== // // This function will validate that the time structure contains legitimate // values. If this function determines that the time values are invalid, it // will display an error message to stdout. // // Input: // limit [IN] -- The users time input // // Output: // The Time structure as an argument to the AddOneSecond function // // ============================================================================ bool IsTimeValid(Time timeParam) { // checks to see if user inputted data falls between the specified // const variables as declared above if ((timeParam.hours >= 0 && timeParam.hours <= MAX_HOURS) &&(timeParam.min >= 0 && timeParam.min <= MAX_MINS) &&(timeParam.sec >= 0 && timeParam.sec <= MAX_SECS)) { return true; } else { return false; } } // end of IsTimeValid // ==== AddOneSecond ========================================================== // // This function will add one second to the time // // Input: // limit [IN] -- The users time input // // Output: // The incremented time will be displayed to stdout by calling the // DisplayTime function // // ============================================================================ void AddOneSecond(Time &timeParam) { // this is just a simple bool which checks to see if // the program should increment the max hrs in the // 1st or 2nd if statements, which are located below bool incrementHrsInFirstIf = false; // this is just a simple bool which checks to see if // the program should increment the max mins in the // 2nd or 3rd if statements, which are located below bool incrementMinInSecondIf = false; // ========== if statement #1 - hrs ========== // checks to see if user selected hrs is equal to MAX // if it is, reset time back to 0 if (timeParam.hours == MAX_HOURS && timeParam.min == MAX_MINS) { timeParam.hours = 0; incrementHrsInFirstIf = true; } // ========== if statement #2 - min ========== // checks to see if user selected mins is equal to MAX // if it is, reset time back to 0 if (timeParam.min == MAX_MINS) { timeParam.min = 0; // if mins == 59, we need to increment the hrs by 1 if(incrementHrsInFirstIf == false) { ++timeParam.hours; } incrementMinInSecondIf = true; } // ========== if statement #3 - Secs ========== // checks to see if user selected sec is equal to MAX // if it is, reset time back to 0 if (timeParam.sec == MAX_SECS) { timeParam.sec = 0; // if secs == 59, we need to increment the mins by 1 if(incrementMinInSecondIf == false) { ++timeParam.min; } } else // if time is not at max, increment by 1 { ++timeParam.sec; } } // end of AddOneSecond // ==== DisplayTime =========================================================== // // This function will display the user's time // // Input: // limit [IN] -- The users time input // // Output: // The incremented time will be displayed // // ============================================================================ void DisplayTime(Time timeParam) { cout.fill('0'); cout << setw(2) << timeParam.hours << ":" << setw(2) << timeParam.min << ":" << setw(2) << timeParam.sec << endl; } // http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
STRUCT
The structure declaration is placed above the main function, as noted on lines 16-21, containing the 3 variables (Hrs, min, sec) which are defined within the program. Line 39 displays how to access those variables from the main function, having the variable “Time userTime” as the means of access. Note, line 43, the variables can utilize cin for input.
CONST
Lines 25-27 declare the constant variables, which hold the maximum allowable time the clock is able to display. The function IsTimeValid (line 72) checks to see if user defined input is within the maximum allowable limit or not.
FILL
The program will automatically display 2 numbers for hours,mins,sec even if the user only inputted one number, as noted on lines 169-172. This is basically the same as the setfill function.
Once compiling the above code, you should receive this as your output
Note: The code was compiled five separate times to display the different outputs its able to produce
==== SAMPLE RUN #1 ====
Please enter the time in HH:MM:SS format: 0:0:25
The incremented time is 00:00:26==== SAMPLE RUN #2 ====
Please enter the time in HH:MM:SS format: 23:58:59
The incremented time is 23:59:00==== SAMPLE RUN #3 ====
Please enter the time in HH:MM:SS format: 23:59:59
The incremented time is 00:00:00==== SAMPLE RUN #4 ====
Please enter the time in HH:MM:SS format: : :
The incremented time is 00:00:01==== SAMPLE RUN #5 ====
Please enter the time in HH:MM:SS format: 76:09:67
Invalid input...