What is the benefit of using a function in your program?
Reduces repetition, improves readability, simplifies debugging.
What's the difference between a parameter and an argument?
Parameter = placeholder; Argument = actual value passed.
What keyword sends data back from a function?
return
T/F: Pass by value allows changing the original variable.
False
Which loop repeats a known number of times?
for loop
Name the 3 components of a function definition.
Return type, function name, parameter list.
Define a function that accepts a string.
void greet(string name){}
Complete this: int square(int x) { _____ }
return x * x;
Convert: void changeNum(int num) → pass by reference.
void changeNum(int &num)
Write countdown(int n) that prints from n to 1.
void countdown(int n) {
for (int i = n; i >= 1; --i)
cout << i << " ";
}
Predict the output of calling a function twice.
Function executes twice; prints twice (e.g., Hello!Hello!).
What’s the output of a function that modifies a value passed by value?
Original variable unchanged due to pass-by-value.
Why is it bad to print and return in the same function?
Mixing responsibilities — should separate logic from output.
Output of modifying a variable passed by reference?
Value updated and printed (e.g., 15).
What is printed: loop from 0 to n in steps of 2?
Output is 0 2 4
Write a function that prints "SI Rocks!" 5 times using a for loop.
void printMessage() {
for (int i = 0; i < 5; ++i) cout << "SI Rocks!\n";
}
How would you create a function using 'int x' to not modify the actual value of x?
Change to pass-by-reference using int &x.
Compare a void and value-returning function.
Void = performs action, no return. Value-returning = sends result back.
What's the risk of reference? How to prevent it?
Risk = accidental data change; prevent with const & for read-only.
Write countdown(int n) that it returns the sum, not print.
int countdownSum(int n) {
int total = 0;
for (int i = n; i >= 1; --i)
total += i;
return total;
}
Write a selection sort function that sorts the vector: 2,1,6,4,3
Min and Swap function.
Write a function to swap two integers using reference. Why reference?
void swapVals(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
Write a function to return the sum of 1 through n.
int sumToN(int n) {
int sum = 0;
for (int i = 1; i <= n; ++i) sum += i;
return sum;
Write a function to average two values and store in a reference variable.
void average(int a, int b, double &avg) {
avg = (a + b) / 2.0;
}
Write drawRow(int length) to print a row of *
void drawRow(int length) {
for (int i = 0; i < length; ++i)
cout << "*";
cout << endl;
}