4 Approved
Transcription
4 Approved
4 C P rogram Control Sample solved questions from the text book. d e v Solve them before Exam -1. o r p p These questions and answers are supported by author and not by the instructor: Prof. Yahia Halabi - PSUT. A I selected solutions to practice my student to help them, in addition to my lectures. Thanks too, to Pearson Education Inc. publishing company. Self-Review Exercises 4.1 4.2 4.3 Fill in the blanks in each of the following statements. a) Counter-controlled repetition is also known as repetition because it is known in advance how many times the loop will be executed. ANS: definite. b) Sentinel-controlled repetition is also known as repetition because it is not known in advance how many times the loop will be executed. ANS: indefinite. c) In counter-controlled repetition, a(n) is used to count the number of times a group of instructions should be repeated. ANS: control variable or counter. d) The statement, when executed in a repetition statement, causes the next iteration of the loop to be performed immediately. ANS: continue. e) The statement, when executed in a repetition statement or a switch, causes an immediate exit from the statement. ANS: break. f) The is used to test a particular variable or expression for each of the constant integral values it may assume. ANS: switch selection statement. o r p p d e v State whether the following are true or false. If the answer is false, explain why. a) The default case is required in the switch selection statement. ANS: False. The default case is optional. If no default action is needed, then there is no need for a default case. b) The break statement is required in the default case of a switch selection statement. ANS: False. The break statement is used to exit the switch statement. The break statement is not required when the default case is the last case. c) The expression (x > y && a < b) is true if either x > y is true or a < b is true. ANS: False. Both of the relational expressions must be true in order for the entire expression to be true when using the && operator. d) An expression containing the || operator is true if either or both of its operands is true. ANS: True. A Write a statement or a set of statements to accomplish each of the following tasks: a) Sum the odd integers between 1 and 99 using a for statement. Assume the integer variables sum and count have been defined. ANS: sum = 0; for ( count = 1; count <= 99; count += 2 ) sum += count; b) Print the value 333.546372 in a field width of 15 characters with precisions of 1, 2, 3, 4 and 5. Left justify the output. What are the five values that print? ANS: printf( "%-15.1f\n", 333.546372 ); /* prints 333.5 */ printf( "%-15.2f\n", 333.546372 ); /* prints 333.55 */ printf( "%-15.3f\n", 333.546372 ); /* prints 333.546 */ printf( "%-15.4f\n", 333.546372 ); /* prints 333.5464 printf( "%-15.5f\n", 333.546372 ); /* prints 333.54637 */ */ c) Calculate the value of 2.5 raised to the power of 3 using the pow function. Print the result with a precision of 2 in a field width of 10 positions. What is the value that prints? ANS: printf( "%10.2f\n", pow( 2.5, 3 ) ); /* prints 15.63 */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Self-Review Exercises 99 d) Print the integers from 1 to 20 using a while loop and the counter variable x. Assume that the variable x has been defined, but not initialized. Print only five integers per line. [Hint: Use the calculation x % 5. When the value of this is 0, print a newline character, otherwise print a tab character.] ANS: x = 1; while ( x <= 20 ) { printf( "%d", x ); if ( x % 5 == 0 ) printf( "\n" ); else printf( "\t" ); x++; } or x = 1; while ( x <= 20 ) if ( x % 5 == 0 ) printf( "%d\n", x++ ); else o r p p printf( "%d\t", x++ ); or x = 0; while ( ++x <= 20 ) d e v if ( x % 5 == 0 ) A printf( "%d\n", x ); else printf( "%d\t", x ); e) Repeat Exercise 4.3 (d) using a for statement. ANS: for ( x = 1; x <= 20; x++ ) { printf( "%d", x ); if ( x % 5 == 0 ) printf( "\n" ); else printf( "\t" ); } or for ( x = 1; x <= 20; x++ ) if ( x % 5 == 0 ) printf( "%d\n", x ); else printf( "%d\t", x ); 4.4 Find the error in each of the following code segments and explain how to correct it. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 100 Chapter 4 a) C Program Control x = 1; while ( x <= 10 ); x++; } ANS: Error: The semicolon after the while header causes an infinite loop. Correction: Replace the semicolon with a { or remove both the ; and the }. b) for ( y = .1; y != 1.0; y += .1 ) printf( "%f\n", y ); ANS: Error: Using a floating-point number to control a for repetition statement. Correction: Use an integer, and perform the proper calculation in order to get the values you desire. for ( y = 1; y != 10; y++ ) printf( "%f\n", ( float ) y / 10 ); c) switch ( n ) { case 1: printf( "The number is 1\n" ); case 2: printf( "The number is 2\n" ); break; o r p p default: printf( "The number is not 1 or 2\n" ); break; } d e v ANS: Error: Missing break statement in the statements for the first case. Correction: Add a break statement at the end of the statements for the first case. Note that this is not necessarily an error if you want the statement of case 2: to execute every time the case 1: statement executes. d) The following code should print the values 1 to 10. A n = 1; while ( n < 10 ) printf( "%d ", n++ ); ANS: Error: Improper relational operator used in the while repetition-continuation condi- tion. Correction: Use <= rather than <. Exercises 4.5 Find the error in each of the following (Note: there may be more than one error): a) For ( x = 100, x >= 1, x++ ) printf( "%d\n", x ); ANS: F in for should be lowercase. The infinite loop can be corrected by switching the 1 and the 100 and changing the relational operator to tween the for conditions, not comma operators. <=. Semicolons are needed be- for ( x = 1; x <= 100; x++ ) printf( “%d\n”, x); b) The following code should print whether a given integer is odd or even: switch ( value % 2 ) { case 0: printf( "Even integer\n" ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 101 case 1: printf( "Odd integer\n" ); } ANS: A break is needed for case 0, otherwise both statements will be printed out. switch ( value % 2 ) { case 0: printf( “Even integer\n” ); break; case 1: printf( “Odd integer\n” ); c) The following code should input an integer and a character and print them. Assume the user types as input 100 A. scanf( "%d" , &intVal ); charVal = getchar(); printf( "Integer: %d\nCharacter: %c\n", intVal, charVal ); d e v ANS: charVal will read the blank character when the user types in intVal and hits return. To correct this, scanf should be used to read in charVal. scanf( “%d”, &intVal ); scanf( “\n%c”, &charVal ); /* skips preceding blanks */ o r p p printf( “Integer: %d\nCharacter: %c\n”, intVal, charVal ); d) for ( x = .000001; x == .0001; x += .000001 ) printf( "%.7f\n", x ); ANS: In addition, floating-point numbers should never be compared with == or != due to imprecision. This imprecision often causes infinite loops to occur. To correct this, an integer variable should be used in the for loop. e) The following code should output the odd integers from 999 to 1: for ( x = 999; x >= 1; x += 2 ) printf( "%d\n", x ); A ANS: loop should be decrementing not incrementing. for ( x = 999; x >= 1; x -= 2 ) printf( “%d\n”, x ); f) The following code should output the even integers from 2 to 100: counter = 2; Do { if ( counter % 2 == 0 ) printf( "%d\n", counter ); counter += 2; } While ( counter < 100 ); ANS: D in Do should be lowercase. W in While should be lowercase. The range of 2 to 100 needs to be printed, so the relational operator < should be changed to <=, to include 100. The if test is not necessary here, because counter is being incremented by 2, and will always be even within the body of the do…while. g) The following code should sum the integers from 100 to 150 (assume total is initialized to 0): for ( x = 100; x <= 150; x++ ); total += x; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 102 Chapter 4 C Program Control ANS: The semicolon at the end of the for statement should be removed, such that total += x; is in the loop’s body. for ( x = 100; x <= 150; x++ ) /* ; removed */ total += x; 4.6 State which values of the control variable x are printed by each of the following for statements: a) for ( x = 2; x <= 13; x += 2 ) printf( "%d\n", x ); ANS: 2, 4, 6, 8, 10, 12 b) for ( x = 5; x <= 22; x += 7 ) printf( "%d\n", x ); ANS: 5, 12, 19 c) for ( x = 3; x <= 15; x += 3 ) printf( "%d\n", x ); ANS: 3, 6, 9, 12, 15 d) for ( x = 1; x <= 5; x += 7 ) printf( "%d\n", x ); ANS: 1 e) for ( x = 12; x >= 2; x -= 3 ) printf( "%d\n", x ); ANS: 12, 9, 6, 3 4.7 o r p p d e v Write for statements that print the following sequences of values: a) 1, 2, 3, 4, 5, 6, 7 ANS: for ( i = 1; i <= 7; i++ ) printf( “%d ”, i ); b) 3, 8, 13, 18, 23 ANS: A /* increments of 5 */ for ( i = 3; i <= 23; i += 5 ) printf( “%d ”, i ); c) 20, 14, 8, 2, -4, -10 ANS: /* decrements of 6 */ for ( i = 20; i >= -10; i -= 6 ) printf( “%d ”, i ); d) 19, 27, 35, 43, 51 ANS: /* increments of 8 */ for ( i = 19; i <= 51; i += 8 ) printf( “%d “, i ); 4.8 1 2 3 4 5 6 7 8 What does the following program do? #include <stdio.h> /* function main begins program execution */ int main( void ) { int x; int y; int i; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 103 int j; /* prompt user for input */ printf( "Enter two integers in the range 1-20: " ); scanf( "%d%d", &x, &y ); /* read values for x and y */ for ( i = 1; i <= y; i++ ) { /* count from 1 to y */ for ( j = 1; j <= x; j++ ) { /* count from 1 to x */ printf( "@" ); /* output @ */ } /* end inner for */ printf( "\n" ); /* begin new line */ } /* end outer for */ return 0; /* indicate program ended successfully */ } /* end function main */ ANS: o r p p Enter integers in the range 1-20: 3 4 @@@ @@@ @@@ @@@ d e v 4.9 (Sum a Sequence of Integers) Write a program that sums a sequence of integers. Assume that the first integer read with scanf specifies the number of values remaining to be entered. Your program should read only one value each time scanf is executed. A typical input sequence might be A 5 100 200 300 400 500 where the 5 indicates that the subsequent five values are to be summed. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /* Exercise 4.9 Solution */ #include <stdio.h> int main( void ) { int sum = 0; /* current sum */ int number; int value; int i; /* number of values */ /* current value */ /* counter */ /* display prompt */ printf( "Enter the number of values to be processed: " ); scanf( "%d", &number ); /* input number of values */ /* loop number times */ for ( i = 1; i <= number; i++ ) { © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 104 17 18 19 20 21 22 23 24 25 Chapter 4 C Program Control printf( "Enter a value: " ); scanf( "%d", &value ); sum += value; /* add to sum */ } /* end for */ /* display sum */ printf( "Sum of the %d values is %d\n", number, sum ); return 0; /* indicate successful termination */ } /* end main */ Enter the number of values to be processed: 5 Enter a value: 10 Enter a value: 15 Enter a value: 20 Enter a value: 25 Enter a value: 30 Sum of the 5 values is 100 d e v 4.10 (Average a Sequence of Integers) Write a program that calculates and prints the average of several integers. Assume the last value read with scanf is the sentinel 9999. A typical input sequence might be o r p p 10 8 11 7 9 9999 indicating that the average of all the values preceding ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 9999 /* Exercise 4.10 Solution */ #include <stdio.h> A is to be calculated. int main( void ) { int value; /* current value */ int count = 0; /* number of values */ int total = 0; /* sum of integers */ /* display prompt */ printf( "Enter an integer ( 9999 to end ): " ); scanf( "%d", &value ); /* loop while sentinel value not read from user */ while ( value != 9999 ) { total += value; /* update total */ ++count; /* get next value */ printf( "Enter next integer ( 9999 to end ): " ); scanf( "%d", &value ); } /* end while */ /* show average if more than 0 values entered */ if ( count != 0 ) { printf( "\nThe average is: %.2f\n", ( double ) total / count ); } /* end if */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 28 29 30 31 32 33 105 else { printf( "\nNo values were entered.\n" ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ Enter Enter Enter Enter Enter Enter Enter an integer ( next integer next integer next integer next integer next integer next integer The average is: 9999 to end ): 1 ( 9999 to end ): ( 9999 to end ): ( 9999 to end ): ( 9999 to end ): ( 9999 to end ): ( 9999 to end ): 2 3 4 5 6 9999 3.50 d e v 4.11 (Find the Smallest) Write a program that finds the smallest of several integers. Assume that the first value read specifies the number of values remaining. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 o r p p /* Exercise 4.11 Solution */ #include <stdio.h> int main( void ) { int number; int value; int smallest; int i; A /* /* /* /* number of integers */ value input by user */ smallest number */ counter */ /* prompt user for number of integers */ printf( "Enter the number of integers to be processed: " ); scanf( "%d", &number ); /* prompt user for an integer */ printf( "Enter an integer: " ); scanf( "%d", &smallest ); /* loop until user has entered all integers */ for ( i = 2; i <= number; i++ ) { printf( "Enter next integer: " ); /* get next integer */ scanf( "%d", &value ); /* if value is smaller than smallest */ if ( value < smallest ) { smallest = value; } /* end if */ } /* end for */ printf( "\nThe smallest integer is: %d\n", smallest ); return 0; /* indicate successful termination */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 106 33 Chapter 4 C Program Control } /* end main */ Enter Enter Enter Enter Enter Enter the number of integers to be processed: 5 an integer: 372 next integer: 920 next integer: 73 next integer: 8 next integer: 3433 The smallest integer is: 8 4.12 (Calculating the Sum of Even Integers) Write a program that calculates and prints the sum of the even integers from 2 to 30. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /* Exercise 4.12 Solution */ #include <stdio.h> int main( void ) { int i; /* counter */ int sum = 0; /* current sum of integers */ o r p p /* loop through even integers up to 30 */ for ( i = 2; i <= 30; i += 2 ) { sum += i; /* add i to sum */ } /* end for */ A d e v printf( "Sum of the even integers from 2 to 30 is: %d\n", sum ); return 0; /* indicate successful termination */ } /* end main */ Sum of the even integers from 2 to 30 is: 240 4.13 (Calculating the Product of Odd Integers) Write a program that calculates and prints the product of the odd integers from 1 to 15. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ANS: /* Exercise 4.13 Solution */ #include <stdio.h> int main( void ) { long i; /* counter */ long product = 1; /* current product */ /* loop through odd integers up to 15 */ for ( i = 3; i <= 15; i += 2 ) { product *= i; /* update product */ } /* end for */ printf("Product of the odd integers from 1 to 15 is: %ld\n", product ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 15 16 107 return 0; /* indicate successful termination */ } /* end main */ Product of the odd integers from 1 to 15 is: 2027025 4.14 (Factorials) The factorial function is used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. Write a program that evaluates the factorials of the integers from 1 to 5. Print the results in tabular format. What difficulty might prevent you from calculating the factorial of 20? ANS: Calculating 20! is difficult in C because the resultant number is too large for even a long int to store. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /* Exercise 4.14 Solution */ #include <stdio.h> int main( void ) { int i; /* outer counter */ int j; /* inner counter */ int factorial; /* current factorial value */ o r p p d e v printf( "X\tFactorial of X\n" ); /* display table headers */ /* compute the factorial for 1 to 5 */ for ( i = 1; i <= 5; i++ ) { factorial = 1; A /* calculate factorial of current number */ for ( j = 1; j <= i; j++ ) { factorial *= j; } /* end inner for */ printf( "%d\t%d\n", i, factorial ); } /* end outer for */ return 0; /* indicate successful termination */ } /* end main */ Factorial of X 1 2 6 24 120 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. X 1 2 3 4 5 16 (Triangle Printing Program) Write a program that prints the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single printf statement of the form printf( "*" ); (this causes the asterisks to print side by side). [Hint: The last two patterns require that each line begin with an appropriate number of blanks.] (D) * ** *** **** ***** ****** ******* ******** ********* ********** A (C) ********** ********* ******** ******* ****** ***** **** *** ** * o r p p (B) ********** ********* ******** ******* ****** ***** **** *** ** * (A) * ** *** **** ***** ****** ******* ******** ********* ********** d e v © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 110 Chapter 4 C Program Control ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /* Exercise 4.16 Solution */ #include <stdio.h> int main( void ) { int row; /* row counter */ int col; /* column counter */ int space; /* spaces counter */ /* Pattern A, loop 10 times for rows */ for ( row = 1; row <= 10; row++ ) { /* print row asterisks */ for ( col = 1; col <= row; col++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ o r p p printf( "\n" ); d e v /* Pattern B, loop 10 times for rows row counts down to correspond to number of asterisks */ for ( row = 10; row >= 1; row-- ) { /* print row asterisks */ for ( col = 1; col <= row; col++ ) { printf( "*" ); } /* end for */ A printf( "\n" ); } /* end for */ printf( "\n" ); /* Pattern C, loop 10 times for rows row counts down to correspond to number of asterisks */ for ( row = 10; row >= 1; row-- ) { /* print (10 - row) number of preceding spaces */ for ( space = 1; space <= 10 - row; space++ ) { printf( " " ); } /* end for */ /* print row asterisks */ for ( col = 1; col <= row; col++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 111 printf( "\n" ); /* Pattern D, loop 10 times for rows */ for ( row = 1; row <= 10; row++ ) { /* print (10 - row) number of preceding spaces */ for ( space = 1; space <= 10 - row; space++ ) { printf( " " ); } /* end for */ /* print row asterisks */ for ( col = 1; col <= row; col++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ d e v printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */ o r p p 4.19 (Calculating Sales) An online retailer sells five different products whose retail prices are shown in the following table: Retail price A $ 2.98 $ 4.50 $ 9.98 $ 4.49 $ 6.87 Product number 1 2 3 4 5 Write a program that reads a series of pairs of numbers as follows: a) Product number b) Quantity sold for one day Your program should use a switch statement to help determine the retail price for each product. Your program should calculate and display the total retail value of all products sold last week. ANS: 1 2 3 4 5 6 7 8 /* Exercise 4.19 Solution */ #include <stdio.h> int main( void ) { int product; /* current product number */ int quantity; /* quantity of current product sold */ double total = 0.0; /* current total retail value */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 /* prompt for input */ printf( "Enter pairs of item numbers and quantities.\n"); printf( "Enter -1 for the item number to end input.\n" ); scanf( "%d", &product ); /* loop while sentinel value not read from user */ while ( product != -1 ) { scanf( "%d", &quantity ); /* determine product number and corresponding retail price */ switch ( product ) { case 1: total += quantity * 2.98; /* update total */ break; case 2: total += quantity * 4.50; /* update total */ break; d e v case 3: total += quantity * 9.98; /* update total */ break; o r p p case 4: total += quantity * 4.49; /* update total */ break; case 5: total += quantity * 6.87; /* update total */ break; default: printf( "Invalid product code: printf( " Quantity: } /* end switch */ A %d\n", product ); %d\n", quantity ); scanf( "%d", &product ); /* get next input */ } /* end while */ /* display total retail value */ printf( "The total retail value was: %.2f\n", total ); return 0; /* indicate successful termination */ } /* end main */ Enter pairs of item numbers and quantities. Enter -1 for the item number to end input. 1 1 2 1 3 1 4 1 5 1 6 1 Invalid product code: 6 Quantity: 1 1 1 -1 The total retail value was: 31.80 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 4.22 (Average Grade) Modify the program of Fig. 4.7 so that it calculates the average grade for the class. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* Exercise 4.22 Solution */ #include <stdio.h> int main( void ) { int grade; int aCount = 0; int bCount = 0; int cCount = 0; int dCount = 0; int fCount = 0; double averageGrade; /* /* /* /* /* /* /* current total a total b total c total d total f average grade */ grades */ grades */ grades */ grades */ grades */ grade for class */ /* prompt user for grades */ printf( "Enter the letter grades.\n"); printf( "Enter the EOF character to end input.\n" ); /* loop while not end of file */ while ( ( grade = getchar() ) != EOF ) { o r p p /* determine which grade was input */ switch ( grade ) { d e v /* grade was uppercase A */ case 'A': 24 /* grade was lowercase a */ case 'a': 25 26 ++aCount; /* update grade A counter * / /* exit switch */ break; 27 A 28 /* grade was uppercase B */ case 'B': 29 /* grade was lowercase b */ case 'b': 30 31 ++bCount; /* update grade B counter * / /* exit switch */ break; 32 /* grade was uppercase C /* grade was lowercase c 36 ++cCount; 37 break; 38 33 */ case 'C': 34 */ case 'c': 35 /* update grade C counter * / /* exit switch */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. /* grade was uppercase D */ /* grade was lowercase d */ 41 ++dCount; /* update grade C counter */ /* exit switch */ /* grade was uppercase F */ /* grade was lowercase f */ 46 ++fCount; /* update grade C counter */ 47 break; /* exit switch */ 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 case '\n': case '\t': case ' ': break; /* /* /* /* case 'D': case 'd': 39 40 break; 42 43 44 45 case 'F': case 'f': ignore newlines, */ tabs, */ and spaces in input */ exit switch */ default: /* catch all other characters */ printf( "Incorrect letter grade entered." ); printf( " Enter a new grade.\n" ); break; /* optional, will exit switch anyway */ } /* end switch */ } /* end while */ /* output totals for each printf( "\nThe totals for printf( "A: %d\n", aCount printf( "B: %d\n", bCount printf( "C: %d\n", cCount printf( "D: %d\n", dCount printf( "F: %d\n", fCount d e v grade */ each letter grade are:\n" ); ); ); ); ); ); o r p p /* calculate average grade */ averageGrade = ( double )( 4 * aCount + 3 * bCount + 2 * cCount + dCount ( aCount + bCount + cCount + dCount + fCount ); A /* output appropriate message for if ( averageGrade >= 3.5 ) { printf( "Average grade is A\n" } /* end if */ else if ( averageGrade >= 2.5 ) { printf( "Average grade is B\n" } /* end else if */ else if ( averageGrade >= 1.5 ) { printf( "Average grade is C\n" } /* end else if */ else if ( averageGrade >= 0.5 ) { printf( "Average grade is D\n" } /* end else if */ else { printf( "Average grade is F\n" } /* end else */ ) / average grade */ ); ); ); ); ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 118 92 93 Chapter 4 C Program Control return 0; /* indicate successful termination */ } /* end main */ Enter Enter A B B C C C B A A ^Z the the B C D D B C letter grades. EOF character to end input. D F D C B C C The totals for each letter grade are: A: 3 B: 6 C: 8 D: 4 F: 1 Average grade is C 4.24 d e v Assume i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? a) printf( "%d", i == 1 ); ANS: 1 b) printf( "%d", j == 3 ); ANS: 0 c) printf( ANS: 1 d) printf( ANS: 0 e) printf( ANS: 1 f) printf( ANS: 0 g) printf( ANS: 0 h) printf( ANS: 1 i) printf( ANS: 0 j) printf( ANS: 1 A o r p p "%d", i >= 1 && j < 4 ); "%d", m < = 99 && k < m ); "%d", j >= i || k == m ); "%d", k + m < j || 3 - j >= k ); "%d", !m ); "%d", !( j - m ) ); "%d", !( k > m ) ); "%d", !( j > k ) ); 4.25 (Table of Decimal, Binary, Octal and Hexadecimal Equivalents) Write a program that prints a table of the binary, octal and hexadecimal equivalents of the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix D before you attempt this exercise. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 120 Chapter 4 C Program Control ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /* Exercise 4.25 Solution */ #include <stdio.h> int main( void { int loop; int number; int temp1; ) /* loop counter */ /* current number */ /* temporary integer */ /* print table headers */ printf( "Decimal\t\tBinary\t\tOctal\t\tHexadecimal\n" ); /* loop through values 1 to 256 */ for ( loop = 1; loop <= 256; loop++ ) { printf( "%d\t\t", loop ); number = loop; d e v /* binary numbers */ printf( "%c", number == 256 ? '1' : '0' ); o r p p printf( "%c", number < 256 && number >= 128 ? '1' : '0' ); number %= 128; printf( "%c", number < 128 && number >= 64 ? '1' : '0' ); number %= 64; printf( "%c", number < 64 && number >= 32 ? '1' : '0' ); number %= 32; A printf( "%c", number < 32 && number >= 16 ? '1' : '0' ); number %= 16; printf( "%c", number < 16 && number >= 8 ? '1' : '0' ); number %= 8; printf( "%c", number < 8 && number >= 4 ? '1' : '0' ); number %= 4; printf( "%c", number < 4 && number >= 2 ? '1' : '0' ); number %= 2; printf( "%c\t", number == 1 ? '1' : '0' ); /* octal numbers */ number = loop; printf( "%d", number < 512 && number >= 64 ? number / 64 : 0 ); number %= 64; printf( "%d", number < 64 && number >= 8 ? number / 8 : 0 ); number %= 8; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 121 printf( "%d\t\t", number == 0 ? 0 : number ); /* hexadecimal numbers */ number = loop; temp1 = 16; if ( number < 4096 && number >= 256 ) { printf( "%d", number / 256 ); number %= 16; } /* end if */ if ( number < 256 && number >= 16 ) { temp1 = number / 16; number %= 16; } /* end if */ else { printf( "0" ); } /* end else */ d e v /* convert to letter if temp1 is above 9 */ if ( temp1 <= 9 ) { printf( "%d", temp1 ); } /* end if */ else if ( temp1 >= 10 && temp1 <= 15 ) { printf( "%c", 'A' + ( temp1 - 10 ) ); } /* end else if */ else if ( temp1 == 16 ) { printf( "0" ); } /* end else if */ A o r p p /* convert to letter if number is above 9 */ if ( number <= 9 ) { printf( "%d", number ); } /* end if */ else if ( number >= 10 && number <= 15 ) { printf( "%c", 'A' + ( number - 10 ) ); } /* end else if */ printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 122 Chapter 4 C Program Control Hexadecimal 01 02 03 04 05 06 07 08 09 0A Octal 001 002 003 004 005 006 007 010 011 012 Binary 000000001 000000010 000000011 000000100 000000101 000000110 000000111 000001000 000001001 000001010 Decimal 1 2 3 4 5 6 7 8 9 10 ... FA FB FC FD FE FF 100 372 373 374 375 376 377 400 o r p p 011111010 011111011 011111100 011111101 011111110 011111111 100000000 250 251 252 253 254 255 256 d e v 4.31 (Diamond Printing Program) Write a program that prints the following diamond shape. You may use printf statements that print either a single asterisk (*) or a single blank. Maximize your use of repetition (with nested for statements) and minimize the number of printf statements. A * *** ***** ******* ********* ******* ***** *** * ANS: 1 2 3 4 5 6 7 8 9 /* Exercise 4.31 Solution */ #include <stdio.h> int main( void ) { int line; /* line counter */ int space; /* space counter */ int asterisk; /* asterisk counter */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 134 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 Chapter 4 C Program Control /* top half */ for ( line = 1; line <= 9; line += 2 ) { /* print preceding spaces */ for ( space = ( 9 - line ) / 2; space > 0; space-- ) { printf( " " ); } /* end for */ /* print asterisks */ for ( asterisk = 1; asterisk <= line; asterisk++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ /* bottom half */ for ( line = 7; line >= 0; line -= 2 ) { d e v /* print preceding spaces */ for ( space = ( 9 - line ) / 2; space > 0; space-- ) { printf( " " ); } /* end for */ o r p p /* print asterisks */ for ( asterisk = 1; asterisk <= line; asterisk++ ) { printf( "*" ); } /* end for */ A printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ 4.32 (Modified Diamond Printing Program) Modify the program you wrote in Exercise 4.31 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond. Your program should then display a diamond of the appropriate size. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 /* Exercise 4.32 Solution */ #include <stdio.h> int main( void ) { int line; int space; int asterisk; int size; /* /* /* /* line counter */ space counter */ asterisk counter */ number of rows in diamond */ /* prompt for diamond size */ printf( "Enter an odd number for the diamond size ( 1-19 ):\n" ); scanf( "%d", &size ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 /* top half */ for ( line = 1; line <= size - 135 2; line += 2 ) { /* print preceding spaces */ for ( space = ( size - line ) / 2; space > 0; space-- ) { printf( " " ); } /* end for */ /* print asterisks */ for ( asterisk = 1; asterisk <= line; asterisk++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ /* bottom half */ for ( line = size; line >= 0; line -= 2 ) { d e v /* print preceding spaces */ for ( space = ( size - line ) / 2; space > 0; space-- ) { printf( " " ); } /* end for */ o r p p /* print asterisks */ for ( asterisk = 1; asterisk <= line; asterisk++ ) { printf( "*" ); } /* end for */ A printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ Enter an odd number for the diamond size ( 1-19 ): 13 * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** * 4.33 (Roman Numeral Equivalent of Decimal Values) Write a program that prints a table of all the Roman numeral equivalents of the decimal numbers in the range 1 to 100. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 136 Chapter 4 C Program Control ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /* Exercise 4.33 Solution */ #include <stdio.h> int main( void ) { int loop; /* loop counter */ int div; /* tens digit */ int mod; /* ones digit */ /* display table headers */ printf( " Roman\nNumeral\t\tDecimal\n" ); /* loop 100 times */ for ( loop = 1; loop <= 100; loop++ ) { div = loop / 10; /* separate tens digit */ mod = loop % 10; /* separate ones digit */ /* switch structure for tens digit */ switch ( div ) { o r p p d e v /* print appropriate Roman numeral for tens digit */ case 0: break; case 1: printf( "X" ); break; /* exit switch */ A case 2: printf( "XX" ); break; /* exit switch */ case 3: printf( "XXX" ); break; /* exit switch */ case 4: printf( "XL" ); break; /* exit switch */ case 5: printf( "L" ); break; /* exit switch */ case 6: printf( "LX" ); break; /* exit switch */ case 7: printf( "LXX" ); break; /* exit switch */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Exercises 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 137 case 8: printf( "LXXX" ); break; /* exit switch */ case 9: printf( "XC" ); break; /* exit switch */ case 10: printf( "C" ); break; /* exit switch */ default: break; /* exit switch */ } /* end switch */ /* switch structure for ones digit */ switch( mod ) { d e v /* print appropriate Roman numeral for ones digit */ case 0: printf( "\t\t%4d\n", loop ); break; /* exit switch */ o r p p case 1: printf( "I\t\t%4d\n", loop ); break; /* exit switch */ case 2: printf( "II\t\t%4d\n", loop ); break; /* exit switch */ A case 3: printf( "III\t\t%4d\n", loop ); break; /* exit switch */ case 4: printf( "IV\t\t%4d\n", loop ); break; /* exit switch */ case 5: printf( "V\t\t%4d\n", loop ); break; /* exit switch */ case 6: printf( "VI\t\t%4d\n", loop ); break; /* exit switch */ case 7: printf( "VII\t\t%4d\n", loop ); break; /* exit switch */ case 8: printf( "VIII\t\t%4d\n", loop ); break; /* exit switch */ © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 138 Chapter 4 C Program Control 108 109 case 9: 110 printf( "IX\t\t%4d\n", loop ); 111 break; /* exit switch */ 112 } /* end switch */ 113 114 } /* end for */ 115 116 return 0; /* indicate successful termination */ 117 } /* end main */ Decimal 1 2 3 4 5 6 7 8 9 10 89 90 91 92 93 94 95 96 97 98 99 100 A o r p p Roman Numeral I II III IV V VI VII VIII IX X d e v ... LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.