MPL Chapter 3 - CSC 121
NOTE: in mathematics, the square root of a negative number is not real; in C++ therefore, passing such a value to the square root function is an error. Given a double variable named areaOfSquare write the necessary code to read in a value, the area of some square, into areaOfSquare and print out the length of the side of that square. HOWEVER: if any value read in is not valid input, just print the message "INVALID".
cin >> areaOfSquare; if (areaOfSquare < 0) { cout << "INVALID"; } else { cout << sqrt(areaOfSquare); }
NOTE: in mathematics, division by zero is undefined. So, in C++, division by zero is always an error. Given a int variable named callsReceived and another int variable named operatorsOnCall write the necessary code to read values into callsReceived and operatorsOnCall and print out the number of calls received per operator (integer division with truncation will do). HOWEVER: if any value read in is not valid input, just print the message "INVALID".
cin >> callsReceived; cin >> operatorsOnCall; if ((operatorsOnCall>0) && (callsReceived >= 0)) { cout << (callsReceived/operatorsOnCall); }else { cout << "INVALID"; }
Assume that an int variable age has been declared and already given a value and assume that a char variable choice has been declared as well. Assume further that the user has just been presented with the following menu: S: hangar steak, red potatoes, asparagus T: whole trout, long rice, brussel sprouts B: cheddar cheeseburger, steak fries, cole slaw (Yes, this menu really IS a menu!) Write some code that reads a single character (S or T or B) into choice. Then the code prints out a recommended accompanying drink as follows: If the value of age is 21 or lower, the recommendation is "vegetable juice" for steak, "cranberry juice" for trout, and "soda" for the burger. Otherwise, the recommendations are "cabernet", "chardonnay", and "IPA" for steak, trout, and burger respectively. Regardless of the value of age, your code should print "invalid menu selection" if the character read into choice was not S or T or B.
cin >> choice; cin >> age; if(choice == 'S') { if(age <=21) cout << "vegetable juice"; else cout << "cabernet"; }else if(choice == 'T') { if(age <=21) cout << "cranberry juice"; else cout << "chardonnay"; }else if(choice == 'B') { if(age <= 21) cout << "soda"; else cout << "IPA"; }else cout << "invalid menu selection";
Given a int variable named yesCount and another int variable named noCount and a char variable named response, write the necessary code to read a value into response and then carry out the following: if the character typed in is a y or a Y then increment yesCount and print out "YES WAS RECORDED" if the character typed in is an n or an N then increment noCount and print out "NO WAS RECORDED" If the input is invalid just print the message "INVALID" and do nothing else.
cin >> response; if ((response == 'y') || (response == 'Y')) { yesCount == 0; yesCount++; cout << "YES WAS RECORDED"; } else if ((response == 'n') || (response == 'N')) { noCount == 0; noCount++; cout << "NO WAS RECORDED"; } else { cout << "INVALID"; }
You need to write a loop that will keep reading and adding integers to a sum, until the sum reaches or exceeds 21. The numbers are all less than 20 and the sum is initially 0. Which is the preferred loop construct to use?
do while loop
Write a loop that displays all possible combinations of two letters where the letters are 'a', or 'b', or 'c', or 'd', or 'e'. The combinations should be displayed in ascending alphabetical order:aaabacadaebabb...ee
for (char outerChar='a'; outerChar<='e'; outerChar++) { for (char innerChar='a'; innerChar<='e'; innerChar++) { cout << outerChar << innerChar << "\n"; } }
Given an char variable last that has been initialized to a lowercase letter, write a loop that displays all possible combinations of two letters in the range 'a' through last. The combinations should be displayed in ascending alphabetical order:For example, if last was initialized to 'c' the output should be aaabacbabbbccacbcc
for (char outterChar='a'; outterChar <=last; outterChar++) { for (char innerChar='a'; innerChar <=last; innerChar++) { cout << outterChar << innerChar << "\n"; } }
Assume the int variables i and result, have been declared but not initialized. Write a for loop header -- i.e. something of the form for ( . . . ) for the following loop body: result = result * i; When the loop terminates, result should hold the product of the odd numbers between 10 and 20. NOTE: just write the for loop header; do not write the loop body itself.
for (i = 11, result = 1; i < 20; i += 2)
Assume that the int variables i, j and n have been declared, and n has been initialized. Write code that causes a "triangle" of asterisks to be output to the screen, i.e., n lines should be printed out, the first consisting of a single asterisk, the second consisting of two asterisks, the third consisting of three, etc. The last line should consist of n asterisks. Thus, for example, if n has value 3, the output of your code should be (scroll down if necessary): ******
for (i=1; i<=n; i++) { for (j=1; j<=i; j++) cout << "*"; cout << "\n"; }
Assume that the int variables i, j and n have been declared, and n has been initialized. Write code that causes a "triangle" of asterisks to be output to the screen, i.e., n lines should be printed out, the first consisting of a single asterisk, the second consisting of two asterisks, the third consisting of three, etc. The last line should consist of n asterisks. Thus, for example, if n has value 3, the output of your code should be (scroll down if necessary): ******
for (i=1; i<=n; i++){ for (j=1; j<=i; j++) cout << "*"; cout << "\n"; }
Assume the int variables i, lo, hi, and result have been declared and that lo and hi have been initialized. Write a for loop that adds the integers between lo and hi (inclusive), and stores the result in result. Your code should not change the values of lo and hi. Also, do not declare any additional variables -- use only i, lo, hi, and result.
for (i=lo; i<=hi; i++){ result += i; }
Write a for loop that prints the odd integers 11 through 121 inclusive, separated by spaces.
for (int i=11; i<=121; i++){ if ((i%2)!=0){ cout << i << " "; } }
Write a for loop that prints in ascending order all the positive multiples of 5 that are less than 175, separated by spaces.
for (int i=1; i<175; i++) { if ((i % 5) == 0){ cout << i << " "; } }
Write a for loop that prints, in ascending order, all the positive integers less than 200 that are divisible by both 2 and 3, separated by spaces.
for (int i=1; i<200; i++){ if ((i%2)==0 && (i%3)==0){ cout << i << " "; } }
You have a variable, n, with a non-negative value, and need to write a loop that will keep print n blank lines. What loop construct should you use?
for loop
You need to write a loop that will repeat exactly 125 times. Which is the preferred loop construct to use?
for loop
Given an int variable count that has already been declared, write a for loop that prints the integers 50 through 1, separated by spaces. Use no variables other than count.
for(count = 50; count >= 1; count--) { cout << count << " "; }
Given an int variable i that has already been declared, write a for loop that prints the integers 0 through 39, separated by spaces. Use no variables other than i.
for(i = 0; i <= 39; i++) { cout << i << " "; }
Write a for loop that prints all the even integers from 80 through 20 inclusive, separated by spaces.
for(int i = 80; i >= 20; i--) { if((i%2) == 0) { cout << i << " "; } }
Write a for loop that computes the following sum: 5+10+15+20+...+485+490+495+500. The sum should be placed in a variable sum that has already been declared and initialized to 0. In addition, there is another variable, num that has also been declared. You must not use any other variables.
for(int num=1; num<=500; num++){ if ((num % 5)==0) { sum+=num; }}
Given an int variable n that has already been declared and initialized to a positive value, and another int variable j that has already been declared, use a for loop to print a single line consisting of n asterisks. Thus if n contains 5, five asterisks will be printed. Use no variables other than n and j.
for(j=0;j<n; j++) { cout << "*"; }
Given an int variable k that has already been declared, use a for loop to print a single line consisting of 97 asterisks. Use no variables other than k.
for(k = 1; k <= 97; k++) { cout << "*"; }
Write an if/else statement that adds 1 to the variable minors if the variable age is less than 18, adds 1 to the variable adults if age is 18 through 64, and adds 1 to the variable seniors if age is 65 or older.
if (age < 18) { minors++; }else if(age >= 18 && age <= 64) { adults++; }else if(age >= 65) { seniors++; }
Write a statement that increments (adds 1 to) one and only one of these five variables: reverseDrivers parkedDrivers slowDrivers safeDrivers speeders. The variable speed determines which of the five is incremented as follows: The statement increments reverseDrivers if speed is less than 0, increments parkedDrivers if speed is less than 1, increments slowDrivers if speed is less than 40, increments safeDrivers if speed is less than or equal to 65, and otherwise increments speeders.
if (speed < 0) { reverseDrivers++; }else if(speed < 1) { parkedDrivers++; }else if(speed < 40) { slowDrivers++; }else if(speed <=65) { safeDrivers++; }else { speeders++; }
Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002 as well all vehicles in its Guzzler line from model years 2004-2007. Given an int variable modelYear and a string modelName write a statement that prints the message "RECALL" to standard output if the values of modelYear and modelName match the recall details.
if(((modelYear >= 1999 && modelYear <=2002) && (modelName == "Extravagant")) || ((modelYear >= 2004 && modelYear <= 2007) && (modelName == "Guzzler"))) { cout << "RECALL"; }
Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002. Given an int variable modelYear and a string modelName write a statement that prints the message "RECALL" to standard output if the values of modelYear and modelName match the recall details.
if((modelYear >= 1999 && modelYear <= 2002) && (modelName == "Extravagant")) { cout << "RECALL"; }
Online Book Merchants offers premium customers 1 free book with every purchase of 5 or more books and offers 2 free books with every purchase of 8 or more books. It offers regular customers 1 free book with every purchase of 7 or more books, and offers 2 free books with every purchase of 12 or more books. Write a statement that assigns freeBooks the appropriate value based on the values of the bool variable isPremiumCustomer and the int variable nbooksPurchased.
if(nbooksPurchased > 4){ if(isPremiumCustomer){ freeBooks = 1; if(nbooksPurchased > 7){ freeBooks = 2; } }else{ freeBooks = 0; if(nbooksPurchased > 6){ freeBooks = 1; } if(nbooksPurchased > 11){ freeBooks = 2; } } }else{freeBooks = 0;}
Write an if/else statement that compares the double variable pH with 7.0 and makes the following assignments to the bool variables neutral, base, and acid: false, false, true if pH is less than 7 false, true, false if pH is greater than 7 true, false, false if pH is equal to 7
if(pH < 7.0) { neutral = false; base = false; acid = true; }else if(pH > 7.0) { neutral = false; base = true; acid = false; }else if(pH == 7.00) { neutral = true; base = false; acid = false; }
Write a statement that compares the values of score1 and score2 and takes the following actions. When score1 exceeds score2, the message "player1 wins" is printed to standard out. When score2 exceeds score1, the message "player2 wins" is printed to standard out. In each case, the variables player1Wins,, player1Losses, player2Wins, and player2Losses,, are incremented when appropriate. Finally, in the event of a tie, the message "tie" is printed and the variable tieCount is incremented.
if(score1 > score2) { cout << "player1 wins"; player1Wins++; player2Losses++; }else if(score2 > score1) { cout << "player2 wins"; player1Losses++; player2Wins++; }else if( score1 == score2) { cout << "tie"; tieCount++; }
Write a statement that terminates the current loop when the value of the int variables x. and y.are equal
if(x == y){ break; }
Assume the input data is structured as follows: first there is a non-negative integer specifying the number of employee timesheets to be read in. This is followed by data for each of the employees. The first number for each employee is an integer that specifies their pay per hour in cents. Following this are 5 integers, the number of hours they worked on each of the days of the workweek. Given this data, and given that an int variable total has been declared, write a loop and any necessary code that reads the data and stores the total payroll of all employees in total. Note that you will have to add up the numbers worked by each employee and multiply that by that particular employee's pay rate to get the employee's pay for the week-- and sum those values into total.
int employees; int a,b; int wage=0; int hours=0; total=0; cin >> employees; for (a=1; a<=employees; a++) { cin >> wage; for (b=1; b<=5; b++) { cin >> hours; total += hours * wage; } }
Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a CONSECUTIVE DUPLICATE. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6. Note that the last 3 is not a consecutive duplicate because it was preceded by a 7. Write some code that uses a loop to read such a sequence of non-negative integers, terminated by a negative number. When the code exits the loop it should print the number of consecutive duplicates encountered. In the above case, that value would be 3.
int firstNumber,secondNumber = -1, duplicates = 0; do { cin >> firstNumber; if ( secondNumber == -1) { secondNumber = firstNumber; }else { if ( secondNumber == firstNumber )duplicates++; elsesecondNumber = firstNumber; } } while(firstNumber > 0 );cout << duplicates;
Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, and that terminates when it reads an integer that is not positive. The values should be separated by single blank spaces. Declare any variables that are needed.
int num; do{ cin >> num; if (num > 100) cout << num << " "; } while (num>0);
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by exactly one space. Declare any variables that are needed.
int num=0; int sumeven=0; int sumodd=0; int evencount=0; int oddcount=0; do{cin >> num;if (num % 2 == 0 && num > 0) { evencount++; sumeven += num; }else if (num > 0){ oddcount++;sumodd += num; } }while (num > 0); cout<<sumeven;cout<<" "<<sumodd;cout<<" "<<evencount;cout<<" "<<oddcount;
Write a loop that reads positive integers from standard input, printing out those values that are even, separating them with spaces, and that terminates when it reads an integer that is not positive. Declare any variables that are needed.
int num=1; while (num>0) { cin >> num; if ((num % 2) == 0 && num > 0 ) { cout << num << " "; } }
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read. Declare any variables that are needed.
int sum=0; int num=1; while(num > 0) { cin >> num; if ((num % 2)==0 & (num>0)){sum+=num;}}cout << sum;
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read and the sum of all the odd integers read(The two sums are separated by a space). Declare any variables that are needed.
int x; int esum=0; int osum=0; cin >> x; while (x>0) { if (x%2==0)esum += x;elseosum += x; cin >> x;}cout << esum << " " << osum;
Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a while loop to compute the sum of the cubes of the first n counting numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total. Do NOT modify n.
k = 1; total = 0; while (k <= n) { total = total + (k*k*k); k++; }
Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". Let's define a SINGLETON to be a data element that is not repeated immediately before or after itself in the sequence. So, here there are four SINGLETONs (the first appearance of "fish", the first appearance of "bird", "mammal", and the second appearance of "fish"). Write some code that uses a loop to read a sequence of words, terminated by the "xxxxx". The code assigns to the variable n the number of SINGLETONs that were read. (For example in the above data sequence it would assign 4 to n). Assume that n has already been declared but not initialized. Assume that there will be at least one word before the terminating "xxxxx".
n = 0; string prev = "xxxxx", current, next; cin >> current; while (current != "xxxxx") { cin >> next; if (prev != current && current != next) { n++; }prev = current;current = next; }
Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002 as well all vehicles in its Guzzler line from model years 2004-2007. A bool variable named recalled has been declared. Given an int variable modelYear and a string modelName write a statement that assigns true to recalled if the values of modelYear and modelName match the recall details and assigns false otherwise. Do not use an if statement in this exercise!
recalled = (((modelYear >= 1999 && modelYear <= 2002) && (modelName == "Extravagant")) ||((modelYear >= 2004 && modelYear <= 2007) && (modelName == "Guzzler")));
Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002. A bool variable named recalled has been declared. Given an int variable modelYear and a string modelName write a statement that assigns true to recalled if the values of modelYear and modelName match the recall details and assigns false otherwise. Do not use an if statement in this exercise!
recalled = ((modelYear >= 1999 && modelYear <= 2002) && (modelName == "Extravagant"));
Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". There is a CONSECUTIVE REPETITION of length 3 (the three consecutive birds) and a CONSECUTIVE REPETITION of length 2 (the two reptiles). There are also several SINGLETONs of length 1 (a singleton fish, a singleton bird, a singleton mammal, and another singleton fish). Write some code that uses a loop to read in a sequence of words, terminated by the "xxxxx". The code assigns to t the number of CONSECUTIVE REPETITIONS that were read. (For example, in the above data sequence that value would be 2.) Assume that t has already been declared but not initialized. Assume that there will be at least one word before the terminating "xxxxx".
string currentWord="";string previousWord="";int currentState=0;int lastState=-1;t=-1;while (currentWord != "xxxxx"){cin >> currentWord;if (currentWord!=previousWord && currentWord!="xxxxx")currentState=0;if (currentWord==previousWord && currentWord!="xxxxx")currentState=1;if (currentState!=lastState && lastState!=1)t++;previousWord=currentWord;lastState=currentState;}cout << t;
Write a loop that reads strings from standard input where the string is either "duck" or "goose". The loop terminates when "goose" is read in. After the loop, your code should print out the number of "duck" strings that were read.
string duck; string goose; string x; int count = 0; do { cin >> x; if (x < "goose") { count++; } } while (x < "goose"); cout << count;
Write a loop that reads strings from standard input where the string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters) is read in. Other strings are ignored. After the loop, your code should print out 3 lines: the first consisting of the string "land:" followed by the number of "land" strings read in, the second consisting of the string "air:" followed by the number of "air" strings read in, and the third consisting of the string "water:" followed by the number of "water" strings read in. Each of these should be printed on a separate line.
string input; int land=0; int air=0; int water = 0; cin>>input; while(input!= "xxxxx") { if(input.compare("land") == 0 ) { land++; }if(input.compare("air") == 0) { air++; } if (input.compare("water") == 0) { water++; } cin>>input; } cout << "land:"<<land;cout << endl<<"air:"<<air; cout << endl<< "water:"<<water;
In the Happy Valley School System, children are classified by age as follows: less than 2, ineligible 2, toddler 3-5, early childhood 6-7, young reader 8-10, elementary 11 and 12, middle 13, impossible 14-16, high school 17-18, scholar greater than 18, ineligible Given an int variable age, write a switch statement that prints out the appropriate label from the above list based on age.
switch(age){ case 0: case 1: cout << "ineligible"; break; case 2: cout << "toddler"; break; case 3: case 4: case 5: cout << "early childhood"; break; case 6: case 7: cout << "young reader"; break; case 8: case 9: case 10: cout << "elementary"; break; case 11: case 12: cout << "middle"; break; case 13: cout << "impossible"; break; case 14: case 15: case 16: cout << "high school"; break; case 17: case 18: cout << "scholar"; break; default: cout << "ineligible"; break; }
Assume that grade is a variable whose value is a letter grade-- any one of the following letters: 'A', 'B', 'C', 'D', 'E', 'F', 'W', 'I'. Assume further that there are the following int variables, declared and already initialized: acount, bcount, ccount, dcount, ecount, fcount, wcount, icount.Write a switch statement that increments the appropriate variable (acount, bcount, ccount, etc.) depending on the value of grade. So if grade is 'A' then acount is incremented; if grade is'B' then bcount is incremented, and so on.
switch(grade){ case 'A': acount++; break; case 'B': bcount++; break; case 'C': ccount++; break; case 'D': dcount++; break; case 'E': ecount++; break; case 'F': fcount++; break; case 'W': wcount++; break; case 'I': icount++; break; }
Write a switch statement that tests the value of the char variable response and performs the following actions: if response is y, the message Your request is being processed is printed if response is n, the message Thank you anyway for your consideration is printed if response is h, the message Sorry, no help is currently available is printed for any other value of response, the message Invalid entry; please try again is printed
switch(response){ case 'y': cout << "Your request is being processed"; break; case 'n': cout << "Thank you anyway for your consideration"; break; case 'h': cout << "Sorry, no help is currently available"; break; default: cout << "Invalid entry; please try again"; break; }
HTTP is the protocol that governs communications between web servers and web clients (i.e. browsers). Part of the protocol includes a status code returned by the server to tell the browser the status of its most recent page request. Some of the codes and their meanings are listed below: 200, OK (fulfilled) 403, forbidden 404, not found 500, server error Given an int variable status, write a switch statement that prints out the appropriate label from the above list based on status.
switch(status){ case 200: cout << "OK (fulfilled)"; break; case 403: cout << "forbidden"; break; case 404: cout << "not found"; break; case 500: cout << "server error"; break; }
Given that two int variables, total and amount, have been declared, write a sequence of statements that: initializes total to 0 reads three values into amount, one at a time. After each value is read in to amount, it is added to the value in total (that is, total is incremented by the value in amount).
total = 0; cin >> amount; total=total+amount; cin >> amount; total=total+amount; cin >> amount; total=total+amount;
Given int variables k and total that have already been declared, use a do...while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.
total = 0; do { total += k*k; k++; }while (k <= 50);
Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a for loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total.
total = 0; for(k = 1; k <= n; k++) { total = total + (k*k*k); }
Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a do...while loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total.
total = 0; k = 1; do { total += k*k*k; k++; }while(k <= n);
Given int variables k and total that have already been declared, use a while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.
total = 0; k = 1; while (k <= 50) { total = total + (k*k); k++; }
Given int variables k and total that have already been declared, use a for loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.
total = 0;for(k = 1; k <= 50; k++){ total = total + (k*k);}
Write a statement that increments the value of the int variable total by the value of the int variable amount. That is, add the value of amount to total and assign the result to total.
total+= amount;
Given that two int variables, total and amount, have been declared, write a loop that reads integers into amount and adds all the non-negative values into total. The loop terminates when a value less than 0 is read into amount. Don't forget to initialize total to 0.
total=0; do { cin >> amount; if (amount>0) total += amount; } while (amount >=0);
You need to write a loop that reads integers and adds them to a sum as long as they are positive. Once 0 or a negative value is read in your loop terminates. Which is the preferred loop construct to use?
while loop