CSCI 159 Quiz 1 Sample Solutions (F25N01) Wednesday lab


Question 1 [3 marks]
Write a C++ code segment that declares a variable named starter of type long, uses cout to ask the user to enter a value, uses cin to read their input into the variable, and uses cout to display the entered value back to them.

Sample Solution
// I'm assuming  the using std::cin, cout, etc has been done

long starter;
cout << "Please enter a value" << endl;
cin >> starter;
cout << "You entered " << starter << endl;


Question 2 [3 marks]
Suppose top, bot, and r have already been declared as variables of type int, and that values have already been assigned to top and bot. Write a C++ code segment that uses the modulo operator (%) to compute the remainder after dividing top by bot, storing that value in r.

Sample Solution
r = top % bot;


Question 3 [3 marks]
Suppose weight1, weight2, and weight3 have already been declared as variables of type double and that values have already been assigned to them. Write a C++ code segment that uses cout, setw, fixed, and setprecision to display them on separate lines (one per line) in a column of width 13, with 3 digits of precision after the decimal point for each.

Sample Solution
// this question should have said fixed instead of cin in the "... that uses ..."
// so I didn't take marks off if folks neglected the << fixed part of the answer below

// Here assuming  the using std::cin, cout, etc has been done
// note that setw has to be done for each columnized value,
// whereas fixed and setprecision need only be done once
cout << fixed << setprecision(3);
cout << setw(13) << weight1 << endl;
cout << setw(13) << weight2 << endl;
cout << setw(13) << weight3 << endl;


Question 4 [3 marks]
Suppose four variables, v1, v2, v3, v4 have already been declared as type double, and that v2, v3, v4, already have values assigned to them. Write a short code segment that computes (v2v3 + the square root of (v2 + v3)), storing the result in v1. (You can assume the cmath library has already been #included, so pow and sqrt are available.)

Sample Solution
v1 = pow(v2,v3) + sqrt(v2+v3);


Question 5 [8 marks]
Write a short but complete C++ program that gets the user to enter a real number, stores that value appropriately, displays the value back to the user, then computes and displays half the original value and then one third of that value. (E.g. if the original value was 1.2 then the program would display 0.6 and 0.2.)

Each value displayed should be on a line of its own.

Sample Solution
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
   double userVal;
   cout << "Please enter a real number" << endl;
   cin >> userVal;
   double half, third;
   half = userVal / 2;
   third = half / 3;
   cout << "Half original is " << half << endl;
   cout << "One third that value is " << third << endl;
   return 0;
}