1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

A Bigger Bag of Tricks—Some More Operators for Your Programs

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (12.99 MB, 617 trang )


If the test in the first set of parentheses is true, the trueStatement executes. If the test in the first

set of parentheses is false, the falseStatement executes. The conditional operator you just saw

does exactly the same thing as this if...else statement:

if (total <= 3850.0

{ total *= 1.10; }

else

{ total *= 1.05; )



This statement tells C to multiply total by 1.10 or by 1.05, depending on the result of the relational

test.

Just about any if...else statement can be rewritten as a conditional statement. The conditional

requires less typing, you won’t accidentally leave off a brace somewhere, and the conditional runs

more efficiently than an if...else because it compiles into more compact code.

Tip

The format of the conditional operator is obvious when you think of it like this: The

question mark asks a question. Keeping this in mind, you could state the earlier

example as follows: Is the total <= 3850.0? If so, do the first thing; otherwise, do

the second.

C programmers don’t like the redundancy you saw in the earlier use of the conditional operator. As

you can see, the total variable appears twice. Both times, it is being assigned a value. When you

face such a situation, take the assignment out of the conditional operator’s statements:

Click here to view code image

total *= (total <= 3850.0) ? (1.10): (1.05);



Don’t replace every single if...else with a conditional operator. Many times, if...else is

more readable, and some conditional statements are just too complex to squeeze easily into a

conditional operator. However, when a simple if...else is all that’s needed, the conditional

operator provides a nice alternative.

The conditional operator offers one additional advantage over if: The conditional often can appear

in places where if can’t go. The following print(f) prints a trailing s if the number of pears is

more than 1:

Click here to view code image

printf("I ate %d pear%s\n", numPear, (numPear>1) ? ("s.") : ("."));



If the value in numPear is greater than 1, you’ll see something like this printed:

I ate 4 pears.



But if there is only one pear, you’ll see this:

I ate 1 pear.



Note

Maybe you’re wondering why the conditional operator is ?:, but the question mark

and colon never appear next to each other. Well, that’s just the way it is. It would be

too cumbersome to go around saying that the conditional operator looks like a question

mark and a colon with some stuff in between.

Here’s a short program that uses the conditional operator. (Actually, it uses it eight times!) The

program prompts the user for an integer and then tests whether the number is divisible by all singledigit numbers between 2 and 9:

Click here to view code image

// Example program #1 from Chapter 13 of Absolute Beginner's Guide

// to C, 3rd Edition

// File Chapter13ex1.c

/* This program asks for a number from 1 to 100 and tells then

whether or not their choice is equally divisible by 2 through 9. */

#include



main()

{

// Define the integer to hold the user's guess and then get it

// from the user

int numPick;

printf("Pick an integer between 1 and 100 ");

printf("(The higher the better!)\n");

scanf(" %d", &numPick); //remember for an int, you do need the &

printf("%d %s divisible by 2.", numPick, (numPick %

: ("is not"));

printf("\n%d %s divisible by 3.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 4.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 5.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 6.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 7.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 8.", numPick, (numPick

("is") : ("is not"));

printf("\n%d %s divisible by 9.", numPick, (numPick

("is") : ("is not"));

return 0;

}



2 == 0) ? ("is")

% 3 == 0) ?

% 4 == 0) ?

% 5 == 0) ?

% 6 == 0) ?

% 7 == 0) ?

% 8 == 0) ?

% 9 == 0) ?



Note

Although the printf() statement asks for the number to be between 1 and 100, users

actually can enter any integer. If you use 362880, you’ll find that it is divisible by all

eight single-digit integers.



The Small-Change Operators: ++ and -Although the conditional operator works on three arguments, the increment and decrement operators

work on only one. The increment operator adds 1 to a variable, and the decrement operator subtracts

1 from a variable. That’s it. ‘Nuff said. Almost....

Incrementing and decrementing variables are things you would need to do if you were counting items

(such as the number of customers who shopped in your store yesterday) or counting down (such as

removing items from an inventory as people buy them). In Chapter 10, “Powering Up Your Variables

with Assignments and Expressions,” you read how to increment and decrement variables using

