Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
245 views
Selection Statements
Uploaded by
yaazel
AI-enhanced title
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF, TXT or read online on Scribd
Download now
Download
Save 5. Selection Statements For Later
Download
Save
Save 5. Selection Statements For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
245 views
Selection Statements
Uploaded by
yaazel
AI-enhanced title
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF, TXT or read online on Scribd
Download now
Download
Save 5. Selection Statements For Later
Carousel Previous
Carousel Next
Save
Save 5. Selection Statements For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 26
Search
Fullscreen
return statement 22 Selection Statements Programmers are not to be measured by their ingenuity and their logic but by the completeness of their case analysis. Although C has many operators, it has relatively few statements. We've encoun tered just two so far: the return statement and the expression statement. Most of C’s remaining statements fall into three categories, depending on how they affect the order in which statements are executed: = Selection statements. The if and switch statements allow a program to select a particular execution path from a set of alternatives. = Mteration statements. The while, do, and for statements support iteration (looping). = Jump statements. The break, continue, and goto statements cause an unconditional jump to some other place in the program. (The return state- ment belongs in this category, as well.) ‘The only other statements in C are the compound statement, which groups several statements into a single statement, and the null statement, which performs no action. ‘This chapter discusses the selection statements and the compound statement. (Chapter 6 covers the iteration statements, the jump statements, and the null state- ment.) Before we can write i£ statements, we'll need logical expressions: condi- tions that 4£ statements can test. Section 5.1 explains how logical expressions are built from the relational operators (<, <=, >, and >=), the equality operators ( and ! =), and the logical operators (&&, | |, and !). Section 5.2 covers the if state- ment and compound statement, as well as introducing the conditional operator (?:), which can test a condition expression. Section 5.3 describes the switch statement74 Chapter § Selection Statements 5.1 Table 5.1 Relational Operators Logical Expressions Several of C’s statements, including the i£ statement, must test the value of an expression to see if it is “true” or “false.” For example, an if statement might need to test the expression i < 3; a true value would indicate that i is less than j. In many programming languages, an expression such as i < } would have a special “Boolean” or “logical” type. Such a type would have only two values, false and true. In C, however, a comparison such as i < j yields an integer: either 0 (false) or | (true). With this in mind, let’s look at the operators that are used to build logi- cal expressions Relational Operators C's relational operators (Table 5.1) correspond to the <, >, S, and 2 operators of mathematics, except that they produce 0 (false) or 1 (true) when used in expres- sions. For example, the value of 10 < 11 is I; the value of 11 < 10 is 0. ‘Symbol Meaning < __lessthan > greater than <= less than or equal to >= greater than or equal to The relational operators can be used to compare integers and floating-point numbers, with operands of mixed types allowed. Thus, 1 < 2.5 has the value 1, while 5.6 < 4 has the value 0, ‘The precedence of the relational operators is lower than that of the arithmetic operators; for example, i + j < k-means (i +5) < (c- 1). The relational operators are left associative. ‘The expression ajo is legal in C, but doesn't have the meaning that you might expect. Since the < oper- ator is left associative, this expression is equivalent to (i
= j) + (1 == §) iseither 0, 1, or 2, depending on whether i is less than, greater than, or equal to 3, respectively. Tricky coding like this generally isn’t a good idea, how- ever; it makes programs hard to understand. Logical Operators More complicated logical expressions can be built from simpler ones by using the logical operators: and, or, and not (Table 5.3). The | operator is unary, while && and | | are binary. Symbol | Tegical negation | g& logical and [IL logical or The logical operators produce either 0 or 1 as their result. Often, the operands will have values of O or 1, but this isn’t a requirement; the logical operators treat any nonzero operand as a true value and any zero operand as a false value The logical operators behave as follows: m {expr has the value 1 if exprhas the value 0. = exprl && expr2 has the value 1 if the values of expr! and expr2 are both non- zer0.76 Chapter 5 Selection Statements 5.2 if statement = expr] | | expr2 has the value 1 if either expr! or expr2 (or both) has a nonzero value. In all other cases, these operators produce the value 0. Both && and | | perform “short-circuit” evaluation of their operands. That is, these operators first evaluate the left operand, then the right operand. If the value of the expression can be deduced from the value of the left operand alone, then the right operand isn’t evaluated. Consider the following expression: 0) && (j / i > 0) To find the value of this expression, we must first evaluate (i |= 0). If 4 isn’t equal to 0, then we'll need to evaluate (3 / i > 0) to determine whether the entire expression is true or false, However, if 4 is equal to 0, then the entire expression must be false, so there’s no need to evaluate (3 / i > 0). The advantage of short- circuit evaluation is apparent—without it, evaluating the expression would have caused a division by zero. Be wary of side effects in logical expressions. Thanks to the short-circuit nature of the && and | | operators, side effects in operands may not always occur, Consider the following expression: i> 0 & Hy >0 Although 3 is apparently incremented as a side effect of evaluating the expression, that isn’t always the case. If 4 > 0 is false, then ++ > 0 is not evaluated, so 3 isn't incremented. The problem can be fixed by changing the condition to ++4 > 0 && i > 0 or, even better, by incrementing j separately. ‘The | operator has the same precedence as the unary plus and minus opera- tors. The precedence of && and | | is lower than that of the relational and equality operators; for example, i < j && k == mmeans (i
= n) Note the use of the | | operator instead of the && operator, Compound Statements In our if statement template, notice that statement is singular, not plural: if ( expression ) statement What if we want an i£ statement to control vo or more statements? That's where the compound statement comes in. A compound statement has the form { statements} By putting braces around a group of statements, we can force the compiler to treat it as a single statement.78 Chapter 5 Selection Statements if statement with else clause Here's an example of a compound statement: { line num = 0; page_num++; } For clarity, I'll usually put a compound statement on several lines, with one state~ ment per line: { line_num page num++; } Notice that each inner statement still ends with a se statement itself does not. Here's what a compound statement would look like when used inside an if statement: on, but the compound if (1ine_num Line num page_num++; MAX_LINES) { Compound statements are also common in loops and other places where the syntax of C requires a single statement, but we want more than one, The else Clause An if statement may have an e1se clause: if ( expression ) statement else statement The statement that follows the word else is executed if the expression in paren- theses has the value 0, Here’s an example of an if statement with an else clause: if (i > 4) max else max 3 i ua Notice that both “inner” statements end with a semicolon. When an if statement contains an e1se clause, a layout issue arises: where should the else be placed? Many C programmers align the if at the beginning of the statement, as in the previous example, The inner statements are usually indented, but if they're short they can be put on the same line as the if and else: if (i > j) max = i; else max = 4;5.2 The if Statement 79 ‘There are no restrictions on what kind of statements can appear inside an if statement. In fact, it’s not unusual for if statements to be nested inside other if statements. Consider the following if statement, which finds the largest of the numbers stored in i, 3, and k and stores that value in max: ) if > j if (A> else else if > k) max = 4; else max an be nested to any depth. Notice how aligning each e1se with the matching i makes the nesting easier to see. If you still find the nesting confusing, don’t hesitate to add braces: 18 seni. if (i> k max = i; else max = k; } else { if (>) max = 4; else max = k; } Adding braces to statements—even when they're not necessary—is like using parentheses in expressions: both techniques help make a program more readable while at the same time avoiding the possibility that the compiler won’t understand the program the way we thought it did. Some programmers use as many braces as possible inside if statements (and iteration statements as well). A programmer who adopts this convention would include a pair of braces for every if clause and every else clause: if (2 > 9) { if (i> k) { max = i; } else ( max = k; } elae { ig GG >) { max = 47 } else { max = k } }80 Chapter Selection Statements Using braces even when they're not required has two advantages. First, the pro- gram becomes easier to modify, because more statements can easily be added to any if or else clause. Second, it helps avoid errors that can result from forget- ting to use braces when adding statements to an if or else clause, Cascaded if Statements We'll often need to test a series of conditions, stopping as soon as one of them is, true. A “cascaded” if statement is often the best way to write such a series of tests. For example, the following cascaded if statement tests whether n is less than 0, equal to 0, or greater than 0: if (n < 0) printf£("n is less than 0\n"); else if (n == 0) printf ("n is equal to 0\n"); else printf ("n is greater than 0\n"); Although the second i statement is nested inside the first, C programmers don’t usually indent it, Instead, they align cach e1se with the original if: if (n < 0) printf("n is less than 0\n"); else if (n == 0) printé("n is equal to 0\n" else printf("n is greater than 0\n"); This arrangement gives the cascaded if a distinctive appearance: if ( expression ) ‘statement else if ( expression ) ‘Statement else if ( expression ) Statement else statement ‘The last two lines (¢1se statement) aren’t always present, of course, This way of indenting the cascaded if statement avoids the problem of excessive indentation when the number of tests is large. Moreover, it assures the reader that the statement is nothing more than a series of tests. Keep in mind that a cascaded if statement isn’t some new kind of statement; it’s just an ordinary i£ statement that happens to have another if statement as its else clause (and that if statement has another if statement as its else clause, ad infinitum).PROGRAM 5.2 The if Statement 81 Calculating a Broker’s Commission When stocks are sold or purchased through a broker, the broker’s commission is often computed using a sliding scale that depends upon the value of the stocks traded. Let's say that a broker charges the amounts shown in the following table: Transaction size Commission rate Under $2,500 $30 + 1.7% $2,500-$6,250 $56 + 0.66% $6,250-$20,000 $76 + 0.34% $20,000-$50,000 $100 + 0.22% $50,000-$500,000 $155 +0.11% Over $500,000 $255 + 0.09% ‘The minimum charge is $39. Our next program asks the user to enter the amount of the trade, then displays the amount of the commission: Enter value of trade: 30000 Commission: $166.00 The heart of the program is a cascaded if statement that determines which range the trade falls into. /* Calculates a broker's commission */ #include
int main(void) { float commission, value; printf ("Enter value of trade: "); scanf("$E", gvalue) ; if (value < 2500. 00£) commission = 30.00f + .017£ * value; else if (value < 6250.00f) commission = 56.00£ + .0066£ * value; else if (value < 20000.00f) commission = 76.00f + .0034£ * value; else if (value < 50000.00£) commission = 100.00f + .0022f * value; else if (value < 500000. 00f) commission = 155.00f + .0011f * value; else commission = 255.00f + .0009f * value; if (commission < 39.00£) commission = 39.00£; printé("Commission: $%.2£\n", commission) ; return 0;82 Chapter Selection Statements The cascaded if statement could have been written this way instead (the changes are indicated in bold): if (value < 2500.00£) commission = 30.00f + .017f * value; else if (value >= 2500.00f && value < 6250.00) commission = 56.00f + .0066f * value; else if (value >= 6250.00f s& value < 20000.00f) commission = 76.00£ + .0034£ * value; Although the program will still work, the added conditions aren't necessary. For example, the first i£ clause tests whether value is less than 2500 and, if so, com- putes the commission. When we reach the second if test (value >= 2500.00f && value < 6250.00£), we know that value can't be less than 2500 and therefore must be greater than or equal to 2500. The condition value >= 2500. 00¢ will always be true, so there’s no point in checking it. The “Dangling else” Problem When i£ statements are nested, we've got to watch out for the notorious “dangling e1se” problem. Consider the following example: if (y I= 0) if (x t= 0) result = x / y: else printf("Error: y is equal to 0\n"); ‘To which if statement does the else clause belong? The indentation suggests that it belongs to the outer 4 statement. However, C follows the rule that an else clause belongs to the nearest 4 £ statement that hasn’t already been paired with an else. In this example, the ese clause actually belongs to the inner if state- ment, so a correctly indented version would look like this: if (y t= 0) if (x f= 0) result = x / y; else printf("Error: y is equal to 0\n"); To make the e1se clause part of the outer if statement, we can enclose the inner if statement in braces: if ly t= 0) { if (x t= 0) result = x / yi } else printf("Error: y is equal to 0\n"); This example illustrates the value of braces; if we'd used them in the original if statement, we wouldn’t have gotten into this situation in the first place.conditional expression 5.2 The if Statement 83 Conditional Expressions C’s i£ statement allows a program to perform one of two actions depending on the value of a condition. C also provides an operator that allows an expression to pro- duce one of two values depending on the value of a condition. ‘The conditional operator consists of two symbols (? and :), which must be used together in the following way: exprl 2 expr2 + expr3 exprl, expr2, and expr3 can be expressions of any type. The resulting expression is said to be a conditional expression. The conditional operator is unique among C operators in that it requires three operands instead of one or two. For this reason, it is often referred to as a ternary operator. The conditional expression expr ? expr2 : expr3 should be read “if expri then expr? else expr3.” The expression is evaluated in stages: expr! is evaluated first; if its value isn’t zero, then expr2 is evaluated, and its value is the value of the entire conditional expression. If the value of expr/ is zero, then the value of expr3 is the value of the conditional. The following example illustrates the conditional operator: one ey eke ale /* k is now 2 */ i: 0) +4; /* k is now 3 */ i i k x ‘The conditional expression i > j ? 4 : J im the first assignment to k returns the value of either i or j, depending on which one is larger. Since i has the value 1 and 3 has the value 2, the 4 > j comparison fails, and the value of the conditional is 2, which is assigned to k. In the second assignment to k, the i >= 0 comparison succeeds; the conditional expression (i >= 0 ? i : 0) has the value 1, which is then added to j to produce 3. The parentheses are necessary, by the way; the prece- dence of the conditional operator is less than that of the other operators we've dis- cussed so far, with the exception of the assignment operators. Conditional expressions tend to make programs shorter but harder to under- stand, so it's probably best to avoid them. There are, however, a few places in which they're tempting; one is the return statement. Instead of writing cae return i; else return jj; many programmers would write returni>j?i:j84 Chapter 5 Selection Statements macro dtnivons > 14.3 Calls of print £ can sometimes benefit from condition expressions. Instead of if (i > 4) print£("td\n", i); else printé("sd\n", 4); ‘we could simply write printe("sd\n", 4 > 424: 9); Conditional expressions are also common in certain kinds of macro definitions. Boolean Values in C89 For many years, the C language lacked a proper Boolean type, and there is none defined in the C89 standard. This omission is a minor annoyance, since many pro- grams need variables that can store either false or true. One way to work around this limitation of C89 is to declare an int. variable and then assign it either 0 or 1: int flag; flag ay flag Although this scheme works, it doesn’t contribute much to program readability. It's not obvious that £1ag is to be assigned only Boolean values and that 0 and | represent false and true, To make programs more understandable, C89 programmers often define mac- ros with names such as TRUE and FALSE: define TRUE 1 iidefine FALSE 0 Assignments to £1ag now have a more natural appearance: flag = FALSE; flag = TRUE; To test whether £1ag is true, we can write if (flag TRUE) . or just if (flag) .. ‘The latter form is better, not only because it’s more concise, but also because it will still work correctly if f1ag has a value other than 0 or 1. ‘To test whether £1ag is false, we can write if (flag == FALSE) ..‘ype detniions »75 ‘eumerations > 165 unsigned integer types > 71 ‘estdbool i> header > 215 5.2 Theif Statement 85 or if (Iflag) . Carrying this idea one step further, we might even define a macro that can be used as a type: #define BOOL int BOOL can take the place of int when declaring Boolean variables: BOOL flag; It’s now clear that £1ag isn't an ordinary integer variable, but instead represents a Boolean condition. (The compiler still treats £1ag as an int variable, of course.) In later chapters, we'll discover better ways to set up a Boolean type in C89 by using type definitions and enumerations. Boolean Values in C99 ‘The longstanding lack of a Boolean type has been remedied in C99, which pro- vides the Bool type. In this version of C, a Boolean variable can be declared by writing _Bool flag; _Bool is an integer type (more precisely, an unsigned integer type), so a _ Bool variable is really just an integer variable in disguise. Unlike an ordinary Integer variable, however, a_Boo1 variable can only be assigned 0 or 1. In gen- eral, attempting to store a nonzero value into a_Bool variable will cause the vari- able to be assigned 1: flag - 5; /* flag is assigned 1 */ It’s legal (although not advisable) to perform arithmetic on _Boo variables; it’s also legal to print a Bool variable (either 0 or 1 will be displayed). And, of ‘course, a_Bool variable can be tested in an if statement: if (flag) /* tests whether flag is 1 */ In addition to defining the _Bool type, C99 also provides a new header,
, that makes it easier to work with Boolean values. This header provides a macro, bool, that stands for Bool. If
is included, we can write bool flag; /* same as _Bool flag; */ The
header also supplies macros named true and false, which stand for 1 and 0, respectively, making it possible to write86 Chapter 5 Selection Statements 5.3 break statement >6.4 flag = false; flag = true; Because the
header is so handy, I'll use it in subsequent programs whenever Boolean variables are needed. The switch Statement In everyday programming, we'll often need to compare an expression against a series of values to see which one it currently matches. We saw in Section 5.2 that a cascaded ££ statement can be used for this purpose. For example, the following cascaded if statement prints the English word that corresponds to a numerical grade: if (grade == 4) printé ("Excellent"); else if (grade == 3) printf ("Good") ; else if (grade printé ("Average’ else if (grade printf ("Poor") ; else if (grade printé ("Failing else printf ("Illegal grade"); 2) 33 As an alternative to this kind of cascaded if statement, C provides the switch statement. The following switch is equivalent to our cascaded if: switch (grade) { case 4: print£(*Excellent"); breal case 3: printf ("Good"); break; case 2: printf ("Average") ; break; case 1: printf ("Poor"); break; case 0: printf ("Failing") ; break; default: printf ("Illegal grade"); break; } When this statement is executed, the value of the variable grade is tested against 4, 3, 2, 1, and 0. If it matches 4, for example, the message Excelent is printed, then the break statement transfers control to the statement following the switch, If the value of grade doesn’t match any of the choices listed, the default case applies, and the message 11. 1egal grade is printed.switch statement characters »7.9 5.3 The switch Statement 87 A switch statement is often easier to read than a cascaded it statement. Moreover, switch statements are often faster than if statements, especially when there are more than a handful of cases. In its most common form, the switch statement has the form switch ( expression ) { case constant-expression : statements case constantexpression : statements default : statements ‘The switch statement is fairly complex; let’s look at its components one by one: = Controlling expression. The word switch must be followed by an integer expression in parentheses. Characters are treated as integers in C and thus ean be tested in switch statements, Floating-point numbers and strings don’t qualify, however. = Case labels, Each case begins with a label of the form case constant-expression : A constant expression is much like an ordinary expression except that it can’t contain variables or function calls. Thus, 5 is a constant expression, and 5 + 10 is a constant expression, but n + 10 isn’t a constant expression (unless n is a macro that represents a constant). The constant expression in a case label ‘must evaluate to an integer (characters are also acceptable), = Statements, After cach case label comes any number of statements. No braces are required around the statements. (Enjoy it—this is one of the few places in C where braces aren’t required.) The last statement in each group is normally break. Duplicate case labels aren’t allowed. The order of the cases doesn’t matter; in par- ticular, the default case doesn’t need to come last. Only one constant expression may follow the word case; however, several case labels may precede the same group of statements: switch (grade) { case 4: case 3 case 2 case 1: printf(*Passing") ; break; case 0: print£("Failing") ; break; default: printf ("Illegal grade") ; break;88 Chapter 5 Selection Statements To save space, programmers sometimes put several case labels on the same line: switch (grade) { case 4: case 3: case 2: case 1: printé ("Passing"); break; case 0: print£ ("Failing"); break; default: printf ("Illegal grade") ; break; } Unfortunately, there’s no way to write a case label that specifies a range of values, as there is in some programming languages. ‘A switch statement isn’t required to have a default case. If default is missing and the value of the controlling expression doesn’t match any of the case labels, control simply passes to the next statement after the switch. The Role of the break Statement Now, let’s take a closer look at the mysterious break statement. As we've seen, executing a break statement causes the program to “break” out of the switch statement; execution continues at the next statement after the switch. ‘The reason that we need break has to do with the fact that the switch state- ment is really a form of “computed jump.” When the controlling expression is evaluated, control jumps to the case label matching the value of the switch expression. A case label is nothing more than a marker indicating a position within the switch, When the last statement in the case has been executed, control “falls through” to the first statement in the following case; the case label for the next case is ignored. Without break (or some other jump statement), control will flow from one case into the next. Consider the following switch statement switch (grade) { case 4: printf (*Excellent"); case 3: printf ("Good") ; case 2: print£ ("Average"); case 1: printf ("Poor") ; case 0: printf ("Failing"); default: printf ("Illegal grade"); } If the value of grade is 3, the message printed is GoodAveragePoorFailingillegal grade j\ Forgetting to use break is a common error. Although omitting break is some- times done intentionally to allow several cases to share code, it’s usually just an oversight.PROGRAM date.c 5.3. The switch Statement 89 Since deliberately falling through from one case into the next is rare, it’s a good idea to point out any deliberate omission of break: switch (grade) { case 4: case 3: case 2: case 1: num_passing++; /* FALL THROUGH */ case 0: total_grades++; breal } Without the comment, someone might later fix the “error” by adding an unwanted break statement. Although the last case in a switch statement never needs a break state- ment, it’s common practice to put one there anyway to guard against a “missing break” problem if cases should later be added. Printing a Date in Legal Form Contracts and other legal documents are often dated in the following way: Dated this day of palais Let’s write a program that displays dates in this form. We'll have the user enter the date in month/day/year form, then we'll display the date in “legal” form: Enter date (mm/dd/yy): 7/19/14 Dated this 19th day of July, 2014. We can get printé to do most of the formatting. However, we're left with two problems: how to add “th” (or “st” or “nd” or “rd”) to the day, and how to print the month as a word instead of a number, Fortunately, the switch statement is ideal for both situations; we'll have one switch print the day suffix and another print the month name. /* Prints a date in legal form */ #include
int main (void) { int month, day, year; printf ("Enter date (mm/dd/yy): "); scanf ("sd /%d /%a", Smonth, &day, gyear); printf ("Dated this a", day); switch (day) { case 1: case 21: case 31 printf ("st"); break; case 2: case 22: printf ("nd"); break;90 ChapterS Selection Statements case 3: case 23: printé ("rd"); break; default: print£("th"); break; print£(" day of "); switch (month) { case 1: printf("January"); break; case 2: printf ("February"); break; case 3: printf ("March"); break; case 4: printf ("april"); break; case 5: printf ("May"); break; case 6: printf("June"); break; case 7: print£(*July"); break; case 8: printf("August"); break; case $: printf ("September") ; break; case 10: print£("October"); break; case 11: printf ("November"); break; case 12: printf("December"); break; } printf(", 20%.2d.\n", year); return 0; } 4d instead, single-digit years would be displayed incorrectly (2005 would be Note the use of % . 2d to display the last two digits of the year. If we had used | printed as 205). My compiler doesn’t give a warning when I use = instead of ==. Is there some way to force the compiler to notice the problem? [p. 77] Here’s a trick that some programmers use: instead of writing Q&A | ; | if (iam 0) ~ they habitually write if (0 == i) . Now suppose that the == operator is accidentally written as =: ££e(0 ad. The compiler will produce an error message, since it’s not possible to assign a value to 0. I don’t use this trick, because I think it makes programs look unnatural. Also, it can be used only when one of the operands in the test condition isn’t an Ialue. Fortunately, many compilers are capable of checking for suspect uses of the = operator in if conditions. The GCC compiler, for example, will perform thisQ&A 91 check if the -Wparentheses option is used or if -Wall (all warnings) is selected. GCC allows the programmer to suppress the warning in a particular case by enclosing the i £ condition in a second set of parentheses: Be 0G 499) on C books seem to use several different styles of indentation and brace place- ment for compound statements. Which style is best? According to The New Hacker's Dictionary (Cambridge, Mass.: MIT Press, 1996), there are four common styles of indentation and brace placement: = The K&R style, used in Kernighan and Ritchie's The C Programming Lan- guage, is the one I've chosen for the programs in this book. In the K&R style, the left brace appears at the end of a line: if (line num MAX_LINES) { line_num = 0; page_num++; The K&R style keeps programs compact by not putting the left brace on a line by itself. A disadvantage: the left brace can be hard to find. (I don’t consider this a problem, since the indentation of the inner statements makes it clear where the left brace should be.) The K&R style is the one most often used in Java, by the way. = The Allman style, named after Eric Allman (the author of sendmail and other UNIX utilities), puts the left brace on a separate line: if (1ine_num == MAX_LINES) { line_num = 0; page_num++; This style makes it easy to check that braces come in matching pairs. = The Whitesmiths style, popularized by the Whitesmiths C compiler, dictates that braces be indented: if (Line_mum { line_num = 0; page_num++; } = The GNU style, used in software developed by the GNU Project, indents the braces, then further indents the inner statements: MAX_LINES) if (line num == MAX_LINES) { line_num = 0; page_num++;92 Chapter 5 Selection Statements labels >6 Which style you use is mainly a matter of taste; there’s no proof that one style is clearly better than the others. In any event, choosing the right style is less impor- tant than applying it consistently. If i isan int variable and £ is a £1oat variable, what is the type of the con- ditional expression (4 > 0? 4: £)? When int and float values are mixed in a conditional expression, as they are here, the expression has type float. If i > 0 is true, the value of the expression will be the value of i after conversion to £loat type. Why doesn’t C99 haye a better name for its Boolean type? [p. 85] _Bool isn’t a very elegant name, is it? More common names, such as bool or boolean, weren't chosen because existing C programs might already define these names, causing older code not to compile. OK, so why wouldn't the name _Boo1 break older programs as well? The C89 standard specifies that names beginning with an underscore followed by aan uppercase letter are reserved for future use and should not be used by program- mers. The template given for the switch statement described it as the “most com- mon form.” Are there other forms? [p. 87] The switch statement is a bit more general than described in this chapter, although the description given here is general enough for virtually all programs. For example, a switch statement can contain labels that aren’t preceded by the word case, which leads to an amusing (?) trap. Suppose that we accidentally mis- spell the word default: switch (..) { defualt: } ‘The compiler may not detect the error, since it assumes that defualt is an ordi- nary label, I’ve seen several methods of indenting the switch statement. Which way is best? ‘There are at least two common methods. One is to put the statements in each case: after the case label: switch (coin) { case printf ("Cent") ; break; case 5: printf ("Nickel"); break; case 10: printf ("Dime") ; break;Section 5.1 Exercises 93 case 25: printf ("Quarter") ; break; } If each case consists of a single action (a call of print, in this example), the break statement could eyen go on the same line as the action: switch (coin) { case 1: print£(*"Cent"); break; case 5: printf ("Nickel"); break; case 10; printf ("Dime"); break; case 25: printf ("Quarter"); break; The other method is to put the statements under the case label, indenting the statements to make the case label stand out: switch (coin) { case 1: printf ("Cent") ; break; case 5 printf ("Nickel"); break; case 10 printé ("Dime") ; break; case 25 printf ("Quarter") ; break; } In one variation of this scheme, each case label is aligned under the word switch. The first method is fine when the statements in each case are short and there are relatively few of them. The second method is better for large switch state- ‘ments in which the statements in each case are complex and/or numerous. Exercises ‘The following program fragments illustrate the relational and equality operators. Show the output produced by each, assuming that i, j, and k are int variables. @) i= 2; 4 23; keitj == 6; printé("#d", k); (b) i= 5; j = 10; k = 1; printé("td", k > i < 4); i= 3: 4-2; k=2 printé("ta", i
= 1 <= 10) print£("n is between 1 and 10\n"); If so, what does it do when n is equal to 0? Is the following 4 statement legal? if (n == 1-10) printf ("n is between 1 and 10\n"); If so, what does it do when n is equal to 5? ‘What does the following statement print if + has the value 172 What does it print if 3 has the value -17? printé("$d\n", i >= 0 24: -i); The following i£ statement is unnecessarily complicated. Simplify it as much as possible. (Hint: The entire statement can be replaced by a single assignment.) if (age >= 13) if (age <= 19) teenager = true; else teenager = false; else if (age < 13) teenager = false;Section 5.3 O10. Programming Projects 95 Are the following i£ statements equivalent? If not, why not? if (score >= 90) if (score < 60) printé ("A") ; printt("F") ; else if (score >= 80) else if (score < 70) printé("B") ; printé("D") ; else if (score >= 70) else if (score < 80) print£("C") ; printf ("Cc"); else if (score >= 60) else if (score < 90) printf (*D") ; printé("B") ; else else print é ("F") ; printé ("A"); What output docs the following program fragment produce? (Assume that 4 i variable.) an integer ina switch (i % 3) { case 0: printf ("zero") ; case 1: print€("one") ; case 2: printf ("two"); 3 The following table shows telephone area codes in the state of Georgia along with the larg- est city in each area: Area code Major city 229 Albany 404 Atlanta 470 Atlanta 478 Macon 678, Allanta 706 Columbus: 162 Columbus. 710 Atlanta 912 ‘Savannah Write a switch statement whose controlling expression is the variable area_code. If the value of area_code is in the table, the switch statement will print the corresponding city name, Otherwise, the switch statement will display the message "Area code not recognized". Use the techniques discussed in Section 5.3 to make the switch state- ‘ment as simple as possible, Programming Projects Write a program that calculates how many digits a number contains: Enter a number: 374 The number 374 has 3 digits You may assume that the number has no more than four digits. Hint: Use if statements to test the number. For example, if the number is between 0 and 9, it has one digit. Ifthe num- ber is between 10 and 99, it has two digits.96 Chapter 5 Selection Statements @ 2 Write a program that asks the user for a 24-hour time, then displays the time in 12-hour form: Enter a 24-hour time: 2 Equivalent 12-hour time: 9: Be careful not to display 12:00 as 0:00. Modify the broker .¢ program of Section 5.2 by making both of the following changes: (a) Ask the user to enter the number of shares and the price per share, instead of the value of the trade. (b) Add statements that compute the commission charged by a rival broker ($33 plus 3¢ per share for fewer than 2000 shares; $33 plus 2¢ per share for 2000 shares or more). Dis- play the rival's commission as well as the commission charged by the original broker. Here’s a simplified version of the Beaufort scale, which is used to estimate wind force: Speed (knots) Description Less than 1 Calm 13 Light air 4.27 Breeze. 28-47 Gale 48-63 Storm Above 63 Hurricane Write a program that asks the user to enter a wind speed (in knots), then displays the corre: sponding description. In one state, single residents are subject to the following income tax: Income Amount of tax Not over $750 1% of income $750-$2,250 $7.50 plus 2% of amount over $750 $2,250-83,750 $37.50 plus 3% of amount over $2,250 $3.750-$5,250 $82.50 plus 4% of amount over $3,750 $5,250-$7,000 $142.50 plus 5% of amount over $5,250 Over $7,000 $230.00 plus 6% of amount over $7,000 ‘Write a program that asks the user to enter the amount of taxable income, then displays the tax due, Modify the upc. c program of Section 4.1 so that it checks whether a UPC is valid. After the user enters a UPC, the program will display either VALID or NOT VALID. ‘Write a program that finds the largest and smallest of four integers entered by the user: Enter four integers: 21 43 10 35 Largest: 43 Smallest: 10 Use as few i£ statements as possible. Hint: Four if statements are sufficient. ‘The following table shows the daily flights from one city to another: Departure time Arrival time 8:00 a.m. 10:16 a.m. 9:43 a.m. 11:52am. 11:19 a.m, 12:47 pm.© 10. in Programming Projects 97 ‘Write a program that asks user to enter a time (expressed in hours and minutes, using the 24- hour clock). The program then displays the departure and arrival times for the flight whose departure time is closest to that entered by the user: Enter a 24-hour time: 2 Closest departure time is 12:47 p.m., arriving at 3:00 p.m. Hint; Convert the input into a time expressed in minutes since midnight, and compare it to the departure times, also expressed in minutes since midnight. For example, 13:15 is 13 x 60+ 15 = 795 minutes since midnight, which is closer to 12:47 p.m, (767 minutes since midnight) than to any of the other departure times. Write a program that prompts the user to enter two dates and then indicates which date comes earlier on the calendar: Enter first date (mm/dd/yy): 3/6/08 Enter second date (mm/dd/yy): 5/17/07 5/17/07 is earlier than 3/6/08 Using the switch statement, write @ program that converts a numerical grade into a letter grade: Enter numerical grade: a4 Letter grade: B Use the following grading scale: A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59. Print an error message if the grade is larger than 100 or less than 0. Hint: Break the grade into two digits, then use a switch statement to test the ten’s digit. Write a program that asks the user for a two-digit number, then prints the English word for the number: Enter a two-digit number: 45 You entered the number forty-five. Hint; Break the number into two digits, Use one switch statement to print the word for the first digit (*twenty.” “thirty,” and so forth), Use a second switch statement to print the word for the second digit. Don’t forget that the numbers between 11 and 19 require special treatment.
You might also like
Algebra Driven Design Elegant Software From Simple Building Blocks (Sandy Maguire)
PDF
No ratings yet
Algebra Driven Design Elegant Software From Simple Building Blocks (Sandy Maguire)
337 pages
C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1
PDF
100% (65)
C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1
120 pages
Learning Sap Abap
PDF
No ratings yet
Learning Sap Abap
42 pages
Richard L. Epstein, Walter A Carnielli - Computability - Computable Functions, Logic, and The Foundations of Mathematics-Advanced Reasoning Forum (2008)
PDF
100% (1)
Richard L. Epstein, Walter A Carnielli - Computability - Computable Functions, Logic, and The Foundations of Mathematics-Advanced Reasoning Forum (2008)
377 pages
Unit 18 Discrete Maths Assignment Brief Part 2
PDF
No ratings yet
Unit 18 Discrete Maths Assignment Brief Part 2
18 pages
Algebra Driven Design Sample
PDF
No ratings yet
Algebra Driven Design Sample
85 pages
Pseudocode Guide For Teachers: Cambridge International AS & A Level Computer Science 9618
PDF
No ratings yet
Pseudocode Guide For Teachers: Cambridge International AS & A Level Computer Science 9618
28 pages
JPR Lec 5
PDF
No ratings yet
JPR Lec 5
14 pages
My Note 1 Cat 12
PDF
No ratings yet
My Note 1 Cat 12
10 pages
Unit 2 Notes Python Operators and Control Flow Statements Part 1
PDF
No ratings yet
Unit 2 Notes Python Operators and Control Flow Statements Part 1
25 pages
Unit 1 - Boolean Algebra
PDF
No ratings yet
Unit 1 - Boolean Algebra
28 pages
DocScanner 14-Dec-2024 2-23 pm
PDF
No ratings yet
DocScanner 14-Dec-2024 2-23 pm
24 pages
Python Assignment
PDF
No ratings yet
Python Assignment
19 pages
Boolean Logic
PDF
No ratings yet
Boolean Logic
25 pages
Gate 2006 It
PDF
No ratings yet
Gate 2006 It
14 pages
5 RTL Verilog Behavioral Assign
PDF
No ratings yet
5 RTL Verilog Behavioral Assign
23 pages
Operators 140917230056 Phpapp01
PDF
No ratings yet
Operators 140917230056 Phpapp01
20 pages
"Boolean Algebra and Its Application": Master of Science
PDF
100% (1)
"Boolean Algebra and Its Application": Master of Science
52 pages
Boolean Algebra Lesson
PDF
No ratings yet
Boolean Algebra Lesson
18 pages
Lecture1 Chapter2 - Introduction To Boolean Algebra, Boolean Functions
PDF
No ratings yet
Lecture1 Chapter2 - Introduction To Boolean Algebra, Boolean Functions
34 pages
Module 2 Part 1
PDF
No ratings yet
Module 2 Part 1
13 pages
DIGITAL_CIRCUITS_AND_SYSTEMS
PDF
No ratings yet
DIGITAL_CIRCUITS_AND_SYSTEMS
53 pages
Module 2 - Operators in C, Type Conversion and Typecasting
PDF
No ratings yet
Module 2 - Operators in C, Type Conversion and Typecasting
22 pages
Discreet Structure
PDF
No ratings yet
Discreet Structure
39 pages
GATE1998
PDF
No ratings yet
GATE1998
8 pages
Gate 2008 It
PDF
No ratings yet
Gate 2008 It
12 pages
Logic and Discrete Mathematics
PDF
No ratings yet
Logic and Discrete Mathematics
140 pages
Lecture 6
PDF
No ratings yet
Lecture 6
19 pages
Lecture 7
PDF
No ratings yet
Lecture 7
19 pages
Logic Circuit Design: Boolean Algebra
PDF
No ratings yet
Logic Circuit Design: Boolean Algebra
18 pages
BCS302 Module1 and 2 ppt
PDF
No ratings yet
BCS302 Module1 and 2 ppt
69 pages
DSD Boolean Algebra and Logic Gates
PDF
No ratings yet
DSD Boolean Algebra and Logic Gates
45 pages
2 Boolean Algebra and Logic Gates - 240603 - 112944
PDF
No ratings yet
2 Boolean Algebra and Logic Gates - 240603 - 112944
53 pages
On Boolean Algebra and Rings - Bryant, O'Hallaron
PDF
No ratings yet
On Boolean Algebra and Rings - Bryant, O'Hallaron
6 pages
Useful Functions Listed by Category.: - Arithmetic Types
PDF
No ratings yet
Useful Functions Listed by Category.: - Arithmetic Types
16 pages
Mod1-DM
PDF
No ratings yet
Mod1-DM
7 pages
GATE1996
PDF
No ratings yet
GATE1996
10 pages
PPL Unit 5-1
PDF
No ratings yet
PPL Unit 5-1
33 pages
DDC Chap 2 TB
PDF
No ratings yet
DDC Chap 2 TB
38 pages
PPS Notes Unit-II
PDF
No ratings yet
PPS Notes Unit-II
41 pages
OPERATORS Dsoft
PDF
No ratings yet
OPERATORS Dsoft
14 pages
DLD Presentation 1
PDF
No ratings yet
DLD Presentation 1
24 pages
Module 2 and 3
PDF
No ratings yet
Module 2 and 3
51 pages
EECS150 - Digital Design: Lecture 6 - Boolean Algebra I
PDF
No ratings yet
EECS150 - Digital Design: Lecture 6 - Boolean Algebra I
20 pages
Digital Logic and Design (BOOLEAN ALGEBRA)
PDF
No ratings yet
Digital Logic and Design (BOOLEAN ALGEBRA)
4 pages
Adobe Scan 10 Dec 2024
PDF
No ratings yet
Adobe Scan 10 Dec 2024
9 pages
Digital Logic Design (R17a0461)
PDF
No ratings yet
Digital Logic Design (R17a0461)
93 pages
Ade Unit-Iv
PDF
No ratings yet
Ade Unit-Iv
46 pages
Imgtopdf 0302221148045
PDF
No ratings yet
Imgtopdf 0302221148045
18 pages
Lecture 3
PDF
No ratings yet
Lecture 3
16 pages
MCA-VTU QP-June-July-2023 JOINTTTTTTTTTTT
PDF
No ratings yet
MCA-VTU QP-June-July-2023 JOINTTTTTTTTTTT
43 pages
Module-3-INTEGRATIVE PROGRAMMING 2
PDF
No ratings yet
Module-3-INTEGRATIVE PROGRAMMING 2
5 pages
Boolean Algebra & Logic Gates
PDF
No ratings yet
Boolean Algebra & Logic Gates
45 pages
04-BooleanLogic
PDF
No ratings yet
04-BooleanLogic
26 pages
Toc Recursive Function Theory
PDF
100% (1)
Toc Recursive Function Theory
83 pages
Lesson 12 Truth Tables
PDF
No ratings yet
Lesson 12 Truth Tables
11 pages
Python Operators (Slideshare)
PDF
No ratings yet
Python Operators (Slideshare)
43 pages
Boolean Algebra - 2
PDF
No ratings yet
Boolean Algebra - 2
12 pages
Expressions, Operators, and Operands
PDF
No ratings yet
Expressions, Operators, and Operands
11 pages
Isc Specimen Paper Computer Science Paper 1 (Theory)
PDF
No ratings yet
Isc Specimen Paper Computer Science Paper 1 (Theory)
7 pages
My First Book Arabic Words: An ABC Rhyming Book of Arabic Language and Culture
From Everand
My First Book Arabic Words: An ABC Rhyming Book of Arabic Language and Culture
Aya Khalil
No ratings yet
Lectures on the Coupling Method
From Everand
Lectures on the Coupling Method
Torgny Lindvall
No ratings yet
Infinite Series
From Everand
Infinite Series
Isidore Isaac Hirschman
4/5 (1)
Statistical Abstract of Andhra Pradesh 2007
PDF
No ratings yet
Statistical Abstract of Andhra Pradesh 2007
628 pages
Important Environment Notes From Wikipedia Ecosystem Services
PDF
No ratings yet
Important Environment Notes From Wikipedia Ecosystem Services
24 pages
CLAT Solved Paper 2014 PDF
PDF
No ratings yet
CLAT Solved Paper 2014 PDF
39 pages
CLAT 2013 Sample Paper
PDF
No ratings yet
CLAT 2013 Sample Paper
41 pages
Tehsildar 4 - 1 - B - Eng
PDF
100% (1)
Tehsildar 4 - 1 - B - Eng
22 pages
Teracom Brochure Videos
PDF
No ratings yet
Teracom Brochure Videos
14 pages
CBSE Psychology Class XII
PDF
No ratings yet
CBSE Psychology Class XII
21 pages
China Reform 20
PDF
No ratings yet
China Reform 20
1 page
Microsoft Excel Features Presentation
PDF
No ratings yet
Microsoft Excel Features Presentation
75 pages
Pro Program
PDF
100% (2)
Pro Program
27 pages
Roadmap To Python
PDF
No ratings yet
Roadmap To Python
19 pages
Java Programming
PDF
No ratings yet
Java Programming
57 pages
Kuliah03-Unsur-Unsur Algoritma
PDF
No ratings yet
Kuliah03-Unsur-Unsur Algoritma
25 pages
Standard: X: Chapter 8: PYTHON REVISION
PDF
No ratings yet
Standard: X: Chapter 8: PYTHON REVISION
10 pages
Chapter 3 - Fundamentals of Programming Language
PDF
No ratings yet
Chapter 3 - Fundamentals of Programming Language
106 pages
COM 411 Web Dev Using PHP Part-1
PDF
No ratings yet
COM 411 Web Dev Using PHP Part-1
36 pages
FeatureCAM Post Processor Reference Manual
PDF
100% (1)
FeatureCAM Post Processor Reference Manual
41 pages
DesignScript Summary User Manual
PDF
No ratings yet
DesignScript Summary User Manual
20 pages
Python Imp
PDF
No ratings yet
Python Imp
44 pages
Algorithms, Flowcharts, Data Types and Pseudocode
PDF
No ratings yet
Algorithms, Flowcharts, Data Types and Pseudocode
49 pages
Computational Thinking Week 7
PDF
No ratings yet
Computational Thinking Week 7
36 pages
VB Question Paper Solved
PDF
77% (22)
VB Question Paper Solved
7 pages
Variables, Data Types, Statements, Operators, Loops
PDF
No ratings yet
Variables, Data Types, Statements, Operators, Loops
59 pages
Conditional Control Structure Chap - 04 - Class - 10
PDF
No ratings yet
Conditional Control Structure Chap - 04 - Class - 10
18 pages
Ilogic Best Practices - Class Handout
PDF
No ratings yet
Ilogic Best Practices - Class Handout
21 pages
Halfyearly CS Syllabus
PDF
No ratings yet
Halfyearly CS Syllabus
2 pages
Excel For Accountants
PDF
100% (1)
Excel For Accountants
63 pages
WWW Pascal Programming Info Lesson5 PHP
PDF
No ratings yet
WWW Pascal Programming Info Lesson5 PHP
12 pages
Instant Download COBOL Programmers Swing with Java 2nd Edition E. Reed Doke PDF All Chapters
PDF
No ratings yet
Instant Download COBOL Programmers Swing with Java 2nd Edition E. Reed Doke PDF All Chapters
51 pages
chapter 3 flow control
PDF
No ratings yet
chapter 3 flow control
23 pages
Cognos Analytics 11.1 Online Training Course
PDF
No ratings yet
Cognos Analytics 11.1 Online Training Course
5 pages
IT112
PDF
No ratings yet
IT112
5 pages
Programming Guidelines
PDF
No ratings yet
Programming Guidelines
10 pages
Basics of C
PDF
No ratings yet
Basics of C
50 pages
Phase 1: Creating A Program: Editor Program Editor Source Code
PDF
No ratings yet
Phase 1: Creating A Program: Editor Program Editor Source Code
9 pages
Documents
Teaching Methods & Materials
Mathematics