CSC 161 Pre-Test Solutions
Question 1
Write code to ask a user his or her first name, age, and GPA. Print the results back in the sentence: "[name], you are [age] years old and your GPA is [gpa]". Use appropriate types!! Don't worry about main—just write the code for this part.
Solution
(Back to top)Question 2
Building on the previous question, print the year the user was born based on the given age; if they were born in the 1960s (1960-1969) print "far out".
Solution
(Back to top)Question 3
Write the C++ code to prompt the user: "Please choose the [s]horter path or [l]onger path:"; keep prompting them until a valid choices is entered (either s or l).
Solution
(Back to top)Question 4
Provide two or more reasons a programmer may want to use functions.
Solution
- reduce code duplication
- ease of code reuse; good modularity
- looks cleaner
- easier to debug and maintain
- there are probably many other good reasons...
Question 5
Define a function called "echo" that returns nothing and takes a single parameter: a name to print. The function should print "Hi", followed by the name passed in. Below the definition, write the code to invoke echo so that it will print out your name.
Solution
(Back to top)Question 6
Provide two or more reasons a programmer may want to use arrays.
Solution
- allows a list of things to be more easily stored
- makes organizing lists of things easy, e.g., sorting
- reduce code (one variable for the array vs. one variables per element
- if the number of things is unknown (e.g., reading in info from a file, which may have 0 things, or 1000 things)
- there are probably many other good reasons...
Question 7
Declare and initialize an array called "friends" containing 5 friends' names.
Solution
(Back to top)Question 8
Write the code to iterate over the array and print out each of your friends' names.
Solution
(Back to top)Question 9
Conceptually, what is the difference between pass-by-reference and pass-by-value? How does the syntax differ between the two?
Solution
In pass-by-value, the parameters are copied from the caller's memory space (e.g., in main
) to the function instance's memory. Any reassignments to the function's copy within the function will not be reflected in the caller's copy.
In pass-by-reference, denoted by a the parameter name preceded with &
, the function's parameter is directly linked to the caller's memory. Reassignments made to the parameter will be reflected in the caller's memory.
Question 10
Provide two or more reasons a programmer may want to use structs.
Solution
- structs allow us to encapsulate related data, e.g., a person's name, phone number, and email
- it makes it easier to pass data around (e.g., passing one struct vs. passing each field individually)
- it makes code more readable when used properly
- it eases debugging and modification
- there are probably many other good reasons...