compound operators. Here, you learn two operators that can more easily do the same. The increment

operator is ++, and the decrement operator is --. If you want to add 1 to the variable count, here’s

how you do it:

count++;



You also can do this:

++count;



The decrement operator does the same thing, except that the 1 is subtracted from the variable. You can

do this:

count--;



You also can do this:

--count;



As you can see, the operators can go on either side of the variable. If the operator is on the left, it’s

called a prefix increment or prefix decrement operator. If the operator is on the right, it’s known as a

postfix increment or postfix decrement operator.

Note

Never apply an increment or decrement operator to a literal constant or an expression.

Only variables can be incremented or decremented. You will never see this:

--14;



/* Don't do this! */



Prefix and postfix operators produce identical results when used by themselves. Only when you

combine them with other expressions does a small “gotcha” appears. Consider the following code:

int i = 2, j = 5, n;

n = ++i * j;



The question is, what is n when the statements finish executing? It’s easy to see what’s in j because j

doesn’t change and still holds 5. The ++ ensures that i is always incremented, so you know that i

becomes 3. The trick is determining exactly when i increments. If i increments before the

multiplication, n becomes 15, but if i increments after the multiplication, n becomes 10.

The answer lies in the prefix and postfix placements. If the ++ or -- is a prefix, C computes it before

anything else on the line. If the ++ or -- is a postfix, C computes it after everything else on the line

finishes. Because the ++ in the preceding code is a prefix, i increments to 3 before being multiplied

by j. The following statement increments i after multiplying i by j and storing the answer in n:

Click here to view code image

n = i++ * j;



/* Puts 10 in n and 3 in i */



Being able to increment a variable in the same expression as you use the variable means less work on

the programmer’s part. The preceding statement replaces the following two statements that you would

have to write in other programming languages:

n = i * j;

i = i + 1



Note

The ++ and -- operators are extremely efficient. If you care about such things (most of

us don’t), ++ and -- compile into only one machine language statement, whereas

adding or subtracting 1 using +1 or -1 doesn’t always compile so efficiently.

Let’s revisit the count up and count down program from Chapter 10, this time using the prefix

increment and decrement operators. This involves even fewer lines of code than the last program; we

can even cut the code to fewer lines when you learn about loops in the next chapter.

Click here to view code image

// Example program #2 from Chapter 13 of Absolute Beginner's Guide

// to C, 3rd Edition

// File Chapter13ex2.c

/* This program increases a counter from 1 to 5, printing updates

and then counts it back down to 1. However, it uses the increment

and decrement operators */

#include

main()

{



int ctr = 0;

printf("Counter

printf("Counter

printf("Counter

printf("Counter

printf("Counter



is

is

is

is

is



at

at

at

at

at



%d.\n",

%d.\n",

%d.\n",

%d.\n",

%d.\n",



++ctr);

++ctr);

++ctr);

++ctr);

++ctr);



printf("Counter

printf("Counter

printf("Counter

printf("Counter



is

is

is

is



at

at

at

at



%d.\n",

%d.\n",

%d.\n",

%d.\n",



--ctr);

--ctr);

--ctr);

--ctr);



return 0;

}



Note

To understand the difference between prefix and postfix, move all the increment and

decrement operators to after the ctr variables (ctr++ and ctr--). Can you guess

what will happen? Compile it and see if you are right!



Sizing Up the Situation

You use sizeof() to find the number of memory locations it takes to store values of any data type.

Although most C compilers now use 4 bytes to store integers, not all do. To find out for sure exactly

how much memory integers and floating points are using, you can use sizeof(). The following

statements do just that:

Click here to view code image

i = sizeof(int); // Puts the size of integers into i.

f = sizeof(float); // Puts the size of floats into f



sizeof() works on variables as well as data types. If you need to know how much memory

variables and arrays take, you can apply the sizeof() operator to them. The following section of

code shows you how:

Click here to view code image

char name[] = "Ruth Claire";

int i = 7;

printf("The size of i is %d.\n", sizeof(i));

printf("The size of name is %d.\n", sizeof(name));



Here is one possible output from this code:

The size of i is 4

