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

7.2 skipLines

We have seen that we can use \n in a printf statement to print a blank line. For example,

the statement

printf("%d\n\n%d\n", a, b);

will print a on one line, skip one line and print b on the next line. We can usually skip any number

of lines by writing the appropriate number of \n’s in the printf statement.

Sometimes we may want to skip 3 lines, sometimes 2 lines, sometimes 5 lines, and so on.

It would be nice if there was a statement we could use to skip any number of lines we want.

For instance, to skip 3 lines, we should be able to write

skipLines(3);

and to skip 5 lines, we write

skipLines(5);

What we want is a function called skipLines, which takes an integer argument (n, say) and

skips n lines. In C, we write this function as follows:

void skipLines(int n) {

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

printf("\n");

}

Observe that the structure of the function is similar to the structure of main. It consists of a

header (the first line, except { ) followed by the body enclosed in braces. The word void indicates

that the function does not return a value and (int n) defines n as an integer parameter. When

the function is called, we must supply it with an integer value to match the parameter n.

This is the definition of the function skipLines. We use the function by calling it when we

write, in main, a statement such as:

skipLines(3);

(A function can normally be called from any other function but, to focus our discussion, we

will assume it is called from main.)

166

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!