1. Trang chủ
  2. » Công Nghệ Thông Tin

C Programming for the Absolute Beginner phần 5 potx

25 384 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 25
Dung lượng 1,09 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

It is a common program-ming practice to construct your function prototype before the actual function is built.. IIt is common pprogramming practice to construct your function prototype

Trang 1

a function that contains the logic and structures to handle this procedure and then reusethat function when needed Putting all the code into one function that can be called repeat-edly will save you programming time immediately and in the future if changes to the functionneed to be made.

Let me discuss another example using the printf() function (which you are already familiarwith) that demonstrates code reuse In this example, a programmer has already implementedthe code and structures needed to print plain text to standard output You simply use theprintf() function by calling its name and passing the desired characters to it Because theprintf() function exists in a module or library, you can call it repeatedly without knowingits implementation details, or, in other words, how it was built Code reuse is truly a pro-grammer’s best friend!

Information Hiding

Information hiding is a conceptual process by which programmers conceal implementationdetails into functions Functions can be seen as black boxes A black box is simply a compo-nent, logical or physical, that performs a task You don't know how the black box performs(implements) the task; you just simply know it works when needed Figure 5.2 depicts theblack box concept

F IGURE 5.2

Demonstrating the black box concept.

Consider the two black box drawings in Figure 5.2 Each black box describes one component;

in this case the components are printf() and scanf() The reason that I consider the twofunctions printf() and scanf() black boxes is because you do not need to know what’s inside

of them (how they are made), you only need to know what they take as input and what theyreturn as output In other words, understanding how to use a function while not knowinghow it is built is a good example of information hiding

Many of the functions you have used so far demonstrate the usefulness of information hiding.Table 5.1 lists more common library functions that implement information hiding in struc-tured programming

Trang 2

If you’re still put off by the notion of information hiding or black boxes, consider the followingquestion Do most people know how a car’s engine works? Probably not, most people are onlyconcerned that they know how to operate a car Fortunately, modern cars provide an interfacefrom which you can easily use the car, while hiding its implementation details In otherwords, one might consider the car's engine the black box You only know what the black boxtakes as input (gas) and what it gives as output (motion).

Going back to the printf() function, what do you really know about it? You know that theprintf() function prints characters you supply to the computer’s screen But do you knowhow the printf() function really works? Probably not, and you don’t need to That’s a keyconcept of information hiding

In structured programming you build components that can be reused (code reusability) andthat include an interface that other programmers will know how to use without needing tounderstand how they were built (information hiding)

Function prototypes tell C how your function will be built and used It is a common

program-ming practice to construct your function prototype before the actual function is built Thatstatement was so important it is worth noting again IIt is common pprogramming practice

to construct your function prototype before the actual ffunction is built

Programmers must think about the desired purpose of the function, how it will receiveinput, and how and what it will return To demonstrate, take a look at the following functionprototype

TA B L E 5 1 CO M M O N LI B R A R Y FU N C T I O N S

Library Name Function Name Description

Standard input/output scanf() Reads data from the keyboard

Standard input/output printf() Prints data to the computer monitor

Character handling isdigit() Tests for decimal digit characters

Character handling islower() Tests for lowercase letters

Character handling isupper() Tests for uppercase letters

Character handling tolower() Converts character to lowercase

Character handling toupper() Converts character to uppercase

Trang 3

float addTwoNumbers(int, int);

This function prototype tells C the following things about the function:

• The data type returned by the function—in this case a float data type is returned

• The number of parameters received—in this case two

• The data types of the parameters—in this case both parameters are integer data types

• The order of the parameters

Function implementations and their prototypes can vary It is not always necessary to sendinput as parameters to functions, nor is it always necessary to have functions return values

In these cases, programmers say the functions are void of parameters and/or are void of areturn value The next two function prototypes demonstrate the concept of functions withthe void keyword

void printBalance(int); //function prototype

The void keyword in the preceding example tells C that the function printBalance will notreturn a value In other words, this function is void of a return value

int createRandomNumber(void); //function prototype

The void keyword in the parameter list of the createRandomNumber function tells C this functionwill not accept any parameters, but it will return an integer value In other words, this func-tion is void of parameters

