CPSC 225, Spring 2002
Quiz #1, January 28This is the first quiz in CPSC 225: Intermediate Programming.
Question 1: In C++, parameters can be passed by reference. What does this mean, and what syntax is used in a program to indicate that a parameter will be passed by reference?
Answer: When a parameter is passed by reference to a function, that function can change the value of the actual parameter that is provided in the function call. The formal parameter in the function becomes an "alias" for the actual argument; that is, it refers to the same memory location. In the standard "pass by value", the formal parameter has its own memory location, and changes made to the contents of this memory location have no effect on the actual argument. Pass by reference is indicated by an ampersand appended to the type that is specified for the formal parameter. For example, in "void changeSelection(int& selection, int newSelection)", selection is passed by reference while newSelection is passed by value.
Question 2: Many C++ programs begin with the line "#include <iostream>". What does this mean and why is it necessary?
Answer: Iostream is the name of a header file that declares several things related to input and output, including the variables cout and cin. By including iostream, you make it possible to used these variables in your program. (Notes: (1) In standard C++, you also have to add "using namespace std;" to get direct access to cout, cin, and other identifiers defined in the standard namespace. (2) The textbook says that iostream is a "library", but I think that header file is more accurate. As far as I am concerned, header files ordinarily contain only declarations while libraries contain compiled code.)
Question 3: Write a complete C++ program that will read and evaluate a simple arithmetic expression such as: 27 + 5 or 85 - 12. An expression consists of two integers and an operator. An operator is one of the characters +, -, *, or /. When the program is executed, the user types in one expression of this form and the program prints the value of the expression.
Answer:
#include <iostream> using namespace std; int main() { int x,y; // The operands of the expression. char op; // The operator in the expression. cout << "Enter your expression: "; cin >> x >> op >> y; cout << "The value is: "; if ( op == '+' ) cout << (x+y); else if ( op == '-' ) cout << (x-y); else if ( op == '*' ) cout << (x*y); else if ( op == '/' ) { if ( y == 0 ) cout << "undefined, because division by zero is not allowed."; else cout << (x/y); } else cout << "undefined, because " << op << " is an unknown operator."; cout << endl; }