MPL Answers
Write the necessary preprocessor directive to enable the use of file streams.
#include <fstream>
Consider this code: "int v = 20; --v; cout << v++;". What value is printed, what value is v left with?
20 is printed, v ends up with 19 19 is printed, v ends up with 20 20 is printed, v ends up with 20 19 is printed, v ends up with 19 cannot determine what is printed, v ends up with 20 correct - 19 is printed, v ends up with 20
Given the availability of an ofstream object named output , and a string variable name tweet, write the other statements necessary to open a file named "mytweet", display the prompt tweet: and then read an entire line into tweet and then write it out to the file mytweet. (Do not define a main function.)
cout << "tweet:"; getline(cin,tweet); output.open("mytweet"); output << tweet; output.close();
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
Given the availability of an ifstream object named indata and an ofstream object named outdata, write the other statements necessary to read one integer from a file called currentsales and write twice its value into a file called projectedsales. Assume that this is the extent of the input and output that this program will do.
double sales=0.0; indata.open("currentsales"); outdata.open("projectedsales"); indata >> sales; outdata << sales * 2.0; indata.close(); outdata.close();
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: aa ab ac ad ae ba bb ... 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 aa ab ac ba bb bc ca cb cc
for (char outterChar='a'; outterChar <=last; outterChar++){ for (char innerChar='a'; innerChar <=last; innerChar++){ cout << outterChar << innerChar << "\n"; } }
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>0; 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 << '\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 << " "; } }
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 << " "; } }
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 << "*"; }
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
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 << "*"; }
Write a statement that terminates the current loop when the value of the int variables x. and y.are equal
if(x == y){ break; }
Given an int variable x write some statements that attempt to open a file named "table20" and read a value into x; if that turns out not to be possible your code should then read avalue from standard input into x.
ifstream filename; filename.open("table20"); if (filename.fail()){ cin >> x; }else{ filename >> x; }
Given a bool variable isReadable write some statements that assign true to isReadable if the file "topsecret" exists and can be read by the program and assigns false to isReadable otherwise.
ifstream filename; filename.open("topsecret"); if (filename.fail()){ isReadable=false; }else{ isReadable=true; }
Define two objects named infile1 and infile2 that can be used to read data into program variables from two different files.
ifstream infile1, infile2;
Define an object named infile that can be used to read data into program variables from a file.
ifstream infile;
Given four files named winter2003.txt, spring2003.txt, summer2003.txt, fall2003.txt, define four ifstream objects named wntr, sprg, sumr, and fall, and use them, respectively, to open the four files for reading.
ifstream wntr, sprg, sumr, fall; wntr.open("winter2003.txt"); sprg.open("spring2003.txt"); sumr.open("summer2003.txt"); fall.open("fall2003.txt");
Given the availability of an ifstream object named input, write the other statements necessary to read an integer into a variable datum that has already been declared from a file called rawdata. Assume that reading that one integer is the only operation you will carry out with this file. (Note: write just the statements , do not define a main function.)
input.open("rawdata"); input >> datum; input.close();
Given an ifstream object named input1, associate it with a file named winterdata.txt by opening the file for reading.
input1.open("winterdata.txt");
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; } }
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=0; total=0; while (k<=n){ total+=k*k*k; k++; }
Given an int variable k that has already been declared , use a do...while loop to print a single line consisting of 97 asterisks. Use no variables other than k.
k=1; do { cout << "*"; k++; } while (k<=97);
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; }
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; while (k<=50) { total += (k*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);
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; for (int i=1; i<=3; i++){ cin >> amount; total += amount; }
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 (int k=1; k<=50; k++){ total += 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 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=n;k>0;--k) 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++; }while (k<=50);
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; k=1; do{ total += k*k; k++; }while (k<=50);
Given an int variable n that has already been declared , write some code that repeatedly reads a value into n until at last a number between 1 and 10 (inclusive) has been entered.
while ( n > 10 || n < 1 ) { cin >> n; }
Given a string variable s that has already been declared , write some code that repeatedly reads a value from standard input into s until at last a "Y" or "y"or "N" or "n" has been entered.
while ((s!="Y" && s!="y" && s!="N" && s!="n")) { cin >> s; }
Given an int variable k that has already been declared , use a while loop to print a single line consisting of 97 asterisks. Use no variables other than k.
while (k < 97) { cout << "*"; k++;}
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
Suppose that the code below is the body of some loop. Use a continue statement to make sure that the nothing is written to cout when y is 0.
cin >> x >> y; if (y == 0) continue; cout << x / y;
Given that corpdata is an ifstream object that has been used for reading data and that there is no more data to be read, write the necessary code to complete your use of this object . corpdata
corpdata.close();
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++; else secondNumber = firstNumber; } } while(firstNumber > 0 ); cout << duplicates;
Assume that two int constants ,FIRST_YEAR and LAST_YEAR have already been declared and initialized with year values (like 2009, 2014), along with a double variable oil that has been initialized with the number of barrels of oil consumed in Canada in the year given by FIRST_YEAR. Write some code that uses a while statement to print on a line by itself, each of the years from FIRST_YEAR to LAST_YEAR inclusive. On each line, after the year, separated by a colon and a space, print the new value amount of oil, taking into account that each year the oil consumed increases by 20%.
int i = FIRST_YEAR; while (i <= LAST_YEAR) { cout << i << ": " << oil << endl; oil *= 1.2; i++; }
Use an ifstream object named indata to read the first three integers from a file called lottowins and write each number to standard output , on a line by itself. Assume that this is the extent of the input that this program will do.
int int1, int2, int3; indata.open("lottowins"); indata >> int1 >> int2>> int3; cout << int1 << "\n"; cout << int2 << "\n"; cout << int3 << "\n"; indata.close();
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 << " "; } }
Given the availability of a file named numbers write the statements necessary to read an integer from standard input and then read in that many values from numbers and display their total.
int number, sum=0; #include <fstream> std::ifstream infile("numbers"); while (infile >> number) { sum += number; } cout << sum << endl;
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;
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 do...while 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.
j=1; do{ cout << "*"; j++; } while (j<=n);
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 while 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.
j=n; while ( j > 0 ) { cout << "*"; j--; }
Given four files named asiasales2009.txt, europesales2009.txt, africasales2009.txt, latinamericasales2009.txt, define four ofstream objects named asia, europe, africa, and latin, and use them, respectively, to open the four files for writing.
ofstream asia("asiasales2009.txt"); ofstream europe("europsales2009.txt"); ofstream africa("africasales2009.txt"); ofstream latin("latinamericasales2009.txt");
Define two objects named outfile1 and outfile2 that can be used to write data from program variables to two different files.
ofstream outfile1, outfile2;
Define an object named outfile that can be used to write data from program variables to a file.
ofstream outfile;
Given the availability of an ofstream object named output , write the other statements necessary to write the string "3.14159" into a file called pi. (Do not define a main function.)
output.open("pi"); output << "3.14159"; output.close();
Given an ofstream object named output , associate it with a file named yearsummary.txt by opening the file for writing.
output.open("yearsummary.txt");
Consider this code: "int s = 20; int t = s++ + --s;". What are the values of s and t?
s is 20 and t cannot be determined
Given an integer variable strawsOnCamel, write a statement that uses the auto-increment operator to increase the value of that variable by 1.
strawsOnCamel++;
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;
read first a user's given name followed by the user's age from standard input. Then use an ofstream object named outdata to write this information separated by a space into a file called outdata. Assume that this is the extent of the output that this program will do.
string name; int age; cin >> name >> age; outdata.open("outdata"); outdata << name << " " << age; outdata.close();
Given an integer variable timer, write a statement that uses the auto-decrement operator to decrease the value of that variable by 1.
timer--;