Function prototypes should be placed outside the main() function and before the main() tion starts, as demonstrated next

Trang 4

#include <stdio.h>

int addTwoNumbers(int, int); //function prototype

int subtractTwoNumbers(int, int); //function prototype

int divideTwoNumbers(int, int); //function prototype

int multiplyTwoNumbers(int, int); //function prototype

Function definitions implement the function prototype In fact, the first line of the functiondefinition (also known as the header) resembles the function prototype, with minor excep-tions To demonstrate, study the next block of code

Trang 5

return operand1 + operand2;

}

I have two separate and complete functions: the main() function and the addTwoNumbers()function The function prototype and the first line of the function definition (the functionheader) bear a striking resemblance The only difference is that the function header containsactual variable names for parameters and the function prototype contains only the variabledata type The function definition does not contain a semicolon after the header (unlike itsprototype) Similar to the main() function, the function definition must include a beginningand ending brace

In C, functions can return a value to the calling statement To return a value, use thereturn keyword, which initiates the return value process In the next section, you will learnhow to call a function that receives its return value

You can use the keyword return in one of two fashions: First, you can use thereturn keyword to pass a value or expression result back to the calling state-ment Second, you can use the keyword return without any values or expres-sions to return program control back to the calling statement

Sometimes however, it is not necessary for a function to return any value For example, thenext program builds a function simply to compare the values of two numbers

//function definition

int compareTwoNumbers(int num1, int num2)

{

if (num1 < num2)

printf("\n%d is less than %d\n", num1, num2);

else if (num1 == num2)

printf("\n%d is equal to %d\n", num1, num2);

T I P

Trang 6

def-#include <stdio.h>

int addTwoNumbers(int, int); //function prototype

int subtractTwoNumbers(int, int); //function prototype

Trang 7

return num1 - num2;

}

It’s now time to put your functions to work with function calls Up to this point, you mayhave been wondering how you or your program will use these functions You work withyour user-defined functions the same way you work with other C library functions such asprintf() and scanf()

Using the addTwoNumbers() function from the previous section, I include a single function call

in my main() function as shown next

Trang 8

encoun-In other words, the entire statement addTwoNumbers(5, 5) is replaced with the number 10 Inthe preceding program, the returned value of 10 is assigned to the integer variable iResult.Function calls can also be placed in other functions To demonstrate, study the next block ofcode that uses the same addTwoNumbers() function call inside a printf() function.

int num1, num2;

printf("\nEnter the first number: ");

Trang 9

Demonstrated next is the printReportHeader() function that prints a report header using the

\t escape sequence to print a tab between words

#include <stdio.h>

void printReportHeader(); //function prototype

main()

{

Trang 10

com-printReportHeader; //Incorrect function call printReportHeader(); //Correct function callThe first function call will not cause a compile error but will fail to execute thefunction call to printReportHeader The second function call, however, containsthe empty parentheses and will successfully call printReportHeader().

V ARIABLE S COPE

Variable scope identifies and determines the life span of any variable in any programming

language When a variable loses its scope, it means its data value is lost I will discuss twocommon types of variables scopes in C, local and global, so you will better understand theimportance of variable scope

Local Scope

You have unknowingly been using local scope variables since Chapter 2, "Primary Data Types."Local variables are defined in functions, such as the main() function, and lose their scope eachtime the function is executed, as shown in the following program:

#include <stdio.h>

main()

C A U T

I O N

Trang 12

printf("\nEnter a second number: ");

Global Scope

Locally scoped variables can be reused in other functions without harming one another’scontents At times, however, you might want to share data between and across functions To

support the concept of sharing data, you can create and use global variables.

Global variables are created and defined outside any function, including the main() function

To show how global variables work, examine the next program

#include <stdio.h>

void printLuckyNumber(); //function prototype

int iLuckyNumber; //global variable

main()

{

Trang 13

printf("\nEnter your lucky number: ");

As demonstrated in Figure 5.5, the Trivia game utilizes many of this chapter’s concepts andtechniques

F IGURE 5.5

Demonstrating chapter-based concepts with the Trivia game.

The Trivia game uses function prototypes, function definitions, function calls, and a globalvariable to build a simple and fun game Players select a trivia category from the main menuand are asked a question The program replies that the answer is correct or incorrect

Trang 14

Each trivia category is broken down into a function that implements the question and answerlogic There is also a user-defined function, which builds a pause utility.

All of the code necessary for building the Trivia game is shown next

Trang 16

printf("\nEnter your selection: ");

scanf("%d", &iAnswer);

return iAnswer;

} //end sportsQuestion function

/********************************************************** FUNCTION DEFINITION

**********************************************************/ int geographyQuestion(void)

************************************************************/ void pause(int inNum)

{

int iCurrentTime = 0;

int iElapsedTime = 0;

Trang 17

iCurrentTime = time(NULL);

do {

iElapsedTime = time(NULL);

} while ( (iElapsedTime - iCurrentTime) < inNum );

} // end pause function

• Code reusability is implemented as functions in C

• Information hiding is a conceptual process by which programmers conceal tation details into functions

implemen-• Function prototypes tell C how your function will be built and used

• It is common programming practice to construct your function prototype before theactual function is built

• Function prototypes tell C the data type returned by the function, the number of rameters received, the data types of the parameters, and the order of the parameters

pa-• Function definitions implement the function prototype

• In C, functions can return a value to the calling statement To return a value, use thereturn keyword, which initiates the return value process

• You can use the return keyword to pass a value or expression result back to the callingstatement or you can use the keyword return without any values or expressions to returnprogram control back to the calling statement

• Failing to use parentheses in function calls void of parameters can result in compileerrors or invalid program operations

• Variable scope identifies and determines the life span of any variable in any ming language When a variable loses its scope, its data value is lost

program-• Local variables are defined in functions, such as the main() function, and lose their scopeeach time the function is executed

Trang 18

• Locally scoped variables can be reused in other functions without harming one another’scontents.

• Global variables are created and defined outside any function, including the main()function

Challenges

1 Write a function prototype for the following components:

A function that divides two numbers and returns the

remainder

A function that finds the larger of two numbers and returns

the result

A function that prints an ATM menu—it receives no

parameters and returns no value

2 Build the function definitions for each preceding function

prototype.

3 Add your own trivia categories to the Trivia game.

4 Modify the Trivia game to track the number of times a user gets

an answer correct and incorrect When the user quits the

program, display the number of correct and incorrect answers.

Consider using global variables to track the number of

questions answered, the number answered correctly, and the

number answered incorrectly.

Trang 19

C H A P T E R

A RRAYS

n important and versatile programming construct, arrays allow you to

build collections of like variables This chapter will cover many array ics, such as creating single and multidimensional arrays, initializing them,and searching through their contents Specifically, this chapter covers the follow-ing array topics:

• Variables in an array share the same name

• Variables in an array share the same data type

A

Trang 20

• Individual variables in an array are called elements

• Elements in an array are accessed with an index number

Like any other variable, arrays occupy memory space Moreover, an array is a grouping ofcontiguous memory segments, as demonstrated in Figure 6.1

F IGURE 6.1

A six-element

array.

The six-element array in Figure 6.1 starts with index 0 This is an important concept to

remember, so it’s worth repeating Elements in an array begin with index number zero There are

six array elements in Figure 6.1, starting with element 0 and ending with element 5

A common programming error is to not account for the zero-based index inarrays This programming error is often called the off-by-one error This type oferror is generally not caught during compile time, but rather at run time when auser or your program attempts to access an element number of an array thatdoes not exist For example, if you have a six-element array and your programtries to access the sixth element with index number six, either a run-timeprogram error will ensue or data may be lost This is because the last index in asix-element array is index 5

There are occasions when you might need or want to use a one-dimensional array Althoughthere is no rule for when to use an array, some problems are better suited for an array-basedsolution, as demonstrated in the following list

• The number of pages in each chapter of a book

• A list of students’ GPAs

• Keeping track of your golf score

• A list of phone numbers

Looking at the preceding list, you may be wondering why you would use an array to store theaforementioned information Consider the golf score statement If you created a program

C A U T

I O N

Ngày đăng: 05/08/2014, 09:45

TỪ KHÓA LIÊN QUAN