5.8. Functions¶
In the last section I mentioned “all the things functions are good for.” About this time, you might be wondering what exactly those things are. Here are some of the reasons functions are useful:
By giving a name to a sequence of statements, you make your program easier to read and debug.
Dividing a long program into functions allows you to separate parts of the program, debug them in isolation, and then compose them into a whole.
Functions facilitate both recursion and iteration.
Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
For example, instead of writing the 53 lines of code below…
A function allows you to reduce it to the 21 lines of code below. The function makes it easier to read, debug, and use the function many times without rewriting it each time.
- A named sequence/group of statements that perform a particular task.
- Yes, a function is a named sequence of statements.
- Any sequence of statements.
- While functions contain sequences of statements, not all sequences of statements are considered functions.
- A mathematical expression that calculates a value.
- While some functions do calculate values, the python idea of a function is slightly different from the mathematical idea of a function in that not all functions calculate values. Consider, for example, the turtle functions in this section. They made the turtle draw a specific shape, rather than calculating a value.
- A statement of the form x = 5 + 4.
- This statement is called an assignment statement. It assigns the value on the right (9), to the name on the left (x).
Q-3: What is a function in C++?
Create a function called absoluteValue
, which returns the absolute value of a parameter num
. Assume you do not have access to #include <cmath>
.
- Once you write and debug a function, you can reuse it.
- The reusability of functions is very useful.
- Makes your program easier to read and debug.
- By abstracting blocks of code, functions make your code easier to read and understand.
- Functions facilitate both recursion and iteration.
- Recursive functions and iterative functions are useful.
- None of the above.
- All of the choices above are reasons for why functions are useful.
Q-5: What is of these is NOT a reason that functions are useful?
More to Explore
From cppreference.com