Today we practiced with functions.
Most of the stuff I wanted to emphasize is in the source code below (read the comments!)
but here are a couple of extra points:
A few of you have told me you don't see the "point" of functions.
That actually makes a ton of sense.
Functions don't let you code anything you couldn't do before;
they're basically just a useful way to consolidate / organize your code,
and avoid repeating the same code twice.
This isn't so important for your example programs now, since they're mostly very short.
But one day, if you work on a "real" project with many thousands of lines of code,
you'll be very thankful you learned how to use functions to keep everything organized!
Passing by const reference is also not so obviously useful yet.
The "reference" part means that instead of making a copy,
you're letting the function work with the variable itself.
The "const" part means the function is promising to never change that variable.
The only point of using const reference instead of pass-by-value is to avoid making that copy,
so it's only really useful if you're passing in a variable that's very big in terms of memory.
(Think about a string that contains 10000000 characters.)
excitement.cpp - demos a basic function.
Input a string and output a modified version.
pe5_functions.cpp - modifies
this old program
to use a function.
sortTwo.cpp - trickier example, used to demo the difference between
passing by value vs passing by reference.
If I were you guys, I'd spend my midterm prep time as follows.
First, go reread all the professor's slides.
Then, spend your remaining study time on practice problems,
either from the bottom of this page or from here.
Make sure to do practice problems with just pencil+paper instead of typing your code!
It's hard at first to get the syntax right when you're used to Visual Studio helping find mistakes for you,
but you won't have Visual Studio's help during the test!
Here are some Google searches you could try if you're having trouble with today's material.
I'm deliberately trying to choose search terms that you could have thought of yourself!
c++ function declaration example (or substutitute "definition" or "call" for "declaration")
c++ pass by value vs by reference
c++ why pass const reference
Extra stuff to try for fun (not required)
In the "pe5.cpp" example above, I converted a previously-written program
into a new version that does the same thing but uses a function.
Here are links to other old programs we've written together.
Try setting up the function version yourself if you want extra practice!
Write and use a function with signature: bool isDivisibleBy3or5(int n).
Put the "grab a random double in [a,b]" code in its own function.
The function signature should be: double getRandomAtoB(double a, double b).
This function should get called twice.