6. Functions¶
Q) Purpose of Functions¶
Which of the following best explains the general purpose of using functions?
a) Runs some statements multiple times.
b) Split a large program into smaller, more understandable chunks.
c) Print multiple lines of text the screen at once.
d) Prompt the user to input a value and read in the value.
Q) Asking Age Function¶
Which of the following partial function definitions would be best for a function which asks the user their age and returns the answer?
a) int promptUserForAge() {...}
b) int promptUserForAge(int age) {...}
c) void promptUserForAge(int age) {...}
d) string promptUserForAge(string age) {...}
Q) Why use return
?¶
What is the purpose of a return statement in a function?
a) Print a value to the screen and leave the function.
b) Print a value to the screen and exit the program.
c) Exit the program.
d) Leave a function and pass back a value.
Q) Variable Scope¶
Consider the following code:
const int HEIGHT = 10;
void foo()
{
cout << "Height is: " << HEIGHT << endl;
}
int main()
{
foo();
}
Which is true about the constant HEIGHT
?
a) It is in the local scope of main()
.
b) It is in the global scope.
c) It can be used only inside the function foo()
.
d) It can be changed by code in either main()
or foo()
.
Q) What's in scope?¶
Consider the following code:
void baz()
{
int apple = 0;
}
void bar()
{
int grape = 0;
cout << XXXXXX << endl;
int pear = 0;
}
int main()
{
int orange = 0;
baz();
}
Which of the variables in this code could replace XXXXXX
and still have the program compile?
a) grape
b) apple
or grape
c) grape
or pear
d) apple
, grape
, or orange
Answers¶
b) Split a large program into smaller, more understandable chunks.
a) int promptUserForAge() {...}
d) Leave a function and pass back a value.
b) It is in the global scope.
a) grape