The size of name is 12



Depending on your computer and C compiler, your output might differ because of the differences in



integer sizes. Notice that the character array size is 12, which includes the null zero.

Tip

The length of a string and the size of a string are two different values. The length is the

number of bytes up to but not including the null zero, and it is found via strlen().

The size of a string is the number of characters it takes to hold the string, including the

null zero.



Note

Although sizeof() might seem worthless right now, you’ll see how it comes in

handy as you progress in C.



The Absolute Minimum

The goal of this chapter was to round out your knowledge of C operators.

Understanding these operators doesn’t take a lot of work, yet the operators are

powerful and substitute for complete statements in other languages. Key concepts from

this chapter include:

• Use the conditional operator in place of simple if...else statements to improve

efficiency.

• The conditional operator requires three arguments. Extra parentheses help clarify

these three arguments by separating them from each other.

• Use ++ and -- to increment and decrement variables instead of adding and

subtracting 1 using assignment or the += and -= operators.

• Don’t think that a prefix and postfix always produce the same values. A prefix and

postfix are identical only when a single variable is involved. If you combine ++ or

-- with other variables and expressions, the placement of the prefix and postfix is

critical to get the result you want.



Part III: Fleshing Out Your Programs



14. Code Repeat—Using Loops to Save Time and Effort

In This Chapter

• Saving time by looping through code

• Using while

• Using do...while

Now that you’ve learned the operators, you’re ready to play “loop the loop” with your programs. A

loop is simply a section of code that repeats a few times. You don’t want a loop to repeat forever—

that’s called an infinite loop. The loops you write (if you write them properly—and, of course, you

will) should come to a conclusion when they finish doing the job you set them up to do.

Why would you want a program to loop? The answer becomes clear when you think about the

advantage of using a computer for tasks that people wouldn’t want to do. Computers never get bored,

so you should give them mundane and repetitive tasks; leave the tasks that require thought to people.

You wouldn’t want to pay someone to add a list of hundreds of payroll figures, and few people would

want to do it anyway. Computer programs can do that kind of repetitive work. People can then

analyze the results when the computer loop finishes calculating all the figures.

If you want to add a list of figures, print company sales totals for the past 12 months, or add up the

number of students who enroll in a computer class, you need to use a loop. This chapter explains two

common C loops that use the while command.



while We Repeat

The while statement always appears at the beginning or end of a loop. The easiest type of loop that

uses while is called the while loop. (The other is called the do...while loop. You’ll see it a

little later.) Here is the format of while:

Click here to view code image

while (condition)

{ block of one or more C statements; }



The condition is a relational test that is exactly like the relational test condition you learned

for if. The block of one or more C statements is called the body of the while.

The body of the while repeats as long as the condition is true. This is the difference between a

while statement and an if statement: The body of the if executes if the condition is true. The

body of the if executes only once, however, whereas the body of the while can execute a lot of

times.

Figure 14.1 helps explain the similarities and differences between if and while. The formats of the

two commands are similar, in that braces are required if the body of the while has more than one

statement. Even if the body of the while contains only a single statement, you should enclose the

body in braces so that the braces will still be there if you later add statements to the while. Never

put a semicolon after the while’s parenthesis. The semicolon follows only the statements inside the



body of the while.

Warning

The two statements in Figure 14.1 are similar, but they don’t do the same thing. while

and if are two separate statements that do two separate things.

You must somehow change a variable inside the while loop’s condition. If you don’t, the

while will loop forever because it will test the same condition each time through the loop.

Therefore, you avoid infinite loops by making sure the body of the while loop changes something in

the condition so that eventually the condition becomes false and the program continues with

the statements that follow the while loop.



FIGURE 14.1 The if body executes once; the while body can repeat more than once.

Note

As with if, the while might never execute! If the condition is false going into

while the first time, the body of the while doesn’t execute.



Using while

If you want to repeat a section of code until a certain condition becomes false, while is the way to

go. Let’s revisit the counter up and down program for a fourth go-round and use while loops this

time:

Click here to view code image



Xem Thêm
Tải bản đầy đủ (.pdf) (617 trang)

×