More Functions

Functions are super important in code, so we’re going to practice writing a few more! For a lot of students, the whole concept of a function will seem pretty fuzzy at this point, but with a little practice, it’ll all click.

Exercise 1:

Write the following functions, along with some statements that call each of them:

  1. A function that asks the user how old they are, then then tells them (by printing to the console) how old they’ll be in 5 years. This function doesn’t need to have any input parameter or return value.
  2. A function that takes two int parameters called A and B, ads them together, and prints the sum to the console
  3. A function that takes two float parameters called A and B, multiplies them together, and returns the product.
  4. A function that takes two number parameters and returns the average of the two.
  5. A function that takes two number parameters, and returns true if the first is larget than the second..

Exercise 2:

Revisit your Madlib program from the last lesson, and use functions to handle the user prompting, usinng colored text for the prompts. This should make your program quite a bit shorter, and it will look nicer too!

How do you feel about going back to your old code and improving it like that?

Exercise 3:

Go back to your “madlib” program from lesson 2, and use functions to simplify it.

  1. Identify patterns of statements that you repeat a lot, such as querying the user for a particular input
  2. Write a function to do that thing, using parameters and return values.
  3. Replace your statements with calls to those functions.

This process of going back and improving old code is called “Refactoring”.


Previous submodule: