In: Computer Science
Discuss Exercises #1 on page 171: Anne complains that defining functions to use in her programs is a lot of extra work. She says she can finish her programs much more quickly if she just writes them using the basic operators and control statements. State three reasons why her view is shortsighted. Explain why functions are useful in structuring code in a program.
Lets first write some general statements as to why
functions are important.
- Function provide readability in the code.
- Functions avoid redundancy in the code.
- Program is broken down in sub parts of functions which is easy to
understand by any new joiner.
- Name of function directly refers to the work that a function does
(convention). So, just by looking at function , we can come to know
about the overview of code it computes.
1.) Lets take an example where we need to write a code that
computes average , max , min of students marks based on user input.
Enter 1 - > Avergae. 2 -> Max. 3 -> Min 4->
exit
Consider the below steps
in case no function is involved
- Show menu on screen by writting print statements.
- Take input from user
- Open and read file
- Does the calculation
- These steps are for one user. This menu has to be shown until
user exits. In this case, we have to keep on writting the print
statements for the menu. Number of print statements will be N where
N is number of times user does an action.
Consider the
below steps is case function is involved
- Call function to show menu
- Call funtion to take user input and return a value.
- Return contents of file from a function.
- Calls another function that computes the result and return it to
the caller.
Here, we have to just define all the cases only ONCE. In every
case, we just call the method and get the result.
2.)
Modifications - > In case we want to debug the code and we know
there is some error in a portion of code, it is always easier to
maintain the code if one logical set of code is seperated from
another set of code.
3.)
Code growth -> It is okay if the lines of code of a program are
10-100 or even in thousands. But, this is not a practical case. In
a real life project, the lines of codes are in lakhs. To maintain
that huge amount of code, we need some logical segregated approach
to identify any issues or make any code changes.
4.)
Reusability -> If same snippet is required at some other place
in a project/program, we need to write that again. So, better have
functions. Just pass a value to it and get the result without
having to write code again.
*Kindly upvote if this
helped