08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7

Functions

In this chapter, we will explain the following:

• Why functions are important in programming

• How to write functions

• What happens when a function is called

• Where functions are placed in a program

• Some important concepts relating to functions using several examples

7.1 About Functions

So far, all our programs have consisted of a single function called main. However, we have made

use of predefined C functions such as printf, scanf, strcpy, and fopen. When we run a program,

it starts executing with the first statement in main and ends when it reaches the last statement.

As we have seen, it is possible to write reasonably useful programs with only main. However,

there are many limitations to this approach. The problem to be solved may be too complex to be

solved with one function. We may need to break it up into subproblems and try to solve each of

these individually. It would be impractical to solve all the subproblems in one function. It might

be better to write a separate function to solve each subproblem.

Also, we may want to reuse the solution to common problems. It would be difficult to reuse

a solution if it is part of the solution to a bigger problem. For example, if we need the highest

common factor (HCF) of two numbers in several places, it would be best to write a routine that

works out the HCF of two given numbers; we call this routine whenever we need to find the HCF

of two numbers.

A well-written function performs some well-defined task; for example, skip a specified

number of lines in the output or arrange some numbers in ascending order. However, quite often,

a function also returns a value; for example, calculate the salary of a person and return the answer

or play one turn of a game and return the score for that turn. The value returned is normally used

at the point from which the function was called.

Previously, we used the string function strcmp, which returns a value that tells us the

result of comparing two strings. And we have used getchar and getc to return the next character

in the input.

We are now ready to learn how to write our own functions (called user-defined functions),

and we will see several examples in the rest of this book.

165

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!