6.x — Chapter 6 summary and quiz
Quick review#
- A function is a named group of steps. Call it with
name();. - The return type says what comes back.
void= nothing. - Parameters are inputs. By default the function gets copies.
- Variables live only inside their
{ }block (scope). - Declare a function before you call it.
- Overloading: same name, different parameters.
- Headers (
.h) declare, source files (.cpp) define.
Pick an answer. You find out right away if it is right.
What does a function with return type void give back?
void means the function returns no value.
By default, what does a function get when you pass it an int?
This is "pass by value". Changing the parameter doesn't change the original.
Where should function declarations usually go when splitting code into files?
Headers hold declarations. .cpp files hold the definitions.
What is wrong here?
int doubleIt(int x){ int result { x * 2 };}The function says it returns an int, but it never returns anything. Add return result; at the end.
What does this print?
void change(int n){ n = n * 10;} int main(){ int x { 3 }; change(x); std::cout << x;}3. The function changes a copy of x, not x itself.
Write a function isEven that takes an int and returns true if it is even.
bool isEven(int n){ return n % 2 == 0;}Write a function getNumber() that asks the user for a number and returns it. Then use it in main to read two numbers and print their sum.
#include <iostream> int getNumber(){ std::cout << "Enter a number: "; int n {}; std::cin >> n; return n;} int main(){ int a { getNumber() }; int b { getNumber() }; std::cout << "Sum: " << a + b << '\n'; return 0;}See how getNumber saved us from writing the same three lines twice?
Tip: press ← / → to move between lessons, / to search.