c++ programing review

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

4.7 Loops**: Removing leading/trailing whitespace Users may type or copy-paste in a text box of a web form, perhaps a name like "Joe Smith". The user sometimes has whitespace before or after the text, like " Joe Smith ". A program typically strips such leading and trailing whitespace. Given a string, create a new string that lacks any leading or trailing spaces. Given " Joe Smith ", the new string should be "Joe Smith". Be sure to handle the case of the user entering only whitespace, or entering nothing, which each should yield an empty string "". Hints: ***Initially, try to find the index of the first non-space character. Set the index to 0, then use a while loop to check each character. ***Your while loop expression should first check that the index is valid for the size of the string The size() function of a string returns an unsigned int, so declare your index variable as an unsigned int so you can compare without a compiler warning ***Next, try to find the index of the last non-space character. Use a different index variable. Your while loop expression should first check that it is greater-than-or-equal to 0 to ensure it is valid. ***Once you know the first and last non-space characters, you can use a for loop to copy those characters to the new string. ***After the first while loop, be sure to check if any non-space character was found (by checking if the index is less than the string's last element). If no non-space character was found, just return.

#include <iostream> #include <string> using namespace std; int main() { string userText; string cleanedText; // Hint: Add declarations as needed unsigned int i, j, n; getline(cin, userText); // Find first non-space character i = 0; while ((i < userText.size()) && (userText.at(i) == ' ')) { ++i; } if (i == userText.size()) { return 0; // No non-space characters, just return } // Find last non-space character j = userText.size() - 1; while ((j >= 0) && (userText.at(j) == ' ')) { --j; } // Copy just characters from i to j to new string for (n = i; n <= j; ++n) { cleanedText.push_back(userText.at(n)); } cout << cleanedText << endl;

Write an assignment statement for the following mathematical equation: y = (1/3)x + (x/4) + 2x Keep x as an integer. Use an expression that matches the equation's right side as closely as possible. If the input is -1, the output is -2.58333. Hints: Don't rearrange the equation or try to simplify it. If both operands of division (or other operators) are integers, integer division is performed, which rounds down; so for example 1/2 is 0. So make at least one operand a floating-point type, as in 1.0/2, or 1.0/2.0, to cause floating-point division.

#include <iostream> using namespace std; int main() { int x; double y; cin >> x; // Type your code here y = (1.0/3.0)*(x)+(x/4.0)+2.0*x; cout << y << endl; return 0; }

***Branches/24hr time**** 24-hour time (also known in the U.S. as military time) is widely used around the world. Time is expressed as hours since midnight. The day starts at 00:00, and ends at 23:59. Write a program that converts am/pm time to 24-hour time. The input is two numbers and a string. If the input is 2 30 pm, the output should be 14:30. If the input is 12 01 am, the output should be 00:01. Hints: ***Think of how each hour should be handled. 12 00 am -12 59 am becomes what? 8 00 am becomes what? 12 00 pm? 1 00 pm? Group the hours into cases that should be handled similarly (e.g., 1 00 am to 11 00 am are handled the same). ***Declare variables for hoursAmPm, minAmPm, and hours24. Note that minutes for 24-hour time remain the same as for am/pm, so no extra variable is needed. ***Use an if-else statement to detect each case, and set the hours24 appropriately. ***When outputting hour24, check if the hour is 0-9 (just check for < 10). If so, output a "0". So 7 will be output as 07. Do the same when outputting the minutes.

#include <iostream> using namespace std; int main() { int hourAmPm; int minAmPm; string amPm; int hour24; cin >> hourAmPm; cin >> minAmPm; cin >> amPm; if ( (hourAmPm == 12) && (amPm == "am") ) { // Special case for first hour hour24 = 0; } else if ( (amPm == "pm") && (hourAmPm != 12) ) { // Add 12 for 1 pm and higher (not for 12 pm). hour24 = hourAmPm + 12; // Ex: 2 pm becomes 14 } else { // must be 1 am to 11 am, so hour stays the same (e.g., 9 am stays 9 am hour24 = hourAmPm; } if (hour24 < 10) { // Prepend a "0", such as 02:30 cout << "0"; } cout << hour24 << ":"; if (minAmPm < 10) { // Prepend a "0", such as 12:01 cout << "0"; } cout << minAmPm << endl; return 0; } /* NOTES * Enumerating cases as above is a common skill needed by a programmer. * Formulating an if-else to detect each case is also a common skill. Note that the structure of the if-else captures each case, without using complicated expressions, because if an expression evaluates to false, the next expression can take advantage of that fact, especially in the "else" part. * The output is just text, so we could prepend 0's to the hour and minute. Trying to get those integers to output with a leading 0 would have been hard. The program could have also written to a string, and then output that string. */

4.1 Loops (for)*: Output sequence (1) Given an integer n, write a for loop that outputs the numbers from -n to +n. Assume n is nonnegative. End the sequence with a newline. Enter an integer: 2 Sequence: -2 -1 0 1 2 (2) If n is negative, treat as the absolute value. So n of -2 is the same as n of 2. Hint: Use an if statement before the for loop, to compute the absolute value of n. Enter an integer: -2 Sequence: -2 -1 0 1 2

#include <iostream> using namespace std; int main() { int n; int i; cout << "Enter an integer:" << endl; cin >> n; cout << "Sequence: "; /* Type your code here. */ if (n < 0) { n = -n; } for (i = -n; i <= n; ++i) { cout << i << " "; } cout << endl; return 0; }

4.5 Loops (nested)**: Sum a given number of integers A user will enter an initial number, followed by that number of integers. Output those integers' sum. Repeat until the initial number is 0 or negative. Ex: If the user enters 3 9 6 1 0, the output is: 16 Ex: If the user enters 3 9 6 1 2 5 3 0, the output is: 16 8 Hints: ***Use a while loop as an outer loop. Get the user's initial number of ints before the loop, and at then end of the loop body. ***Use a for loop as an inner loop, inside the while loop body. Loop from i = 0, to i < (the number of ints). ***In the for loop, first read the next integer, then update the sum. After the for loop, output the sum.

#include <iostream> using namespace std; int main() { int numInts = 0; int intsSum = 0; int userInt = 0; int i; cin >> numInts; while (numInts > 0) { intsSum = 0; for (i = 0; i < numInts; ++i) { cin >> userInt; intsSum += userInt; } cout << intsSum << endl; cin >> numInts; } return 0; } /* NOTES * Think of the outer loop separately from the inner loop. The outer loop uses "while" because the number of iterations is unknown. The inner loop uses "for" because the number of iterations is known to be numInts. * A common error is to forget to get user input at the end of the while loop's body, yielding an infinite loop */

****Branches/Complex cost structure*** An airline describes airfare as follows. A normal ticket's base cost is $300. Persons aged 60 or over have a base cost of $290. Children 2 or under have $0 base cost. A carry-on bag costs $10. A first checked bag is free, second is $25, and each additional is $50. Given inputs of age, carry-on (0 or 1), and checked bags (0 or greater), compute the total airfare. Hints: First use an if-else statements to assign airFare with the base cost Use another if statement to update airFare for a carryOn Finally, use another if-else statement to update airFare for checked bags Think carefully about what expression correctly calculates checked bag cost when bags are 3 or more

#include <iostream> using namespace std; int main() { int passengerAge; int carryOns; int checkedBags; int airFare; cin >> passengerAge; cin >> carryOns; cin >> checkedBags; if (passengerAge >= 60) { airFare = 290; // Senior } else if (passengerAge <= 2) { airFare = 0; // Lap child } else { // Regular: 2 < age < 60 airFare = 300; } if (carryOns > 0) { airFare += 10; } if (checkedBags == 2) { airFare += 25; } else if (checkedBags >= 3) { airFare += 25 + (checkedBags - 2) * 50; // 2nd bag is $25. Each bag beyond 2nd is $50 } // Note: 0 or 1 bags is $0, so no adjustment to airfare cout << airFare << endl; return 0; } /* NOTES * Notice the careful use of distinct if-else statements. Each has a particular role. * Updating a single value (airFare) is a common pattern. An alternative approach uses variables for baseCost, carryOnCost, and checkedBagCost. Each if-else assigns one of those variables. Then a final equation assigns airFare = baseCost + carryOnCost + checkedBagCost */

4.3 Loops (while)**: Output rocket height Suppose a launched toy rocket's height is computed as h = vi*t - 5t2. vi is the initial velocity, and t is time in seconds since the launch (starting at 0). Write a program to read the initial velocity, then output the time and the rocket's height once per second. Stop when the height would be negative, meaning the rocket hit the ground (don't print the negative). Assume all values are integers. Ex: For input 20, the output is: 0 0 1 15 2 20 3 15 4 0 Hints: Use a while loop t squared is easily calculated as t * t Use this expression for the while loop: (rocketHeight >= 0) Don't forget to increment time inside the while loop (else you'll get an infinite loop)

#include <iostream> using namespace std; int main() { int rocketHeight = 0; int initialVelocity = 0; int timeSinceLaunch = 0; /* Type your code here. */ cin >> initialVelocity; while (rocketHeight >= 0) { cout << timeSinceLaunch << " " << rocketHeight << endl; timeSinceLaunch = timeSinceLaunch + 1; rocketHeight = (initialVelocity * timeSinceLaunch ) - (5 * timeSinceLaunch * timeSinceLaunch); } return 0; } /* NOTES: * The number of iterations isn't known beforehand, meaning a while loop is usually more appropriate than a for loop. * The loop only executes if rocketHeight >= 0, so doesn't execute when rocketHeight becomes negative. */

***Branches/Runway headings*** Airport runways are numbered using a 2-digit number, like 09. The meaning generally is that planes taking off or landing on that runway will be facing 090 or 90 degrees rotated right from north, namely facing east. Given a runway number (integer), output the degrees followed by the closest direction indication (north, northeast, east, southeast, south, southwest, west, or northwest). If the input is 03, the output is: 30 degrees (northeast). Hints: ***First just read the input number, multiply by 10 to yield runwayDeg. ***Next, create an if-else statement to compare runwayDeg's value with ranges for each direction. For north, the value should be within -22.5 and +22.5. For northeast, the value should be between 45 - 22.5 and 45 + 22.5. And so on. ***Based on the range in which the value falls, update a string variable with the direction. Then after the if-else, have a single output statement that outputs "270 degrees (north)" or whatever value and direction are correct. ***Don't forget that ranges use &&. An expression detecting a value x is between 1 and 10 is (x > 1) && (x < 10). ***Because the input is an integer which is multiplied by 10 to yield runwayDeg, the comparisons with floating-point values like 22.5 will never result in equality. Hence, the ranges don't have to account for such quality.

#include <iostream> using namespace std; int main() { int runwayNum; int runwayDeg; string runwayDirection; cin >> runwayNum; runwayDeg = runwayNum * 10; // Determine closest direction. Ranges are heading +/- 22.5. if ((runwayDeg > 0 - 22.5) && (runwayDeg < 0 + 22.5)) { runwayDirection = "north"; } else if ((runwayDeg > 45 - 22.5) && (runwayDeg < 45 + 22.5)) { runwayDirection = "northeast"; } else if ((runwayDeg > 90 - 22.5) && (runwayDeg < 90 + 22.5)) { runwayDirection = "east"; } else if ((runwayDeg > 135 - 22.5) && (runwayDeg < 135 + 22.5)) { runwayDirection = "southeast"; } else if ((runwayDeg > 180 - 22.5) && (runwayDeg < 180 + 22.5)) { runwayDirection = "south"; } else if ((runwayDeg > 225 - 22.5) && (runwayDeg < 225 + 22.5)) { runwayDirection = "southwest"; } else if ((runwayDeg > 270 - 22.5) && (runwayDeg < 270 + 22.5)) { runwayDirection = "west"; } else if ((runwayDeg > 315 - 22.5) && (runwayDeg < 315 + 22.5)) { runwayDirection = "northwest"; } cout << runwayDeg << " degrees (" << runwayDirection << ")" << endl; return 0; } /* NOTES: * Breaking a problem into sub-problems is common. Here, the first problem is converting the two-digit number to degrees (by multiplying by 10) and outputing that item. The second is determining the direction, done using the if-else. * Detecting if a value is in a range is common. The pattern is (x > 1) && (x < 10) to detect a value between 1 and 10. * The program leaves the - 22.5 and + 22.5 to be clear, rather than doing the calculation. * Having one output statement at the end is cleaner than having output statements on every branch. Better to update a string in each branch, and then output that string at the end. * The comparisons of the integer and floating-point value is allowed. Note that integer runwayDegrees will never equal any of the range values, which always end with 0.5. */

4.6 Loops**: Output integer's digits Given an input positive integer, output each digit on its own line, starting with the rightmost digit. Ex: If the input is 935, the output is: 5 3 9 Hints: ***Use the mod operator (%) to get the rightmost digit. ***Mod by 10 to get the rightmost digit. ***Use a loop that keeps a current dividend (the number being divided). In each iteration, output the rightmost digit, then update the divisor by dividing by 10. ***End the loop when the divisor is 0.

#include <iostream> using namespace std; int main() { int userInt; int divisor; cin >> userInt; divisor = userInt; while (divisor != 0) { cout << divisor % 10 << endl; // Outputs righmost digit divisor = divisor / 10; // Shifts the integer right by one digit } return 0; } /* NOTES * Using % 10 is a common way to get the rightmost digit's value. Ex: 532 % 10 is 2 (the quotient is 53, remainder 2). * Using / 10 is a common way to shift a decimal value to the right by one digit. Ex: 532 / 10 is 53. Note that integer division drops any fractional part, so the result is 53, not 53.2. */

***Branches/ Next date**** Many websites let users make reservations (hotel, car, flights, etc.). When a user selects a date, the next day is often automatically selected (for hotel checkout, car return, flight return, etc.). Given a date in the form of three integers, output the next date. If the input is 1 15 2017, the output should be 1 16 2017. If the input is 8 31 2017, the output should be 9 1 2017. Ignore leap years. Hints: Group the months based on number of days. Then create an if-else statement for each case. Note that 12 (December) is a special case; after the last day, the next month is 1 (January) and is the next year.

#include <iostream> using namespace std; int main() { int userMonth; int userDay; int userYear; int nextMonth; int nextDay; int nextYear; cin >> userMonth; cin >> userDay; cin >> userYear; // Days per month // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec // 1 2 3 4 5 6 7 8 9 10 11 12 // 31 28 31 30 31 30 31 31 30 31 30 31 if ((userMonth == 12) && (userDay == 31)) { // Last day of year nextMonth = 1; nextDay = 1; nextYear = userYear + 1; } else if ( ( (userMonth == 1) || (userMonth == 3) || (userMonth == 5) || (userMonth == 7) || (userMonth == 8) || (userMonth == 10) ) && (userDay == 31) ) { nextMonth = userMonth + 1; nextDay = 1; nextYear = userYear; } else if ( ( (userMonth == 4) || (userMonth == 6) || (userMonth == 9) || (userMonth == 11) ) && (userDay == 30) ) { nextMonth = userMonth + 1; nextDay = 1; nextYear = userYear; } else if ( (userMonth == 2) && (userDay == 28) ) { nextMonth = userMonth + 1; nextDay = 1; nextYear = userYear; } else { // Normal case, just increment day nextMonth = userMonth; nextDay = userDay + 1; nextYear = userYear; } cout << nextMonth << " " << nextDay << " " << nextYear << endl; return 0; }

4.4 Loops (while)**: Compute modified average Compute the average of a list of user-entered integers representing rolls of two dice. The list ends when 0 is entered. Integers must be in the range 2 to 12 (inclusive); integers outside the range don't contribute to the average. Output the average, and the number of valid and invalid integers (excluding the ending 0). If only 0 is entered, output 0. The output may be a floating-point value. Ex: If the user enters 8 12 13 0, the output is: Average: 10 Valid: 2 Invalid: 1 Hints: ***Use a while loop with expression (userInt != 0) ***Read the user's input into userInt before the loop, and also at the end of the loop body ***In the loop body, use an if-else to distinguish integers in the range and integers outside the range ***For integers in the range, keep track of the sum, and number of integers. For integers outside the range, just keep track of the number. ***Use a static cast to get a floating-point output: (static_cast (sum)) / num ***Whenever dividing, be sure to handle the case of the denominator being 0.

#include <iostream> using namespace std; int main() { int validSum = 0; int validNum = 0; int invalidNum = 0; int userInt = 0; double averageNum = 0.0; cin >> userInt; while (userInt != 0) { if ((userInt >= 2) && (userInt <= 12)) { // Valid validSum += userInt; validNum += 1; } else if (userInt != 0) { // Invalid invalidNum += 1; } else { // 0: Done // Do nothing. Looping will end. } cin >> userInt; } if (validNum > 0) { // Avoid dividing by 0 averageNum = (static_cast <double> (validSum)) / validNum; } cout << "Average: " << averageNum << endl; cout << "Valid: " << validNum << endl; cout << "Invalid: " << invalidNum << endl; return 0; } /* NOTES: * Getting input before a while loop and at the end of a loop is a common pattern when the number of input values is unknown * A while loop is usually preferred when the number of iterations is not known beforehand * A common error is to forget to get the next input, yielding an infinite loop * A common error is to do: static_cast <double> (validSum / validNum), because the integer division will be done first. Ex: (10 / 4) will yield 2, not 2.5 * Division by 0 is undefined, yielding a runtime error. Thus, an if statement checks if validNum > 0. */

***Branches/Listing names*** A university has a web page that displays the instructors for a course, using the following algorithm: If only one instructor exists, the instructor's first initial and last name are listed. If two instructors exist, only their last names are listed, separated by /. If three exist, only the first two are listed, with "/ ..." following the second. If none exist, print "TBD". Given six words representing three first and last names (each name a single word; latter names may be "none none"), output one line of text listing the instructors' names using the algorithm. If the input is "Ann Jones none none none none", the output is "A. Jones". If the input is "Ann Jones Mike Smith Lee Nguyen" then the output is "Jones / Smith / ...". Hints: Use an if-else statement with four branches. The first detects the situation of no instructors. The second one instructor. Etc. Detect whether an instructor exists by checking if the first name is "none". LAB

#include <iostream> using namespace std; int main() { string firstName1, lastName1; string firstName2, lastName2; string firstName3, lastName3; // Get instructors' names cin >> firstName1; cin >> lastName1; cin >> firstName2; cin >> lastName2; cin >> firstName3; cin >> lastName3; // Output names. Detect each possible case (1 name, 2 names, 3 names), handling each differently if (firstName1 == "none") { // No names exist cout << "TBD" << endl; } else if (firstName2 == "none") { // 1 name exists. Output first initial and last name. cout << firstName1.at(0) << ". " << lastName1 << endl; } else if (firstName3 == "none") { // 2 names exist. Output last names separated by / cout << lastName1 << " / " << lastName2 << endl; } else { // 3 names exist. Output first two last names followed by / ... cout << lastName1 << " / " << lastName2 << " / ..." << endl; } return 0; } /* NOTES * Enumerating different cases using an if-else, and handling each one independently, is a common pattern. * Some students might try to combine the 2 name and 3 name cases. That's not unreasonable, but keeping the cases separate yields clean structured code that is easy to understand. */

***Branches/Caption punctuation*** A user is asked to type a caption for a photo in a web form's text field. If the caption didn't end with a punctuation mark (. ! ?), a period should automatically be added. A common error is to end with a comma, which should be replaced by a period. Another common error is to end with two periods, which should be changed to one period (however, ending with three periods (or more) indicates elipses so should be kept as is). The corrected caption is output. If the input is "I like pie", the output is "I like pie." If the input is "I like pie!", the output remains "I like pie!" If the input is "Coming soon...", the output remains "Coming soon..." Hints: Start by checking for ! or ? which don't require any action Then check for , which requires the simple action of replacing by a period. Then check for two ending periods (making sure the caption is at least 2 characters long). If found, check for three ending periods (making sure caption is at least 3 characters long), in which case no action required. Otherwise, remove the last period. Use pop_back() to remove the last period

#include <iostream> using namespace std; int main() { string userCaption; int lastIndex; char lastChar; getline(cin, userCaption); lastIndex = userCaption.size() - 1; lastChar = userCaption.at(lastIndex); if ((lastChar == '!') || (lastChar == '?')) { // Caption OK; do nothing } else if (lastChar == ',') { userCaption.at(lastIndex) = '.'; // Replace ending , (common mistake) by . } else if (lastChar != '.') { // Not ! ? , . so append . userCaption.push_back('.'); } else if ((lastIndex > 0) && (lastChar == '.') && (userCaption.at(lastIndex - 1) == '.')) { // Two periods // Three periods? if ((lastIndex > 1) && (userCaption.at(lastIndex - 2) == '.')) { // Caption OK (ends with elipses ... Do nothing } else { // Ends with two periods; remove one userCaption.pop_back(); } } cout << userCaption << endl; return 0; } /* NOTES * Careful arrangement of the if-else simplifies the coding. * When accessing string elements, always make sure the element exists. Hence the checks for lastIndex > 0 and > 1. * This kind of form entry correction is common. * lastChar and lastIndex variables aren't necessary but make the code more readable. */

***Branches/Guitar tabs*** A guitar has 6 strings that play the notes E (lowest), A, D, G, B, and e (highest). A guitar's neck has regions called frets. A musical chord like a "G" or "C" is a combination of notes, and can be played by pressing certain strings at certain frets and then strumming all 6 strings. To quickly learn to play chords, people share "tabs" -- visual indications of what strings to press. To enable easy sharing over the internet, tabs are usually shared as text files. Write a program that takes a string input representing one of three chords (G, C, D) and outputs the corresponding tab. If the input is G, the output is: e|-3- B|-0- G|-0- D|-0- A|-2- E|-3- 0 means to strum the string open (without pressing). 1 means to press the string at the first fret, 2 at the second fret, 3 at the third fret. If the input is C, the output is: e|-0- B|-1- G|-0- D|-2- A|-3- E|--- The - on the E string below the numbers means to not strum that string for that chord. If the input is D, the output is: e|-2- B|-3- G|-2- D|-0- A|--- E|--- If the user enters an unrecognized chord like Am, the output should be: Am is not a supported chord. For more info, see [https://www.ultimate-guitar.com/lessons/forbeginners/howtoreadtabs.html](How to read tabs). (The above three chords, G C D, is the sequence of chords in the classic song "Sweet Home Alabama". Hints: Use an if-else that outputs the appropriate text per chord input Using \n for newlines may make creating the output statements simpler, using a single output string per chord. In fact, you can copy-paste the above output examples between " ", then delete the new lines and spaces and replacing with \n. Use an ending "else" branch to output the error message.

#include <iostream> using namespace std; int main() { string userChord; // Currently supported: G, C, D. Future chord may involve multiple characters, like Am. cin >> userChord; if (userChord == "G") { cout << "e|-3-\nB|-0-\nG|-0-\nD|-0-\nA|-2-\nE|-3-" << endl; /* e|-3- B|-0- G|-0- D|-0- A|-2- E|-3- */ } else if (userChord == "C") { cout << "e|-0-\nB|-1-\nG|-0-\nD|-2-\nA|-3-\nE|---" << endl; /* e|-0- B|-1- G|-0- D|-2- A|-3- E|--- */ } else if (userChord == "D") { cout << "e|-2-\nB|-3-\nG|-2-\nD|-0-\nA|---\nE|---" << endl; /* e|-2- B|-3- G|-2- D|-0- A|--- E|--- */ } else { cout << userChord << " is not a supported chord." << endl; } return 0; } /* NOTES * The comments showing the desired chord help guide the current and future programmer to create a correct output. * \n is used rather than endl to keep the cout more compact, but endl could be used instead * The program outputs nothing if anything is entered other than a recognized chord. * Having an ending "else" to catch unsupported values is a common pattern. * userChord was declared as string rather than char to support future chords like Am (A minor). */

****Branches/shape display**** A user inputs the name of a shape (square or triangle). The program outputs the shape using asterisks. For input square, the output is: *** * * *** If the input is triangle, the output is: * * * *****

#include <iostream> using namespace std; int main() { string userShape; cin >> userShape; if (userShape == "square") { cout << "***" << endl; cout << "* *" << endl; cout << "***" << endl; } else if (userShape == "triangle") { cout << " *" << endl; cout << " * *" << endl; cout << "*****" << endl; } return 0; }

4.2 Loops (for)*: Output evens (1) Given positive integer n, write a for loop that outputs the even numbers from n down to 0. If n is odd, start with the next lower even number. Hint: Use an if statement and the % operator to detect if n is odd, decrementing n if so. Enter an integer: 7 Sequence: 6 4 2 0 (2) If n is negative, output 0. Hint: Use an if statement to check if n is negative. If so, just set n = 0. Enter an integer: -1 Sequence: 0

#include <iostream> using namespace std; int main() { int n; // MAKE userNum int i; cout << "Enter an integer:" << endl; cin >> n; cout << "Sequence: "; /* Type your code here. */ if (n < 0) { n = 0; } if ((n % 2) == 1) { // Odd n = n - 1; } for (i = n; i >= 0; i = i - 2) { cout << i << " "; } cout << endl; return 0; }

HTML is the language of web pages. Items start and end with tags. A table starts with <table> and ends with </table>. In a table, a row starts with <tr> and ends with </tr>. In a row, a column starts with <td> and ends with </td>. Given two integers for rows and columns, generate an appropriately sized html table. Place the character c in each table cell. If the input is 2 3, the output is: <table> <tr> <td> c </td> <td> c </td> <td> c </td> </tr> <tr> <td> c </td> <td> c </td> <td> c </td> </tr> </table>

#include <iostream> using namespace std; int main() { int userRows; int userCols; int i; int j; cin >> userRows; cin >> userCols; cout << "<table>" << endl; for (i = 0; i < userRows; ++i) { cout << "<tr> "; for (j = 0; j < userCols; ++j) { cout << "<td> c </td> "; } cout << "<tr>" << endl; } cout << "</table>" << endl; return 0; }

Map/GPS applications commonly compute the distance between two points. A point may be a coordinate on an x-y plane like (1.5, 2.0). The distance formula is d = √((x2 - x1)2 + (y2-y1)2) (basically, Pythagorean's Theorem). Given two points, output the distance between them. If the input is (1.5, 2.0) (4.5, 6.0), the output is 5. Hints: Read in the parentheses and commas as in cin >> c to skip over them, and read in the numbers as doubles. Add #include <math.h> and then use the sqrt() function. For squaring, you might use the pow() function with a second parameter of 2.

#include <iostream> #include <math.h> using namespace std; int main() { /* Type your code here. */ char skip; double x1; double x2; double y1; double y2; double d; cin >> skip; cin>>x1; cin >> skip; cin>>y1; cin >> skip; cin >> skip; cin>>x2; cin >> skip; cin>>y2; cin >> skip; d= sqrt((pow(x2-x1,2))+(pow(y2-y1,2))); cout << d<<endl; return 0; }

4.8 Loops*: Password requirements Websites commonly require a password that satisfies several requirements. Write a program that checks if an input string satisfies the following (error message is shown for each): At least 8 characters (Too short) At least one letter (Missing letter) At least one number (Missing number) At least one of these special characters: !, #, % (Missing special) Output OK, or all related error messages (in above order). If the input string is "Hello", the output is: Too short Missing number Missing special Hints: ***Declare a boolean variable for each requirement. ***Use a for loop to visit each character, setting the corresponding boolean to true if satisfied (length is done differently though). ***Use functions in the cctype library (must include the library first) to detect if a character is a letter or a number.

#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string userText; unsigned int i; char c; // Improves code readability in expressions below bool lengthOK = false; bool hasLetter = false; bool hasNumber = false; bool hasSpecial = false; cin >> userText; if (userText.size() >= 8) { lengthOK = true; } for (i = 0; i < userText.size(); ++i) { c = userText.at(i); if (isalpha(c)) { // At least one letter found hasLetter = true; } else if (isdigit(c)) { // At least one number found hasNumber = true; } else if ( (c == '!') || (c == '#') || (c == '%') ) { hasSpecial = true; } } if (lengthOK && hasLetter && hasNumber && hasSpecial) { // All requirements met cout << "OK" << endl; } else { if (!lengthOK) { cout << "Too short" << endl; } if (!hasLetter) { cout << "Missing letter" << endl; } if (!hasNumber) { cout << "Missing number" << endl; } if (!hasSpecial) { cout << "Missing special" << endl; } } return 0; } /* NOTES * Using boolean variables makes the code a lot easier to read than some other approaches. * A common mistake is to set each boolean as hasLetter = isalpha(c). That statement will keep changing hasLetter's value based on each character, with the final value being for the last character. Instead, only one letter must exist, so once true, this value should never be set back to false. The if statement accomplishes that. * The ending if-else checks if all requirements are met (outputting OK if so). If not all met, then the else part has a nested series of if statements, in order to print every failed requirement. A common mistake is to use a nested if-else, which would only print one failed requirement. * Inside the for loop, an if-else was used because a character can only be one of those things. But a series of if statements would have worked as well (for the same reason; only one could have a true expression). * Be careful to use && and not &, and || and not |. (& and | are for bitwise and/or, not logical and/or). * Don't do this: if (lengthOK == false). When using boolean variables, good practice in logical expressions is to just list the boolean variable, either in true (lengthOK) or complemented (!lengthOK) form. The expressions are more concise and easier to comprehend. * The character c was introduced to make the expressions concise and easy-to-read. Normally variables should have meaningful names (and some say at least two words as well, like userText). Exceptions include loop indices like i, coordinates like x and y, and in this case a single character in a string like c. */

***Branches/Next license plate number*** A state's Department of Motor Vehicles needs a program to generate license plate numbers. A license plate number consists of three letters followed by three digits, as in CBJ523. (So "number" is a bit inaccurate, but that's the standard word used for license plates). The plate numbers are given out in sequence, so given the current number, the program should output the next number. If the input is CBJ523, the output should be CBJ524. If the input is CBJ999, the output should be CBK000. For the last number ZZZ999, the next is AAA000. Hints: Treat each character individually. Initially, don't try to create an "elegant" solution. Just consider each of the six places one at a time, starting from the right. For each place, if less than the max for that place ('9' for digits, 'Z' for letters), just increment that place. (Note that you can just type c = c + 1 to get the next higher character for a digit like '5' or for a letter like 'K'). If a place is at the max, set it with the '0' or 'A', and then set a boolean variable to true to indicate a "carry" is needed. (If a carry isn't needed, set to false). With the above process, you'll have 6 separate if-else statements.

#include <iostream> #include <string> using namespace std; int main() { string plateNumber, nextPlateNumber; char c1, c2, c3; // The three letters char i1, i2, i3; // The three digits int threeNum, nextThreeNum; // The current and next three numbers at the end of the plate number. bool carryNeeded; cin >> plateNumber; c1 = plateNumber.at(0); c2 = plateNumber.at(1); c3 = plateNumber.at(2); i1 = plateNumber.at(3); i2 = plateNumber.at(4); i3 = plateNumber.at(5); // Check each place starting from the right. If less than max, just increment it. // If at max, set to start val, set carry true // Place 6 if (i3 < '9') { i3 += 1; carryNeeded = false; } else { i3 = '0'; carryNeeded = true; } // Place 5 if (carryNeeded) { if (i2 < '9') { i2 += 1; carryNeeded = false; } else { i2 = '0'; carryNeeded = true; } } // Place 4 if (carryNeeded) { if (i1 < '9') { i1 += 1; carryNeeded = false; } else { i1 = '0'; carryNeeded = true; } } // Place 3 if (carryNeeded) { if (c3 < 'Z') { c3 += 1; carryNeeded = false; } else { c3 = 'A'; carryNeeded = true; } } // Place 2 if (carryNeeded) { if (c2 < 'Z') { c2 += 1; carryNeeded = false; } else { c2 = 'A'; carryNeeded = true; } } // Place 1 if (carryNeeded) { if (c1 < 'Z') { c1 += 1; carryNeeded = false; } else { c1 = 'A'; carryNeeded = true; } } cout << c1 << c2 << c3 << i1 << i2 << i3 << endl; return 0; } /* NOTES * Hard problems can often be solved just by handling one item at a time. Here, we handled one place at a time. A more elegant solution is certainly possible, involving perhaps a function for each place, or even better using a loop. But here, there are only 6 places, so a "brute force" solution is reasonable, at least for the first version of a program. One can later rewrite it to be more elegant. * You almost certainly copy-pasted. When doing so, GREAT CARE must be taken to fully modify the pasted code as needed. Copy-paste is useful, but is also a common source of errors, so programmers should be extremely cautious after pasting code, meticulously modifying the code, and then double-checking the code to ensure all needed changes were made. * A common error is to forget to assign carryNeeded with false if an increment is done. * Some beginning programmers might try to create a nested if-else structure, but such nesting is really not necessary. The multiple if-else statements, in conjunction with the boolean for carries, works well. */


Kaugnay na mga set ng pag-aaral

DHO Chapter 7:1 Basic Structure of the Human Body - 7:2 Body Planes, Directions, and Cavities.

View Set

Fundamentals of Management: Chapter 14

View Set

Chapter 5 - Gross Income and Exclusions

View Set

11th Grade Louise Erdrich Short Story Links

View Set

Elements and Compounds - Unit 3 - Review Sheet

View Set