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

We say that we call (or invoke) the function with the argument. (In this book, we use the term

‘parameter’ when referring to the definition of the function and the term ‘argument’ when the

function is called. Others use the terms interchangeably.) The “call” is executed as follows:

• The value of the argument is determined. In this case, it is just the constant 3

but, in general, it could be an expression.

• The value is copied to a temporary memory location. This location is passed

to the function where it is labeled with the name of the parameter, n. In

effect, the parameter variable n is set to the value of the argument. We can

picture this as follows:

n 3

• The body of the function is executed. In this case, since n is 3, the for loop

becomes

for (int h = 1; h <= 3; h++)

and it prints \n three times.

• When the function is finished, the location containing the argument

is discarded and control returns to main to the statement following

skipLines(3).

Note that we can get skipLines to print a different number of blank lines by supplying a

different argument when we call it.

When the value of an argument is passed to a function, we say the argument is passed “by

value.” In C, arguments are passed “by value.”

7.3 A Program with a Function

We write Program P7.1 to show how skipLines fits into a complete program.

Program P7.1

#include <stdio.h>

int main() {

void skipLines(int);

printf("Sing a song of sixpence\n");

skipLines(2);

printf("A pocket full of rye\n");

} //end main

void skipLines(int n) {

for (int h = 1; h <= n; h++)

printf("\n");

} //end skipLines

167

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!