CSCI 159 Quiz 1 Sample Solutions (F25N02) Monday lab


Question 1 [3 marks]
Write a C++ code segment that declares a variable named initialVal of type float, 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

float initialVal;
cout << "Please enter a value" << endl;
cin >> initalVal;
cout << "You entered " << initialVal << endl;


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

Sample solution
rem = num % denom;


Question 3 [3 marks]
Suppose price1, price2, and price3 have already been declared as variables of type float 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 three separate lines (one value per line) in a column of width 10, with 2 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(2);
cout << setw(10) << price1 << endl;
cout << setw(10) << price2 << endl;
cout << setw(10) << price3 << endl;


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

Sample solution
w = pow(x,y) + sqrt(z);


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 twice the original value and then three times that value. (E.g. if the original value was 1.2 then the program would display 2.4 and 7.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 twice, thrice;
   twice = 2 * userVal;
   thrice = 3 * twice;
   cout << "Twice original is " << twice << endl;
   cout << "Three times that value is " << thrice << endl;
   return 0;
}