Chtp4IM(chtp4_01) C How To Program Solution Manual

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 675

Instructor's Manual for  C How to Program, 4/e  Deitel & Deitel © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Contents  1 Introduction to Computers, the Internet and the World Wide Web  1  2  Introduction to C Programming  5  3  Structured Program Development in C  19  4  C Program Control  55  5  C Functions  97  6  C Arrays  169  7  Pointers  233  8  C Characters and Strings  283  9  C Formatted Input/Output  319  10 Structures, Unions, Bit Manipulations and Enumerations  333  11  C File Processing  353  12  Data Structures  375  II  13  The Preprocessor  441  14  Other C Topics  447  15  C++ as a "Better C"  16  C++ Classes and Data Abstraction  463  17  C++ Classes: Part II  485  18  C++ Operator Overloading  493  19  C++ Inheritance  499  20  C++ Virtual Functions and Polymorphism  511  21  C++ Stream Input/Output  519  22  C++ Templates  537  23  C++ Exception Handling: Solution  543  24  Introduction to Java Applications and Applets  547  457  25 Beyond C & C++: Operators, Methods & Arrays in Java  557  26  Java Object-Based Programming  585  27  Java Object-Oriented Programming  603  28  Java Graphics and Java2D  617  29  Java Graphical User Interface Components  633  30  Java Multimedia: Images, Animation, and Audio  661  1 Introduction to Computers, the Internet and the World Wide Web: Solutions SOLUTIONS 1.3  Categorize each of the following items as either hardware or software: a) CPU ANS: hardware. b) C compiler ANS: software. c) ALU ANS: hardware. d) C preprocessor ANS: software. e) input unit ANS: hardware. f) a word processor program ANS: software.  1.4 Why might you want to write a program in a machine-independent language instead of a machine-dependent language? Why might a machine-dependent language be more appropriate for writing certain types of programs? ANS: Machine independent languages are useful for writing programs to be executed on multiple computer platforms. Machine dependent languages are appropriate for writing programs to be executed on a single platform. Machine dependent languages tend to exploit the efficiencies of a particular machine. 1.5 Translator programs such as assemblers and compilers convert programs from one language (referred to as the source language) to another language (referred to as the object language). Determine which of the following statements are true and which are false: a) A compiler translates high-level language programs into object language. ANS: True. b) An assembler translates source language programs into machine language programs. ANS: True. c) A compiler converts source language programs into object language programs. ANS: False. d) High-level languages are generally machine-dependent. ANS: False. e) A machine language program requires translation before the program can be run on a computer. ANS: False.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  2 Introduction to Computers, the Internet and the World Wide Web: Solutions  Chapter 1  1.6  Fill in the blanks in each of the following statements: a) Devices from which users access timesharing computer systems are usually called . ANS: terminals. b) A computer program that converts assembly language programs to machine language programs is called . ANS: an assembler. c) The logical unit of the computer that receives information from outside the computer for use by the computer is called . ANS: The input unit. d) The process of instructing the computer to solve specific problems is called . ANS: computer programming. e) What type of computer language uses English-like abbreviations for machine language instructions? . ANS: a high-level language. f) Which logical unit of the computer sends information that has already been processed by the computer to various devices so that the information may be used outside the computer? . ANS: The output unit. g) The general name for a program that converts programs written in a certain computer language into machine language is . ANS: compiler. h) Which logical unit of the computer retains information? . ANS: memory unit and secondary storage unit. i) Which logical unit of the computer performs calculations? . ANS: arithmetic and logical unit. j) Which logical unit of the computer makes logical decisions? . ANS: arithmetic and logical unit k) The commonly used abbreviation for the computer's control unit is . ANS: CPU. l) The level of computer language most convenient to the programmer for writing programs quickly and easily is . ANS: high-level language. m) The only language that a computer can directly understand is called that computer's . ANS: machine language. n) Which logical unit of the computer coordinates the activities of all the other logical units? . ANS: central processing unit.  1.7  State whether each of the following is true or false. If false, explain your answer. a) Machine languages are generally machine dependent. ANS: True. Machine languages are closely related to the hardware of a particular machine. b) Timesharing truly runs several users simultaneously on a computer. ANS: False. Time sharing systems split CPU time amongst several users so that the users appear to be operating simultaneously c) Like other high-level languages, C is generally considered to be machine independent. ANS: True. C programs can be written on most machines, and with some care, C programs can be written on one machine and run on many machines with few changes or no changes.  1.8  Discuss the meaning of each of the following names: a) stdin ANS: This refers to the standard input device. The standard input device is normally connected to the keyboard b) stdout ANS: This refers to the standard output device. The standard output device is normally connected to the computer screen. c) stderr ANS: This refers to the standard error device. Error messages are normally sent to this device which is typically connected to the computer screen.  1.9  Why is so much attention today focused on object-oriented programming in general and C++ in particular? ANS: Object-oriented programming enables the programmer to build reusable software components that model items in the real world. Building software quickly, correctly, and economically has been an elusive goal in the software industry. The modular, object-oriented design and implementation approach has been found to increase productivity 10 to 100 times over conventional programming languages while reducing development time, errors, and cost. C++ is used for object-oriented programming because it is a superset of the C programming language and C is widely used. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 1  1.10  Introduction to Computers, the Internet and the World Wide Web: Solutions 3  Which programming language is best described by each of the following? a) Developed by IBM for scientific and engineering applications. ANS: FORTRAN b) Developed specifically for business applications. ANS: COBOL c) Developed for teaching structured programming. ANS: Pascal d) Named after the world's first computer programmer. ANS: Ada e) Developed to familiarize novices with programming techniques. ANS: BASIC f) Specifically developed to help programmers migrate to .NET. ANS: C# g) Known as the development language of UNIX. ANS: C h) Formed primarily by adding object-oriented programming to C. ANS: C++ i) Succeeded initially because of its ability to create Web pages with dynamic content. ANS: Java  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  4 Introduction to Computers, the Internet and the World Wide Web: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 1  2 Introduction to C Programming: Solutions  SOLUTIONS: 2.7  Identify and correct the errors in each of the following statements (Note: there may be more than one error per statement): a) scanf( "d", value ); ANS: scanf( "%d", &value ); b) printf( "The product of %d and %d is %d"\n, x, y ); ANS: printf( "The product of %d and %d is %d\n", x, y, z ); c) firstNumber + secondNumber = sumOfNumbers ANS: sumOfNumbers = firstNumber + secondNumber; d) if ( number => largest ) largest == number;  ANS: if ( number >= largerst ) largest = number;  e) */ Program to determine the largest of three integers /* ANS: /* Program to determine the largest of three integers */ f) Scanf( "%d", anInteger ); ANS: scanf( "%d", &anInteger ); g) printf( "Remainder of %d divided by %d is\n", x, y, x % y ); ANS: printf( "Remainder of %f divided by %d is %d\n", x, y, x % y ); h) if ( x = y ); printf( %d is equal to %d\n", x, y );  ANS: if ( x == y ) printf( "%d is equal to %d\n", x, y ); i) print( "The sum is %d\n," x + y ); ANS: printf( "The sum is %d\n", x + y ); j) Printf( "The value you entered is: %d\n, &value ); ANS: printf( "The value you entered is: %d\n", value );  2.8  Fill in the blanks in each of the following: a) are used to document a program and improve its readability. ANS: comments. b) The function used to display information on the screen is . ANS: printf. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  6 Introduction to C Programming: Solutions  Chapter 2  c) A C statement that makes a decision is . ANS: if. d) Calculations are normally performed by statements. ANS: assignment. e) The function inputs values from the keyboard. ANS: scanf. 2.9  Write a single C statement or line that accomplishes each of the following: a) Print the message "Enter two numbers." ANS: printf( "Enter two numbers\n" ); b) Assign the product of variables b and c to variable a. ANS: a = b * c; c) State that a program performs a sample payroll calculation (i.e., use text that helps to document a program). ANS: /* Sample payroll calculation program */ d) Input three integer values from the keyboard and place these values in integer variables a, b and c. ANS: scanf( "%d%d%d", &a, &b, &c );  2.10  State which of the following are true and which are false. If false, explain your answer. a) C operators are evaluated from left to right. ANS: False. Some operators are evaluated left to right and others are evaluated from right to left depending on their associativity (see Appendix C). b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales, his_account_total, a, b, c, z, z2. ANS: True. c) The statement printf("a = 5;"); is a typical example of an assignment statement. ANS: False. The statement prints a = 5; on the screen. d) A valid arithmetic expression containing no parentheses is evaluated from left to right. ANS: False. Multiplication, division, and modulus are all evaluated first from left to right, then addition and subtraction are evaluated from left to right. e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h. ANS: False. Those beginning with a number are invalid.  2.11  Fill in the blanks in each of the following: a) What arithmetic operations are on the same level of precedence as multiplication? . ANS: division, modulus. b) When parentheses are nested, which set of parentheses is evaluated first in an arithmetic expression? . ANS: The innermost pair of parenthesis. c) A location in the computer's memory that may contain different values at various times throughout the execution of a program is called a . ANS: variable.  2.12 What, if anything, prints when each of the following C statements is performed? If nothing prints, then answer "nothing." Assume x = 2 and y = 3. a) printf( "%d", x ); ANS: 2 b) printf( "%d", x + x ); ANS: 4 c) printf( "x=" ); ANS: x= d) printf( "x=%d", x ); ANS: x=2 e) printf( "%d = %d", x + y, y + x ); ANS: 5 = 5 f) z = x + y; ANS: Nothing. Value of x + y is assigned to z. g) scanf( "%d%d", &x, &y );  ANS: Nothing. Two integer values are read into the location of x and the location of y. h) /* printf( "x + y = %d", x + y ); */ ANS: Nothing. This is a comment. i) printf( "\n" ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 7  Chapter 2  ANS: A newline character is printed, and the cursor is positioned at the beginning of the next line on the screen. 2.13  Which, if any, of the following C statements contain variables involved in destructive read-in? a) scanf( "%d%d%d%d%d", &b, &c, &d, &e, &f ); b) p = i + j + k + 7; c) printf( "Destructive read-in" ); d) printf( "a = 5" ); ANS: (a).  2.14  Given the equation y = ax3 + 7, which of the following, if any, are correct C statements for this equation? a) y = a * x * x * x + 7; b) y = a * x * x * ( x + 7 ); c) y = ( a * x ) * x * ( x + 7 ); d) y = ( a * x ) * x * x + 7; e) y = a * ( x * x * x ) + 7; f) y = a * x * ( x * x + 7 ); ANS: (a), (d), and (e).  2.15 State the order of evaluation of the operators in each of the following C statements and show the value of x after each statement is performed. a) x = 7 + 3 * 6 / 2 - 1; ANS: * is first, / is second, + is third, and - is fourth. Value of x is 15. b) x = 2 % 2 + 2 * 2 - 2 / 2; ANS: % is first, * is second, / is third, + is fourth, - is fifth. Value of x is 3. c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ); ANS: 5 6 4 2 3 1. Value of x is 338.  2.16 Write a program that asks the user to enter two numbers, obtains the two numbers from the user and prints the sum, product, difference, quotient and remainder of the two numbers. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  /* Exercise 2.16 Solution */ #include                      int main() { int x; /* define first number */ int y; /* define second number */ printf( "Enter two numbers: "); /* prompt user */ scanf( "%d%d", &x, &y ); /* read values from keyboard */ /* output results */ printf( "The sum is %d\n", x + y ); printf( "The product is %d\n", x * y ); printf( "The difference is %d\n", x - y ); printf( "The quotient is %d\n", x / y ); printf( "The modulus is %d\n", x % y ); return 0; /* indicate successful termination */ } /* end main */  Enter two numbers: 20 5 The sum is 25 The product is 100 The difference is 15 The quotient is 4 The modulus is 0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  8 Introduction to C Programming: Solutions  2.17  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  Chapter 2  Write a program that prints the numbers 1 to 4 on the same line. Write the program using the following methods. a) Using one printf statement with no conversion specifiers. b) Using one printf statement with four conversion specifiers. c) Using four printf statements. ANS: /* Exercise 2.17 Solution */ #include                          int main() { printf( "1 2 3 4\n\n" ); /* part a */ printf( "%d %d %d %d\n\n", 1, 2, 3, 4 ); /* part b */ printf( printf( printf( printf(  "1 " ); /* part c */ "2 " ); "3 " ); "4\n" );  return 0; /* indicates successful termination */ } /* end main */  1 2 3 4 1 2 3 4 1 2 3 4  2.18 Write a program that asks the user to enter two integers, obtains the numbers from the user, then prints the larger number followed by the words "is larger." If the numbers are equal, print the message "These numbers are equal." Use only the single-selection form of the if statement you learned in this chapter. 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  /* Exercise 2.18 Solution */ #include                              int main() { int x; /* define first number */ int y; /* define second number */ printf( "Enter two numbers: " ); /* prompt */ scanf( "%d%d", &x, &y ); /* read two integers */ /* compare the two numbers */ if ( x > y ) { printf( "%d is larger\n", x ); } /* end if */ if ( x < y ) { printf( "%d is larger\n", y ); } /* end if */ if ( x == y ) { printf( "These numbers are equal\n" ); } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 9  Chapter 2  25 26 27  return 0; /* indicate successful termination */ } /* end main */  Enter two numbers: 5 20 20 is larger  Enter two numbers: 239 92 239 is larger  Enter two numbers: 17 17 These numbers are equal  2.19 Write a program that inputs three different integers from the keyboard, then prints the sum, the average, the product, the smallest and the largest of these numbers. Use only the single-selection form of the if statement you learned in this chapter. The screen dialogue should appear as follows:  Input three different integers: 13 27 14 Sum is 54 Average is 18 Product is 4914 Smallest is 13 Largest is 27  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  /* Exercise 2.19 Solution */ #include                                  int main() { int a; int b; int c; int smallest; int largest;  /* /* /* /* /*  define first integer */ define second integer */ define third integer */ smallest integer */ largest integer */  printf( "Input three different integers: " ); /* prompt user */ scanf( "%d%d%d", &a, &b, &c ); /* read three integers */ /* output sum, average and printf( "Sum is %d\n", a + printf( "Average is %d\n", printf( "Product is %d\n",  product of the three integers */ b + c ); ( a + b + c ) / 3 ); a * b * c );  smallest = a; /* assume first number is the smallest */ if ( b < smallest ) { /* is b smaller? */ smallest = b; } /* end if */ if ( c < smallest ) { /* is c smaller? */ smallest = c; } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  10 Introduction to C Programming: Solutions  29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46  Chapter 2  printf( "Smallest is %d\n", smallest ); largest = a; /* assume first number is the largest */ if ( b > largest ) { /* is b larger? */ largest = b; } /* end if */ if ( c > largest ) { /* is c larger? */ largest = c; } /* end if */ printf( "Largest is %d\n", largest ); return 0; /* indicate successful termination */ } /* end main */  2.20 Write a program that reads in the radius of a circle and prints the circle's diameter, circumference and area. Use the constant value 3.14159 for Ï€. Perform each of these calculations inside the printf statement(s) and use the conversion specifier %f. [Note: In this chapter, we have discussed only integer constants and variables. In Chapter 3 we will discuss floating-point numbers, i.e., values that can have decimal points.] ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  /* Exercise 2.20 Solution */ #include                                      int main() { int radius; /* circle radius */ printf( "Input the circle radius: " ); /* prompt user */ scanf( "%d", &radius ); /* read integer radius */ /* calculate and output diameter, circumference and area */ printf( "\nThe diameter is %d\n", 2 * radius ); printf( "The circumference is %f\n", 2 * 3.14159 * radius ); printf( "The area is %f\n", 3.14159 * radius * radius ); return 0; /* indicate successful termination */ } /* end main */  Input the circle radius: 9 The diameter is 18 The circumference is 56.548620 The area is 254.468790  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 11  Chapter 2  2.21  Write a program that prints a box, an oval, an arrow and a diamond as follows:  ********* * * * * * * * * * * * * * * *********  *** *  *  * * * * *  * * * * * *  * ***  * *** ***** * * * * * *  * * * *  *  *  *  *  *  *  * *  * * * *  ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  /* Exercise 2.21 Solution */ #include                                          2.22  What does the following code print?  int main() { printf( printf( printf( printf( printf( printf( printf( printf( printf(  "********* "* * "* * "* * "* * "* * "* * "* * "*********  *** *  *  * * * * *  * * * * * *  * ***  * *** ***** * * * * * *  *\n" ); * *\n" ); * *\n" ); * *\n" ); * *\n" ); * *\n" ); * *\n" ); * *\n" ); *\n" );  return 0; /* indicates successful termination */ } /* end main */  printf( "*\n**\n***\n****\n*****\n" );  ANS:  * ** *** **** *****  2.23 Write a program that reads in five integers and then determines and prints the largest and the smallest integers in the group. Use only the programming techniques you have learned in this chapter. ANS: 1 2 3 4 5 6 7 8 9  /* Exercise 2.23 Solution */ #include                                              int main() { int largest; int smallest; int int1; int int2;  /* largest integer */ /* smallest integer */ /* define int1 for user input */  /* define int2 for user input */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  12 Introduction to C Programming: Solutions  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  int int3; int temp;  Chapter 2  /* define int3 for user input */ /* temporary integer for swapping */  printf( "Input 5 integers: " ); /* prompt user and read 5 ints */ scanf( "%d%d%d%d%d", &largest, &smallest, &int1, &int2, &int3 ); if ( smallest > largest ) { /* make comparisons */ temp = largest; largest = smallest; smallest = temp; } /* end if */ if ( int1 > largest ) { largest = int1; } /* end if */ if ( int1 < smallest ) { smallest = int1; } /* end if */ if ( int2 > largest ) { largest = int2; } /* end if */ if ( int2 < smallest ) { smallest = int2; } /* end if */ if ( int3 > largest ) { largest = int3; } /* end if */ if ( int3 < smallest ) { smallest = int3; } /* end if */ printf( "The largest value is %d\n", largest ); printf( "The smallest value is %d\n", smallest ); return 0; /* indicate successful termination */ } /* end main */  Input 5 integers: 9 4 5 8 7 The largest value is 9 The smallest value is 4  2.24 Write a program that reads an integer and determines and prints whether it is odd or even. [Hint: Use the remainder operator. An even number is a multiple of two. Any multiple of two leaves a remainder of zero when divided by 2.] ANS: 1 2 3 4 5 6 7 8  /* Exercise 2.24 Solution */ #include                                                  int main() { int integer; /* integer input by user */ printf( "Input an integer: " ); /* prompt */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 13  Chapter 2  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  scanf( "%d", &integer );  /* read integer */  /* test if integer is even */ if ( integer % 2 == 0 ) { printf( "%d is an even integer\n", integer ); } /* end if */ /* test if integer is odd */ if ( integer % 2 != 0 ) { printf( "%d is an odd integer\n", integer ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */  Input an integer: 78 78 is an even integer  Input an integer: 79 79 is an odd integer  2.25  Print your initials in block letters down the page. Construct each block letter out of the letter it represents as shown below.  PPPPPPPPP P P P P P P P P JJ J J J JJJJJJJ DDDDDDDDD D D D D D D DDDDD  ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  /* Exercise 2.25 Solution */ #include                                                      int main() { printf( printf( printf( printf( printf( printf( printf( printf( printf(  "PPPPPPPPP\n" ); " P P\n" ); " P P\n" ); " P P\n" ); " P P\n" ); "\n" ); " JJ\n" ); " J\n" ); "J\n" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  14 Introduction to C Programming: Solutions  15 16 17 18 19 20 21 22 23 24 25 26  printf( printf( printf( printf( printf( printf( printf( printf(  Chapter 2  " J\n" ); " JJJJJJJ\n" ); "\n" ); "DDDDDDDDD\n" ); "D D\n" ); "D D\n" ); " D D\n" ); " DDDDD\n" );  return 0; /* indicate successful termination */ } /* end main */  2.26 Write a program that reads in two integers and determines and prints if the first is a multiple of the second. [Hint: Use the remainder operator.] 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  /* Exercise 2.26 Solution */ #include                                                          int main() { int integer1; /* first integer */ int integer2; /* second integer */ printf( "Input two integers: " ); /* prompt user */ scanf( "%d%d", &integer1, &integer2 ); /* read two integers */ /* use remainder operator */ if ( integer1 % integer2 == 0 ) { printf( "%d is a multiple of %d ", integer1, integer2 ); printf( "by a factor of %d\n", integer1 / integer2 ); } /* end if */ if ( integer1 % integer2 != 0 ) { printf( "%d is not a multiple of %d\n", integer1, integer2 ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */  Input two integers: 88 11 88 is a multiple of 11 by a factor of 8  Input two integers: 777 5 777 is not a multiple of 5  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 15  Chapter 2  2.27  Display the following checkerboard pattern with eight printf statements and then display the same pattern with as few  printf statements as possible.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  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  /* Exercise 2.27 Solution */ #include                                                              int main() { printf( "With eight printf() statements: \n" ); printf( printf( printf( printf( printf( printf( printf( printf(  "* * * * * * * *\n" ); " * * * * * * * *\n" ); "* * * * * * * *\n" ); " * * * * * * * *\n" ); "* * * * * * * *\n" ); " * * * * * * * *\n" ); "* * * * * * * *\n" ); " * * * * * * * *\n" );  printf( "\nNow with one printf() statement: \n" ); printf( "* * * * * * * *\n * * * * * * * *\n" "* * * * * * * *\n * * * * * * * *\n" "* * * * * * * *\n * * * * * * * *\n" "* * * * * * * *\n * * * * * * * *\n" ); return 0; /* indicate successful termination */ } /* end main */  With eight printf() statements: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Now with one printf() statement: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  16 Introduction to C Programming: Solutions  Chapter 2  2.28 Distinguish between the terms fatal error and non-fatal error. Why might you prefer to experience a fatal error rather than a non-fatal error? ANS: A fatal error causes the program to terminate prematurely. A nonfatal error occurs when the logic of the program is incorrect, and the program does not work properly. A fatal error is preferred for debugging purposes. A fatal error immediately lets you know there is a problem with the program, whereas a nonfatal error can be subtle and possibly go undetected. 2.29 Here's a peek ahead. In this chapter you learned about integers and the type int. C can also represent uppercase letters, lowercase letters and a considerable variety of special symbols. C uses small integers internally to represent each different character. The set of characters a computer uses and the corresponding integer representations for those characters is called that computer's character set. You can print the integer equivalent of uppercase A for example, by executing the statement printf( "%d", 'A' );  Write a C program that prints the integer equivalents of some uppercase letters, lowercase letters, digits and special symbols. As a minimum, determine the integer equivalents of the following: A B C a b c 0 1 2 $ * + / and the blank character. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  /* Exercise 2.29 Solution */ #include                                                                  int main() { char intEquivalent; /* letter, digit or character */ printf( "Input a letter, digit, or character: " ); /* prompt */ scanf( "%c", &intEquivalent ); /* read user input */ printf( "%c's integer equivalent is %d\n", intEquivalent, intEquivalent ); return 0; /* indicate successful termination */ } /* end main */  Input a letter, digit, or character: % %'s integer equivalent is 37  Input a letter, digit, or character: y y's integer equivalent is 121  Input a letter, digit, or character: 0 0's integer equivalent is 48  2.30 Write a program that inputs one five-digit number, separates the number into its individual digits and prints the digits separated from one another by three spaces each. [Hint: Use combinations of integer division and the remainder operation.] For example, if the user types in 42139, the program should print  4  2  1  3  9  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Introduction to C Programming: Solutions 17  Chapter 2  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  /* Exercise 2.30 Solution */ #include                                                                      int main() { int number; /* number input by user */ int temp1; /* first temporary integer */ int temp2; /* second temporary integer */ printf( "Enter a five-digit number: " ); /* prompt user */ scanf( "%d", &number ); /* read integer */ printf( "%d ", number / 10000 ); /* print left-most digit */ temp2 = number % 10000; printf( " %d ", temp2 / 1000 ); temp1 = temp2 % 1000; printf( " %d ", temp1 / 100 ); temp2 = temp1 % 100; printf( " %d ", temp2 / 10 ); temp1 = temp2 % 10; printf( "  %d\n", temp1 ); /* print right-most digit */  return 0; /* indicate successful termination */ } /* end main */  Enter a five-digit number: 23456 2 3 4 5 6  2.31 Using only the techniques you learned in this chapter, write a program that calculates the squares and cubes of the numbers from 0 to 10 and uses tabs to print the following table of values:  number 0 1 2 3 4 5 6 7 8 9 10  square 0 1 4 9 16 25 36 49 64 81 100  cube 0 1 8 27 64 125 216 343 512 729 1000  ANS: 1 2 3 4 5  /* Exercise 2.31 Solution */ #include                                                                          int main() {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  18 Introduction to C Programming: Solutions  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 53 54 55  int count = 0; /* initialize count to zero */ /* calculate the square and cube for the numbers 0 to 10 */ printf( "\nnumber\tsquare\tcube\n" ); printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; /* increment count by 1 */ printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); count = count + 1; printf( "%d\t%d\t%d\n", count, count * count, count * count * count ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 2  3 Structured Program Development in C: Solutions  SOLUTIONS 3.11  Identify and correct the errors in each of the following [Note: There may be more than one error in each piece of code]: a) if ( age >= 65 ); printf( "Age is greater than or equal to 65\n" ); else printf( "Age is less than 65\n" );  ANS: if ( age >= 65 ) /* ; removed */ printf( "Age is greater than or equal to 65\n" ); else printf( "Age is less than 65\n" ); b) int x = 1, total; while ( x <= 10 ) { total += x; ++x; }  ANS: int x = 1, total = 0; while ( x <= 10 ) { total += x; ++x; } c) While ( x <= 100 ) total += x; ++x;  ANS: while ( x <= 100 ) { total += x; ++x; } d) while ( y > 0 ) { printf( "%d\n", y ); ++y; } © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  20 Structured Program Development in C: Solutions  Chapter 3  ANS: while ( y > 0 ) { printf( "%d\n", y ); --y; }  3.12  Fill in the blanks in each of the following: a) The solution to any problem involves performing a series of actions in a specific . ANS: order. b) A synonym for procedure is . ANS: algorithm c) A variable that accumulates the sum of several numbers is a . ANS: total. d) The process of setting certain variables to specific values at the beginning of a program is called . ANS: initialization. e) A special value used to indicate "end of data entry" is called a , a , a or a value. ANS: sentinel value, dummy value, signal value, flag value. f) A is a graphical representation of an algorithm. ANS: flowchart. g) In a flowchart, the order in which the steps should be performed is indicated by symbols. ANS: arrow (flowline). h) The termination symbol indicates the and of every algorithm. ANS: beginning, end. i) Rectangle symbols correspond to calculations that are normally performed by statements and input/output operations that are normally performed by calls to the and standard library functions. ANS: assignment, printf, scanf. j) The item written inside a decision symbol is called a . ANS: condition.  3.13  What does the following program print?  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  #include                                                                              int main() { int x = 1, total = 0, y; while ( x <= 10 ) { y = x * x; printf( "%d\n", y ); total += y; ++x; } printf("Total is %d\n", total); return 0; }  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 3  Structured Program Development in C: Solutions 21  1 4 9 16 25 36 49 64 81 100 Total is 385  3.14  Write a single pseudocode statement that indicates each of the following: a) Display the message "Enter two numbers". ANS: print "enter two numbers" b) Assign the sum of variables x, y, and z to variable p. ANS: p = x + y + z c) The following condition is to be tested in an if…else selection statement: The current value of variable m is greater than twice the current value of variable v. ANS: if m is greater than twice v do this ... else do this ... d) Obtain values for variables s, r, and t from the keyboard. ANS: input s, input r, input t  3.15  Formulate a pseudocode algorithm for each of the following: a) Obtain two numbers from the keyboard, compute the sum of the numbers and display the result. ANS: Input the first number Input the second number Add the two numbers Output the sum b) Obtain two numbers from the keyboard, and determine and display which (if either) is the larger of the two numbers. ANS: Input the first number from the keyboard Input the second number from the keyboard If the first number is greater than the second number print it Else if the second number is greater than the first number print it Else print a message stating that the numbers are equal c) Obtain a series of positive numbers from the keyboard, and determine and display the sum of the numbers. Assume that the user types the sentinel value -1 to indicate "end of data entry." ANS: Input a value from the keyboard While the input value is not equal to -1 add the number to the running total input the next number Print the sum  3.16  State which of the following are true and which are false. If a statement is false, explain why. a) Experience has shown that the most difficult part of solving a problem on a computer is producing a working C program. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  22 Structured Program Development in C: Solutions  Chapter 3  ANS: False. The algorithm is the hardest of solving a problem. b) A sentinel value must be a value that cannot be confused with a legitimate data value. ANS: True. c) Flowlines indicate the actions to be performed. ANS: False. Flowlines indicate the order in which steps are performed. d) Conditions written inside decision symbols always contain arithmetic operators (i.e., +, -, *, /, and %). ANS: False. They normally contain conditional operators. e) In top-down, stepwise refinement, each refinement is a complete representation of the algorithm. ANS: True. For Exercises 3.17 to 3.21, perform each of these steps: 1. Read the problem statement. 2. Formulate the algorithm using pseudocode and top-down, stepwise refinement. 3. Write a C program. 4. Test, debug, and execute the C program. 3.17 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a program that will input the miles driven and gallons used for each tankful. The program should calculate and display the miles per gallon obtained for each tankful. After processing all input information, the program should calculate and print the combined miles per gallon obtained for all tankfuls. Here is a sample input/output dialog:.  Enter the gallons used (-1 to end): 12.8 Enter the miles driven: 287 The miles / gallon for this tank was 22.421875 Enter the gallons used (-1 to end): 10.3 Enter the miles driven: 200 The miles / gallon for this tank was 19.417475 Enter the gallons used (-1 to end): 5 Enter the miles driven: 120 The miles / gallon for this tank was 24.000000 Enter the gallons used (-1 to end): -1 The overall average miles/gallon was 21.601423  ANS: 2)  Top: Determine the average miles/gallon for each tank of gas, and the overall miles/gallon for an arbitrary number of tanks of gas First refinement: Initialize variables Input the gallons used and the miles driven, and calculate and print the miles/gallon for each tank of gas. Keep track of the total miles and the total gallons. Calculate and print the overall average miles/gallon. Second refinement: Initialize totalGallons to zero. Initialize totalMiles to zero. Input the gallons used for the first tank. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 23  Chapter 3  While the sentinel value (-1) has not been entered for the gallons Add gallons to the running total in totalGallons Input the miles driven for the current tank Add miles to the running total in totalMiles Calculate and print the miles/gallon Input the gallons used for the next tank Set totalAverage to totalMiles divided by totalGallons. print the average miles/gallon 3) 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  /* Exercise 3.17 Solution */ #include                                                                                  int main() { double gallons; double miles; double totalGallons = 0.0; double totalMiles = 0.0; double totalAverage;  /* /* /* /* /*  gallons used for current tank*/ miles driven for current tank*/ total gallons used */ total miles driven */ average miles/gallon */  /* get gallons used for first tank */ printf( "Enter the gallons used ( -1 to end): " ); scanf( "%lf", &gallons ); /* loop until sentinel value read from user */ while ( gallons != -1.0 ) { totalGallons += gallons; /* add current tank gallons to total */ printf( "Enter the miles driven: " ); /* get miles driven */ scanf( "%lf", &miles ); totalMiles += miles; /* add current tank miles to total */ /* display miles per gallon for current tank */ printf( "The Miles / Gallon for this tank was %f\n\n", miles / gallons ); /* get next tank's gallons */ printf( "Enter the gallons used ( -1 to end ): " ); scanf( "%lf", &gallons ); } /* end while */ /* calculate average miles per gallon over all tanks */ totalAverage = totalMiles / totalGallons; printf( "\nThe overall average Miles/Gallon was %f\n", totalAverage ); return 0; /* indicate successful termination */ } /* end main */  3.18 Develop a C program that will determine if a department store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available: 1. Account number 2. Balance at the beginning of the month 3. Total of all items charged by this customer this month 4. Total of all credits applied to this customer's account this month 5. Allowed credit limit © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  24 Structured Program Development in C: Solutions  Chapter 3  The program should input each of these facts, calculate the new balance (= beginning balance + charges – credits), and determine if the new balance exceeds the customer's credit limit. For those customers whose credit limit is exceeded, the program should display the customer's account number, credit limit, new balance and the message "Credit limit exceeded." Here is a sample input/ output dialog: Enter account number ( -1 to end): 100 Enter beginning balance: 5394.78 Enter total charges: 1000.00 Enter total credits: 500.00 Enter credit limit: 5500.00 Account: 100 Credit limit: 5500.00 Balance: 5894.78 Credit Limit Exceeded. Enter Enter Enter Enter Enter  account number ( -1 to end ): 200 beginning balance: 1000.00 total charges: 123.45 total credits: 321.00 credit limit: 1500.00  Enter Enter Enter Enter Enter  account number ( -1 to end ): 300 beginning balance: 500.00 total charges: 274.73 total credits: 100.00 credit limit: 800.00  Enter account number ( -1 to end ): -1  ANS: 2)  Top: Determine if each of an arbitrary number of department store customers has exceeded the credit limit on a charge account. First refinement: Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, calcu late the customer's new balance and determine if the balance exceeds the credit limit. Then process the next customer. Second refinement: Input the first customer's account number. While the sentinel value (-1) has not been entered for the account number Input the customer's beginning balance Input the customer's total charges Input the customer's total credits Input the customer's credit limit Calculate the customer's new balance If the balance exceeds the credit limit Print the account number Print the credit limit Print the balance Print "Credit Limit Exceeded" Input the next customer's account number.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 25  Chapter 3  3) 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  /* Exercise 3.18 Solution */ #include                                                                                      int main() { int accountNumber; double balance; double charges; double credits; double limit;  /* /* /* /* /*  current current current current current  account's account's account's account's account's  number */ starting balance */ total charges */ total credits */ credit limit */  /* get account number */ printf( "\nEnter account number ( -1 to end): " ); scanf( "%d", &accountNumber ); /* loop until sentinel value read from user */ while ( accountNumber != -1 ) { printf( "Enter beginning balance: " ); scanf( "%lf", &balance ); printf( "Enter total charges: " ); scanf( "%lf", &charges ); printf( "Enter total credits: " ); scanf( "%lf", &credits ); printf( "Enter credit limit: " ); scanf( "%lf", &limit ); balance += charges - credits; /* calculate balance */ /* if balance is over limit, display account number with credit limit and balance to two digits of precision */ if ( balance > limit ) { printf( "%s%d\n%s%.2f\n%s%.2f\n%s\n", "Account: ", accountNumber, "Credit limit: ", limit, "Balance: ", balance, "Credit Limit Exceeded." ); } /* end if */ /* prompt for next account */ printf( "\nEnter account number ( -1 to end ): " ); scanf( "%d", &accountNumber ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  26 Structured Program Development in C: Solutions  Chapter 3  3.19 One large chemical company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of chemicals in a week receives $200 plus 9% of $5000, or a total of $650. Develop a program that will input each salesperson's gross sales for last week and will calculate and display that salesperson's earnings. Process one salesperson's figures at a time. Here is a sample input/output dialog: Enter sales in dollars ( -1 to end): 5000.00 Salary is: $650.00 Enter sales in dollars ( -1 to end ): 1234.56 Salary is: $311.11 Enter sales in dollars ( -1 to end ): 1088.89 Salary is: $298.00 Enter sales in dollars ( -1 to end ): -1  ANS: 2)  Top: For an arbitrary number of salespeople, determine each salesperson's earnings for the last week. First refinement: Input the salesperson's sales for the week, calculate and print the salesperson's wages for the week, then process the next salesperson. Second refinement: Input the first salesperson's sales in dollars. While the sentinel value (-1) has not been entered for the sales Calculate the salesperson's wages for the week Print the salesperson's wages for the week Input the next salesperson's sales in dollars  3) 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  /* Exercise 3.19 Solution */ #include                                                                                          int main() { double sales; /* gross weekly sales */ double wage; /* commissioned earnings */ /* get first sales */ printf( "Enter sales in dollars ( -1 to end): " ); scanf( "%lf", &sales ); /* loop until sentinel value read from user */ while ( sales != -1.0 ) { wage = 200.0 + 0.09 * sales; /* calculate wage */ /* display salary */ printf( "Salary is: $%.2f\n\n", wage ); /* prompt for next sales */ printf( "Enter sales in dollars ( -1 to end ): " ); scanf( "%lf", &sales ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 27  Chapter 3  3.20  The simple interest on a loan is calculated by the formula interest = principal * rate * days / 365;  The preceding formula assumes that rate is the annual interest rate, and therefore includes the division by 365 (days). Develop a program that will input principal, rate and days for several loans, and will calculate and display the simple interest for each loan, using the preceding formula. Here is a sample input/output dialog:  Enter loan principal ( -1 to end): 1000.00 Enter interest rate: .1 Enter term of the loan in days: 365 The interest charge is $100.00 Enter loan principal ( -1 to end ): 1000.00 Enter interest rate: .08375 Enter term of the loan in days: 224 The interest charge is $51.40 Enter loan principal ( -1 to end ): 10000.00 Enter interest rate: .09 Enter term of the loan in days: 1460 The interest charge is $3600.00 Enter loan principal ( -1 to end ): -1  ANS: 2)  Top: For an arbitrary number of loans determine the simple interest for each loan. First refinement: Input the principal of the loan, the interest rate, and the term of the loan, calculate and print the simple interest for the loan, and process the next loan. Second refinement: input the first loan principal in dollars. While the sentinel value (-1) has not been entered for the loan principal Input the interest rate Input the term of the loan in days Calculate the simple interest for the loan Print the simple interest for the loan Input the loan principal for the next loan  3) 1 2 3 4 5 6 7 8 9 10 11 12 13  /* Exercise 3.20 Solution */ #include                                                                                              int main() { double principal; double rate; double interest; int term;  /* /* /* /*  loan principal */ interest rate */ interest charge */ length of loan in days */  /* get loan principal */ printf( "Enter loan principal ( -1 to end): " ); scanf( "%lf", &principal );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  28 Structured Program Development in C: Solutions  14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  Chapter 3  /* loop until sentinel value is read from user */ while ( principal != -1.0 ) { printf( "Enter interest rate: " ); /* get rate */ scanf( "%lf", &rate ); printf( "Enter term of the loan in days: " ); /* get term */ scanf( "%d", &term ); /* calculate interest charge */ interest = principal * rate * term / 365.0; printf( "The interest charge is $%.2f\n\n", interest ); /* get next loan principal */ printf( "Enter loan principal ( -1 to end ): " ); scanf( "%lf", &principal ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  3.21 Develop a program that will determine the gross pay for each of several employees. The company pays "straight-time" for the first 40 hours worked by each employee and pays "time-and-a-half" for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, and should determine and display the employee's gross pay. Here is a sample input/output dialog:  Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $390.00  ): 39 ): 10.00  Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $400.00  ): 40 ): 10.00  Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $415.00  ): 41 ): 10.00  Enter number of hours worked (  ): -1  ANS: 2)  -1 to end  Top: For an arbitrary number of employees, determine the gross pay for each employee. First refinement: Input the number of hours worked for the employee, enter the employee's hourly wage, calculate and print the employee's gross pay, and process the next employee. Second refinement: Input the first employee's number of hours worked. While the sentinel value (-1) has not been entered for the hours worked Input the employee's hourly wage Calculate the employee's gross pay with overtime for hours over 40 Print the employee's gross pay Input the number of hours worked for the next computer © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 29  Chapter 3  3) 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  /* Exercise 3.21 Solution */ #include                                                                                                  int main( void ) { double hours; /* total hours worked */ double rate; /* hourly pay rate */ double salary; /* gross pay */ /* get first employee's hours worked */ printf( "Enter number of hours worked ( scanf( "%lf", &hours );  -1 to end  ): "  );  /* loop until sentinel value read from user */ while ( hours != -1.0 ) { /* get hourly rate */ printf( "Enter hourly rate of the worker ( scanf( "%lf", &rate );  $00.00  ): "  );  /* if employee worked less than 40 hours */ if ( hours <= 40 ) { salary = hours * rate; } /* end if */ else { /* compute "time-and-a-half" pay */ salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5; } /* end else */ /* display gross pay */ printf( "Salary is $%.2lf\n\n", salary /* prompt for next employee's data */ printf( "Enter number of hours worked ( scanf( "%lf", &hours ); } /* end while */  );  -1 to end  ): "  );  return 0; /* indicate successful termination */ } /* end main */  3.22 Write a program that demonstrates the difference between predecrementing and postdecrementing using the decrement operator --. ANS: 1 2 3 4 5 6 7 8 9 10 11 12  /* Exercise 3.22 Solution */ #include                                                                                                      int main() { int c; /* define c to use decrement operator */ c = 5; printf( "%d\n", c ); printf( "%d\n", --c ); /* predecrement */ printf( "%d\n\n", c );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  30 Structured Program Development in C: Solutions  13 14 15 16 17 18 19 20  Chapter 3  c = 5; printf( "%d\n", c ); printf( "%d\n", c-- ); /* postdecrement */ printf( "%d\n\n", c ); return 0; /* indicate successful termination */ } /* end main */  5 4 4 5 5 4  3.23 Write a program that utilizes looping to print the numbers from 1 to 10 side-by-side on the same line with 3 spaces between each number. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1  /* Exercise 3.23 Solution */ #include                                                                                                          int main() { int i = 0; /* initialize i */ /* loop while i is less than 11 */ while ( ++i < 11 ) { printf( "%d ", i ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */ 2  3  4  5  6  7  8  9  10  3.24 The process of finding the largest number (i.e., the maximum of a group of numbers) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a program that inputs a series of 10 numbers, and determines and prints the largest of the numbers. [Hint: Your program should use three variables as follows]:  counter: number: largest:  A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed) The current number input to the program The largest number found so far  ANS: Input the first number directly into the variable largest Increment counter to 2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 31  Chapter 3  While counter is less than or equal to 10 input a new variable into the variable number If number is greater than largest replace largest with number Increment counter Print the value of the largest (while condition false when counter is 11)  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  /* Exercise 3.24 Solution */ #include                                                                                                              int main() { int counter; /* counter for 10 repetitions */ int number; /* current number input */ int largest; /* largest number found so far */ /* get first number */ printf( "Enter the first number: " ); scanf( "%d", &largest ); counter = 2; /* loop 9 more times */ while ( counter <= 10 ) { printf( "Enter next number: " ); /* get next number */ scanf( "%d", &number ); /* if current number input is greater than largest number, update largest */ if ( number > largest ) { largest = number; } /* end if */ counter++; } /* end while */ printf( "Largest is %d\n", largest ); /* display largest number */ return 0; /* indicate successful termination */ } /* end main */  Enter the first number: 7 Enter next number: 37 Enter next number: 78 Enter next number: 2 Enter next number: 437 Enter next number: 72 Enter next number: 1 Enter next number: 4 Enter next number: 36 Enter next number: 100 Largest is 437  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  32 Structured Program Development in C: Solutions  3.25  Chapter 3  Write a program that utilizes looping to print the following table of values:  N  10 * N 1 2 3 4 5 6 7 8 9 10  10 20 30 40 50 60 70 80 90 100  100 * N 100 200 300 400 500 600 700 800 900 1000  1000 * N 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000  The tab character, \t, may be used in the printf statement to separate the columns with tabs. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 3.26  /* Exercise 3.25 Solution */ #include                                                                                                                  int main() { int n = 0; /* counter */ /* display table headers */ printf( "\tN\t\t10 * N\t\t100 * N\t\t1000 * N\n\n" ); /* loop 10 times */ while ( ++n <= 10 ) { /* calculate and display table values */ printf( "\t%-2d\t\t%-5d\t\t%-5d\t\t%-6d\n", n, 10 * n, 100 * n, 1000 * n ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  Write a program that utilizes looping to produce the following table of values:  A  A+2  A+4  A+6  3 6 9 12 15  5 8 11 14 17  7 10 13 16 19  9 12 15 18 21  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 33  Chapter 3  ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  /* Exercise 3.26 Solution */ #include                                                                                                                      int main() { int a = 3; /* counter */ /* display table headers */ printf( "A\tA+2\tA+4\tA+6\n\n" ); /* loop 5 times */ while ( a <= 15 ) { /* calculate and display table values */ printf( "%d\t%d\t%d\t%d\n", a, a + 2, a + 4, a + 6 ); a += 3; } /* end while */ return 0; /* indicate successful termination */ } /* end main */  3.27 Using an approach similar to Exercise 3.24, find the two largest values of the 10 numbers. [Note: You may input each number only once.] 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  /* Exercise 3.27 Solution */ #include                                                                                                                          int main() { int int int int  counter; number; largest; secondLargest = 0;  /* /* /* /*  counter for 10 current number largest number second largest  repetitions */ input */ found */ number found */  printf( "Enter the first number: " ); /* get first number */ scanf( "%d", &largest ); counter = 2; /* loop 9 more times */ while ( counter <= 10 ) { printf( "Enter next number: " ); /* prompt for next number */ scanf( "%d", &number ); /* if current number is greater than largest */ if ( number > largest ) { /* update second largest with previous largest */ secondLargest = largest; /* update largest with current number */ largest = number; } /* end if */ else {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  34 Structured Program Development in C: Solutions  32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48  Chapter 3  /* if number is between secondLargest and largest */ if ( number > secondLargest ) { secondLargest = number; } /* end if */ } /* end else */ ++counter; } /* end while */ /* display largest two numbers */ printf( "Largest is %d\n", largest ); printf( "Second largest is %d\n", secondLargest ); return 0; /* indicate successful termination */ } /* end main */  Enter the first number: 100 Enter next number: 102 Enter next number: 83 Enter next number: 3883 Enter next number: 328 Enter next number: 28 Enter next number: 839 Enter next number: 2398 Enter next number: 182 Enter next number: 0 Largest is 3883 Second largest is 2398  3.28 Modify the program in Figure 3.10 to validate its inputs. On any input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value. 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 3.28 Solution */ #include                                                                                                                              int main() { int passes = 0; int failures = 0; int student = 1; int result;  /* /* /* /*  number of passes */ number of failures */ student counter */ one exam result */  /* process 10 students using counter-controlled loop */ while ( student <= 10 ) { /* prompt user for input and obtain value from user */ printf( "Enter result ( 1=pass, 2=fail ): " ); scanf( "%d", &result ); /* loop until valid input */ while ( result != 1 && result != 2 ) { printf( "Invalid result\nEnter result ( 1=pass, 2=fail ): " ); scanf( "%d", &result ); } /* end inner while */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 35  Chapter 3  24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44  /* if result 1, increment passes */ if ( result == 1 ) { ++passes; } /* end if */ else { /* if result is not 1, increment failures */ ++failures; } /* end else */ ++student; } /* end while */ printf( "Passed %d\nFailed %d\n", passes, failures ); /* if more than eight students passed, print "raise tuition" */ if ( passes >= 8 ) { printf( "Raise tuition\n" ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */  Enter result ( Enter result ( Enter result ( Invalid result Enter result ( Invalid result Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Passed 6 Failed 4  3.29 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  1=pass, 2=fail ): 1 1=pass, 2=fail ): 2 1=pass, 2=fail ): 3 1=pass, 2=fail ): 4 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass,  2=fail 2=fail 2=fail 2=fail 2=fail 2=fail 2=fail 2=fail  ): ): ): ): ): ): ): ):  2 2 2 1 1 1 1 1  What does the following program print? #include                                                                                                                                  /* function main begins program execution */ int main() { int count = 1; /* initialize count */ while ( count <= 10 ) { /* loop 10 times */ /* output line of text */ printf( "%s\n", count % 2 ? "****" : "++++++++" ); count++; /* increment count */ } /* end while */ return 0; /* indicate program ended successfully */ } /* end function main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  36 Structured Program Development in C: Solutions  ANS:  **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++  3.30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  What does the following program print? #include                                                                                                                                      /* function main begins program execution */ int main() { int row = 10; /* initialize row */ int column; /* define column */ while ( row >= 1 ) { /* loop until row < 1 */ column = 1; /* set column to 1 as iteration begins */ while ( column <= 10 ) { /* loop 10 times */ printf( "%s", row % 2 ? "<": ">" ); /* output */ column++; /* increment column */ } /* end inner while */ row--; /* decrement row */ printf( "\n" ); /* begin new output line */ } /* end outer while */ return 0; /* indicate program ended successfully */ } /* end function main */  ANS:  >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<<  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 3  Structured Program Development in C: Solutions 37  Chapter 3  3.31 (Dangling Else Problem) Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. Note that the compiler ignores the indentation in a C program. Also, the compiler always associates an else with the previous if unless told to do otherwise by the placement of braces {}. Because, on first glance, the programmer may not be sure which if an else matches, this is referred to as the "dangling else" problem. We have eliminated the indentation from the following code to make the problem more challenging. [Hint: Apply indentation conventions you have learned.] a) if ( x < 10 ) if ( y > 10 ) printf( "*****\n" ); else printf( "#####\n" ); printf( "$$$$$\n" );  ANS: x = 9, y = 11  ***** $$$$$  x = 11, y = 9  $$$$$  b) if ( x < 10 ) { if ( y > 10 ) printf( "*****\n" ); } else { printf( "#####\n" ); printf( "$$$$$\n" ); }  ANS: x = 9, y = 11  *****  x = 11, y = 9  ##### $$$$$  3.32 (Another Dangling Else Problem) Modify the following code to produce the output shown. Use proper indentation techniques. You might not make any changes other than inserting braces. The compiler ignores the indentation in a program. We have eliminated the indentation from the following code to make the problem more challenging. [Note: It is possible that no modification is necessary.] if ( y == 8 ) if ( x == 5 ) printf( "@@@@@\n" else printf( "#####\n" printf( "$$$$$\n" printf( "&&&&&\n"  ); ); ); );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  38 Structured Program Development in C: Solutions  Chapter 3  a) Assuming x = 5 and y = 8, the following output is produced. @@@@@ $$$$$ &&&&&  ANS: if ( y == 8 ) { if ( x == 5 ) printf( "@@@@@\n" ); else printf( "#####\n" ); printf( "$$$$$\n" ); printf( "&&&&&\n" ); }  b) Assuming x = 5 and y = 8, the following output is produced. @@@@@  ANS: if ( y == 8 ) if ( x == 5 ) printf( "@@@@@\n" else { printf( "#####\n" printf( "$$$$$\n" printf( "&&&&&\n" }  ); ); ); );  c) Assuming x = 5 and y = 8, the following output is produced. @@@@@ &&&&&  ANS: if ( y == 8 ) if ( x == 5 ) printf( "@@@@@\n" ); else { printf( "#####\n" ); printf( "$$$$$\n" ); } printf( "&&&&&\n" );  d) Assuming x = 5 and y = 7, the following output is produced. [Note: The last three printf statements are all part of a compound statement. ##### $$$$$ &&&&&  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 39  Chapter 3  ANS: if ( y == 8 ) { if ( x == 5 ) printf( "@@@@@\n" ); } else { printf( "#####\n" ); printf( "$$$$$\n" ); printf( "&&&&&\n" ); }  3.33 Write a program that reads in the side of a square and then prints that square out of asterisks. Your program should work for squares of all side sizes between 1 and 20. For example, if your program reads a size of 4, it should print **** **** **** ****  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  /* Exercise 3.33 Solution */ #include                                                                      int main() { int side; /* side counter */ int temp; /* temporary integer */ int asterisk; /* asterisk counter */ printf( "Enter the square side: " ); /* get size of square */ scanf( "%d", &side ); temp = side; /* loop through rows of square */ while ( side-- > 0 ) { asterisk = temp; /* loop through columns of square */ while ( asterisk-- > 0 ) { printf( "*" ); } /* end inner while */ putchar( '\n' ); } /* end outer while */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  40 Structured Program Development in C: Solutions  Chapter 3  3.34 Modify the program you wrote in Exercise 3.33 so that it prints a hollow square. For example, if your program reads a size of 5, it should print ***** * * * * * * *****  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  /* Exercise 3.34 Solution */ #include                                                                        int main() { int side; /* side counter */ int rowPosition; /* row counter */ int size; /* length of side */ printf( "Enter the square side: " ); /* prompt for side length */ scanf( "%d", &side ); size = side; /* set size counter to length of side */ /* loop side number of times */ while ( side > 0 ) { rowPosition = size; /* set row counter to length of size */ /* loop rowPosition number of times */ while ( rowPosition > 0 ) { /* if side or row counter is 1 or size print an '*' */ if ( size == side ) { printf( "*" ); } /* end if */ else if ( side == 1 ) { printf( "*" ); } /* end else if */ else if ( rowPosition == 1 ) { printf( "*" ); } /* end else if */ else if ( rowPosition == size ) { printf( "*" ); } /* end else if */ else { /* otherwise, print a space */ printf( " " ); } /* end else */ --rowPosition; /* decrement row counter */ } /* end inner while */ printf( "\n" ); /* new line for next row */ --side; /* decrement side counter */ } /* end outer while */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 41  Chapter 3  3.35 A palindrome is a number or a text phrase that reads the same backwards as forwards. For example, each of the following five-digit integers are palindromes: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and determines whether or not it is a palindrome. [Hint: Use the division and remainder operators to separate the number into its individual digits.] 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 53 54 55  /* Exercise 3.35 Solution */ #include                                                                          int main() { int number; int temp1; int temp2; int firstDigit; int secondDigit; int fourthDigit; int fifthDigit;  /* /* /* /* /* /* /*  input number */ first temporary integer */ second temporary integer */ first digit of input */ second digit of input */ fourth digit of input */ fifth digit of input */  printf( "Enter a five-digit number: " ); /* get number */ scanf( "%d", &number ); temp1 = number; /* determine first digit by integer division by 10000 */ firstDigit = temp1 / 10000; temp2 = temp1 % 10000; /* determine second digit by integer division by 1000 */ secondDigit = temp2 / 1000; temp1 = temp2 % 1000; temp2 = temp1 % 100; /* determine fourth digit by integer division by 10 */ fourthDigit = temp2 / 10; temp1 = temp2 % 10; fifthDigit = temp1; /* if first and fifth digits are equal */ if ( firstDigit == fifthDigit ) { /* if second and fourth digits are equal */ if ( secondDigit == fourthDigit ) { /* number is a palindrome */ printf( "%d is a palindrome\n", number ); } /* end if */ else { /* number is not a palindrome */ printf( "%d is not a palindrome\n", number ); } /* end else */ } /* end if */ else { /* number is not a palindrome */ printf( "%d is not a palindrome\n", number ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  42 Structured Program Development in C: Solutions  Chapter 3  Enter a five-digit number: 18181 18181 is a palindrome  Enter a five-digit number: 16738 16738 is not a palindrome  3.36 Input an integer containing only 0s and 1s (i.e., a "binary" integer) and print its decimal equivalent. [Hint: Use the remainder and division operators to pick off the "binary" number's digits one at a time from right to left. Just as in the decimal number system in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10, then 100, then 1000, etc., in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, etc. Thus the decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.] 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  /* Exercise 3.36 Solution */ #include                                                                            int main() { int binary; int number; int decimal = 0; int highBit = 16; int factor = 10000;  /* /* /* /* /*  current value of binary number */ input binary number */ current value of decimal number */ value of highest bit */ factor of 10 to pick off digits */  /* prompt for binary input */ printf( "Enter a binary number ( 5 digits maximum ): " ); scanf( "%d", &binary ); number = binary; /* save in number for final display */ /* loop 5 times using powers of 2 */ while ( highBit >= 1 ) { /* update decimal value with decimal value corresponding to current highest binary bit */ decimal += binary / factor * highBit; /* reduce high bit by factor of 2, i.e., move one bit to the right */ highBit /= 2; /* reduce binary number to eliminate current highest bit */ binary %= factor; /* reduce factor by power of 10, i.e., move one bit to the right */ factor /= 10; } /* end while */ /* display decimal value */ printf( "The decimal equivalent of %d is %d\n", number, decimal ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 43  Chapter 3  Enter a binary number ( 5 digits maximum ): 10111 The decimal equivalent of 10111 is 23  Enter a binary number ( 5 digits maximum ): 1101 The decimal equivalent of 1101 is 13  3.37 How can you determine how fast your own computer really operates? Write a program with a while loop that counts from 1 to 300,000,000 by 1s. Every time the count reaches a multiple of 100,000,000 print that number on the screen. Use your watch to time how long each million repetitions of the loop takes. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  /* Exercise 3.37 Solution */ #include                                                                              int main() { long int count = 1; /* counter */ /* loop to 300,000,000 */ while( count <= 300000000 ) { if ( count % 100000000 == 0 ) { printf( "Multiple is %d\n", count / 100000000 ); } /* end if */ ++count; /* increment count */ } /* end while */ return 0; /* indicate successful termination */ } /* end main */  Multiple is 1 Multiple is 2 Multiple is 3  3.38 Write a program that prints 100 asterisks, one at a time. After every tenth asterisk, your program should print a newline character. (Hint: Count from 1 to 100. Use the remainder operator to recognize each time the counter reaches a multiple of 10.) ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  /* Exercise 3.38 Solution */ #include                                                                                                                                                              int main() { int count = 0; /* counter */ /* loop to 100 */ while( ++count <= 100 ) /* print a new line after every 10th asterisk */ count % 10 == 0 ? printf( "*\n" ) : printf( "*" );  return 0; /* indicate successful termination */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  44 Structured Program Development in C: Solutions  15 16  } /* end main */  ********** ********** ********** ********** ********** ********** ********** ********** ********** **********  3.39  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  Write a program that reads an integer and determines and prints how many digits in the integer are 7s. ANS: /* Exercise 3.39 Solution */ #include                                                                                                                                                                  int main() { int number; /* user input */ int numCopy; /* copy of number */ int factor = 10000; /* set factor to pick off digits */ int digit; /* individual digit of number */ int sevens = 0; /* sevens counter */ printf( "Enter a 5-digit number: " ); /* get number from user */ scanf( "%d", &number ); numCopy = number; /* loop through each of the 5 digits */ while ( factor >= 1 ) { digit = numCopy / factor; /* pick off next digit */ if ( digit == 7 ) { /* if digit equals 7, increment sevens */ ++sevens; } /* end if */ numCopy %= factor; factor /= 10; } /* end while */ /* output number of sevens */ printf( "The number %ld has %d seven(s) in it\n", number, sevens ); return 0; /* indicate successful termination */ } /* end main */  Enter a 5-digit number: 17737 The number 17737 has 3 seven(s) in it  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 3  Structured Program Development in C: Solutions 45  Chapter 3  Enter a 5-digit number: 11727 The number 11727 has 2 seven(s) in it  3.40  Write a program that displays the following checkerboard pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  Your program must use only three output statements, one of each of the following forms: printf( "* " ); printf( " " ); printf( "\n" );  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  /* Exercise 3.40 Solution */ #include                                                                                                                                                                      int main() { int side = 8; /* side counter */ int row; /* row counter */ int mod; /* remainder */ /* loop 8 times */ while ( side >= 1 ) { row = 8; /* reset row counter */ mod = side % 2; /* loop 8 times */ while ( row >= 1 ) { /* if odd row, begin with a space */ if ( mod != 0 ) { printf( " " ); mod = 0; } /* end if */ printf( "* " ); --row; } /* end while */ printf( "\n" ); /* go to next line */ --side; } /* end while */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  46 Structured Program Development in C: Solutions  Chapter 3  3.41 Write a program that keeps printing the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite loop). What happens when you run this program? ANS: Program execution terminates when largest integer is exceeded (i.e., the loop continuation test fails when the maximum value for an integer is exceeded. On a 4-byte system, the largest integer value is 2147483647 and anything above that is represented by a negative number, which fails the loop continuation test). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  /* Exercise 3.41 Solution */ #include                                                                                                                                                                          int main() { int multiple = 1; /* counter */ /* infinite loop */ while ( multiple > 0 ) { /* calculate the next power of two */ multiple *= 2; printf( "%d\n", multiple ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648  3.42 Write a program that reads the radius of a circle (as a float value) and computes and prints the diameter, the circumference and the area. Use the value 3.14159 for Ï€. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 47  Chapter 3  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 3.42 Solution */ #include                                                                                        int main() { float radius; /* input radius */ float pi = 3.14159; /* value for pi */ printf( "Enter the radius: "); /* get radius value */ scanf( "%f", &radius ); /* compute and display diameter */ printf( "The diameter is %.2f\n", radius * 2 ); /* compute and display circumference */ printf( "The circumference is %.2f\n", 2 * pi * radius ); /* compute and display area */ printf( "The area is %.2f\n", pi * radius * radius ); return 0; /* indicate successful termination */ } /* end main */  Enter the radius: 4.7 The diameter is 9.40 The circumference is 29.53 The area is 69.40  3.43 What is wrong with the following statement? Rewrite the statement to accomplish what the programmer was probably trying to do. printf( "%d", ++( x + y ) );  ANS: printf( "%d", 1 + x + y ); 3.44 Write a program that reads three nonzero float values and determines and prints if they could represent the sides of a triangle. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  /* Exercise 3.44 Solution */ #include                                                                                                                                                                                  int main() { double a; /* first number */ double b; /* second number */ double c; /* third number */ /* input 3 numbers */ printf( "Enter three doubleing point numbers: " ); scanf( "%lf%lf%lf", &a, &b, &c); /* use Pythagorean Theorem */ if ( c * c == a * a + b * b ) { printf( "The three numbers could be sides of a triangle\n" ); } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  48 Structured Program Development in C: Solutions  18 19 20 21 22 23 24 25  Chapter 3  else { printf( "The three numbers probably"); printf( " are not the sides of a triangle\n" ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */  Enter three doubleing point numbers: 5.7 3.6 2.2 The three numbers probably are not the sides of a triangle  Enter three doubleing point numbers: 3.0 4.0 5.0 The three numbers could be sides of a triangle  3.45  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  Write a program that reads three nonzero integers and determines and prints if they could be the sides of a right triangle. ANS: /* Exercise 3.45 Solution */ #include                                                                                                                                                                                      int main() { int a; /* first number */ int b; /* second number */ int c; /* third number */ /* input three numbers */ printf( "Enter three integers: "); scanf( "%d%d%d", &a, &b, &c ); /* use Pythagorean Theorem */ if ( c * c == a * a + b * b ) { printf( "The three integers are the sides of"); printf( " a right triangle\n" ); } /* end if */ else { printf( "The three integers are not the sides"); printf( " of a right triangle\n" ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  Enter three integers: 3 4 5 The three integers are the sides of a right triangle  Enter three integers: 9 4 1 The three integers are not the sides of a right triangle  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 49  Chapter 3  3.46 A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of their data is transmitted as four-digit integers. They have asked you to write a program that will encrypt their data so that it may be transmitted more securely. Your program should read a four-digit integer and encrypt it as follows: Replace each digit by the remainder after (the sum of that digit plus 7) is divided by 10. Then, swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer. Write a separate program that inputs an encrypted four-digit integer and decrypts it to form the original number. 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 3.46 Part A solution */ #include                                                                                                                                                                                          int main() { int first; /* first digit replacement */ int second; /* second digit replacement */ int third; /* third digit replacement */ int fourth; /* fourth digit replacement */ int digit; /* input number */ int temp1; /* temporarily hold digit */ int temp2; /* temporarily hold digit */ int encryptedNumber; /* resulting encrypted number */ /* prompt for input */ printf( "Enter a four digit number to be encrypted: " ); scanf( "%d", &digit ); temp1 = digit; /* retrieve each digit and replace with (sum of digit and 7) mod 10 */ first = ( temp1 / 1000 + 7 ) % 10; temp2 = temp1 % 1000; second = ( temp2 / 100 + 7 ) % 10; temp1 = temp2 % 100; third = ( temp1 / 10 + 7 ) % 10; temp2 = temp1 % 10; fourth = ( temp2 + 7 ) % 10; /* swap temp1 = first = third =  first and third */ first; third * 1000; /* multiply by 1000 for 1st digit component */ temp1 * 10; /* multiply by 10 for 3rd digit component */  /* swap second and fourth */ temp1 = second; second = fourth * 100; /* multiply by 100 for 2nd digit component */ fourth = temp1 * 1; /* add components to obtain encrypted number */ encryptedNumber = first + second + third + fourth; /* display encrypted number */ printf( "Encrypted number is %d\n", encryptedNumber ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  50 Structured Program Development in C: Solutions  Enter a four digit number to be encrypted: 5678 Encrypted number is 4523  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  /* Exercise 3.46 Part B Solution */ #include                                                                                                                                                                                              int main() { int first; /* first decrypted digit */ int second; /* second decrypted digit */ int third; /* third decrypted digit */ int fourth; /* fourth decrypted digit */ int decrypted; /* decrypted number */ int temp1; /* temporarily hold digit */ int temp2; /* temporarily hold digit */ int encryptedNumber; /* input number */ /* prompt for input */ printf( "Enter a four digit encrypted number: " ); scanf( "%d", &encryptedNumber ); temp1 = encryptedNumber; /* retrieve each digit and decrypt by (sum of digit and 3) mod 10 */ first = ( temp1 / 1000 ); temp2 = temp1 % 1000; second = ( temp2 / 100 ); temp1 = temp2 % 100; third = ( temp1 / 10 ); temp2 = temp1 % 10; fourth = temp2; temp1 = ( first + 3 ) % 10; first = ( third + 3 ) % 10; third = temp1; temp1 = ( second + 3 ) % 10; second = ( fourth + 3 ) % 10; fourth = temp1; /* add components to obtain decrypted number */ decrypted = ( first * 1000 ) + ( second * 100 ) + ( third * 10 ) + fourth; /* display decrypted number */ printf( "Decrypted number is %d\n", decrypted ); return 0; /* indicate successful termination */ } /* end main */  Enter a four digit encrypted number: 4523 Decrypted number is 5678  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 3  Structured Program Development in C: Solutions 51  Chapter 3  1.1  The factorial of a nonnegative integer n is written n! (pronounced "n factorial") and is defined as follows: n! = n · (n - 1) · (n - 2) · … · 1 (for values of n greater than or equal to 1)  and n! = 1 (for n = 0). For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. a) Write a program that reads a nonnegative integer and computes and prints its factorial. 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  /* Exercise 3.47 Part A Solution */ #include                                                                                                                                                                                                  int main() { int n; /* current multiplication factor */ int number = -1; /* input number */ unsigned factorial = 1; /* resulting factorial */ /* loop until valid input */ do { printf( "Enter a positive integer: " ); scanf( "%d", &number ); } while ( number < 0 ); /* end do...while */ n = number; /* compute factorial */ while( n >= 0 ) { if ( n == 0 ) { factorial *= 1; } /* end if */ else { factorial *= n; } /* end else */ --n; } /* end while */ /* display factorial */ printf( "%d! is %u\n", number, factorial ); return 0; /* indicate successful termination */ } /* end main */  Enter a positive integer: 5 5! is 120  Enter a positive integer: 9 9! is 362880  Enter a positive integer: -8 Enter a positive integer: 0 0! is 1  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  52 Structured Program Development in C: Solutions  Chapter 3  b) Write a program that estimates the value of the mathematical constant e by using the formula: 1- + ---1- + ---1- + … e = 1 + ---1! 2! 3! 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  /* Exercise 3.47 Part B Solution */ #include                                                                                                                                                                                                      int main() { int n = 0; /* int fact = 1; /* int accuracy = 10; /* double e = 0; /*  loop counter for accuracy */ current n factorial */ degree of accuracy */ current estimated value of e */  /* loop until degree of accuracy */ while( n <= accuracy ) { if ( n == 0 ) { fact *= 1; } /* end if */ else { fact *= n; } /* end else */ e += 1.0 / fact; ++n; } /* end while */ printf( "e is %f\n", e ); /* display estimated value */ return 0; /* indicate successful termination */ } /* end main */  e is 2.718282  c) Write a program that computes the value of ex by using the formula 2  3  x x- x x e = 1 + ---+ ----- + ----- + … 1! 2! 3!  ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  /* Exercise 3.47 Part C Solution */ #include                                                                                                                                                                                                          int main() { int n = 0; int accuracy = 15; int x = 3; int times = 0; int count; double e = 1.0; double exp = 0.0; double fact = 1.0;  /* /* /* /* /* /* /* /*  counter */ degree of accuracy */ exponent */ counter */ copy of n */ e raised to the x power */ x raised to the n power */ n factorial */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structured Program Development in C: Solutions 53  Chapter 3  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  /* loop while less than degree of accuracy */ while( n <= accuracy ) { count = n; /* update n! */ if ( n == 0 ) { fact *= 1.0; } /* end if */ else { fact *= n; } /* end else */ while ( times < count ) { /* calculate x raised to the n power */ if ( times == 0 ) { exp = 1.0; exp *= x; } /* end if */ else { exp *= x; } /* end else */ ++times; } /* end while */ e += exp / fact; /* update e raised to the x power */ ++n; } /* end while */ /* display result */ printf( "e raised to the %d power is %f\n", x, e ); return 0; /* indicate successful termination */ } /* end main */  e raised to the 3 power is 20.085534  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  54 Structured Program Development in C: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 3  4 C Program Control: Solutions  SOLUTIONS 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 <=. Semicolons are needed between the for conditions, not comma operators. 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" ); 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 );  ANS: charVal will read the return 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 ); printf( "Integer: %d\nCharacter: %c\n", intVal, charVal );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  56 C Program Control: Solutions  Chapter 4  d) for ( x = .000001; x <= .0001; x += .000001 ) printf( "%.7f\n", x ); ANS: Floating point numbers should never be used in loops 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 );  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;  ANS: 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  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: /* increments of 5 */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 57  Chapter 4  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 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  What does the following program do? #include                                                                                                                                                                                                              /* function main begins program execution */ int main() { int x; int y; int i; 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:  Enter integers in the range 1-20: 3 4 @@@ @@@ @@@ @@@  4.9 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 5 100 200 300 400 500  where the 5 indicates that the subsequent five values are to be summed.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  58 C Program Control: Solutions  Chapter 4  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  /* Exercise 4.9 Solution */ #include                                                                                                                                                                                                                  int main( void ) { int sum = 0; /* int number; /* int value; /* int i; /*  current sum */ 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++ ) { 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  4.10 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 10 8 11 7 9 9999  indicating that the average of all the values preceding 9999 is to be calculated. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13  /* Exercise 4.10 Solution */ #include                                                                                                                                                                                                                      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 );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 59  Chapter 4  14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  /* 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 */ 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  4.11 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  /* Exercise 4.11 Solution */ #include                                                                                                                                                                                                                          int main( void ) { int number; int value; int smallest; int i;  /* /* /* /*  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 );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  60 C Program Control: Solutions  24 25 26 27 28 29 30 31 32 33 34 35  /* 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 */ } /* 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  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  Write a program that calculates and prints the sum of the even integers from 2 to 30. ANS: /* Exercise 4.12 Solution */ #include                                                                                                                                                                                                                              int main( void ) { int i; /* counter */ int sum = 0; /* current sum of integers */ /* loop through even integers up to 30 */ for ( i = 2; i <= 30; i += 2 ) { sum += i; /* add i to sum */ } /* end for */ 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  1 2 3 4 5 6 7 8  Write a program that calculates and prints the product of the odd integers from 1 to 15. ANS: /* Exercise 4.13 Solution */ #include                                                                                                                                                                                                                                  int main( void ) { long i; /* counter */ long product = 1; /* current product */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 4  C Program Control: Solutions 61  Chapter 4  9 10 11 12 13 14 15 16 17 18  /* 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 ); return 0; /* indicate successful termination */ } /* end main */  Product of the odd integers from 1 to 15 is: 2027025  4.14 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: 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 X 1 2 3 4 5  /* Exercise 4.14 Solution */ #include                                                                                                                                                                                                                                      int main( void ) { int i; /* outer counter */ int j; /* inner counter */ int factorial; /* current factorial value */ printf( "X\tFactorial of X\n" ); /* display table headers */ /* compute the factorial for 1 to 5 */ for ( i = 1; i <= 5; i++ ) { factorial = 1; /* 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  4.15 Modify the compound interest program of Section 4.6 to repeat its steps for interest rates of 5 percent, 6 percent, 7 percent, 8 percent, 9 percent, and 10 percent. Use a for loop to vary the interest rate.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  62 C Program Control: Solutions  Chapter 4  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  /* Exercise 4.15 Solution */ #include                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                              int main( void ) { int year; int rate; double amount; double principal = 1000.0;  /* /* /* /*  year counter */ interest rate */ amount on deposit */ starting principal */  /* loop through interest rates 5% to 10% */ for ( rate = 5; rate <= 10; rate++ ) { /* display table headers */ printf( "Interest Rate: %f\n", rate / 100.0 ); printf( "%s%21s\n", "Year","Amount on deposit" ); /* calculate amount on deposit for each of ten years */ for ( year = 1; year <= 10; year++ ) { /* calculate new amount for specified year */ amount = principal * pow( 1 + ( rate / 100.0 ), year ); /* output one table row */ printf( "%4d%21.2f\n", year, amount ); } /* end for */ printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 63  Chapter 4  Interest Rate: 0.050000 Year Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89 ... Interest Rate: 0.080000 Year Amount on deposit 1 1080.00 2 1166.40 3 1259.71 4 1360.49 5 1469.33 6 1586.87 7 1713.82 8 1850.93 9 1999.00 10 2158.92 ... Interest Rate: 0.100000 Year Amount on deposit 1 1100.00 2 1210.00 3 1331.00 4 1464.10 5 1610.51 6 1771.56 7 1948.72 8 2143.59 9 2357.95 10 2593.74  4.16 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.]  (A) * ** *** **** ***** ****** ******* ******** ********* **********  (B) (C) ************ ************ *********** *********** ********* ********** ******* ********* ****** ****** ***** ***** **** **** *** *** ** ** * *  (D) * ** *** **** ***** ****** ******* ******** ********* **********  ANS: 1 2 3 4 5 6  /* Exercise 4.16 Solution */ #include                                                                                                                                                                                                                                                  int main( void ) { int row; /* row counter */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  64 C Program Control: Solutions  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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  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 */ printf( "\n" ); /* 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 */ 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 */ 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 */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 4  C Program Control: Solutions 65  Chapter 4  68 69 70 71 72 73 74 75 76  printf( "\n" ); } /* end for */ printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */  4.17 Collecting money becomes increasingly difficult during periods of recession, so companies may tighten their credit limits to prevent their accounts receivable (money owed to them) from becoming too large. In response to a prolonged recession, one company has cut its customer's credit limits in half. Thus, if a particular customer had a credit limit of $2000, this customer's credit limit is now $1000. If a customer had a credit limit of $5000, this customer's credit limit is now $2500. Write a program that analyzes the credit status of three customers of this company. For each customer you are given: a) The customer's account number b) The customer's credit limit before the recession c) The customer's current balance (i.e., the amount the customer owes the company). Your program should calculate and print the new credit limit for each customer and should determine (and print) which customers have current balances that exceed their new credit limits. 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  /* Exercise 4.17 Solution */ #include                                                                                                                                                                                                                                                      int main( void ) { int account; int i; double limit; double balance; double newLimit;  /* /* /* /* /*  current account number */ counter */ current credit limit */ current balance */ new credit limit */  /* loop three times */ for ( i = 1; i <= 3; i++ ) { /* get account number, credit limit and balance */ printf( "\nEnter account, limit, balance: " ); scanf( "%d%lf%lf", &account, &limit, &balance ); newLimit = limit / 2.0; /* calculate new limit */ printf( "New credit limit for account %d is %.2f\n", account, newLimit ); /* if balance is greater than new credit limit */ if ( balance > newLimit ) { printf( "Limit exceeded for account %d\n", account ); } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  66 C Program Control: Solutions  Chapter 4  Enter account, limit, balance: 100 4000.00 2136.87 New credit limit for account 100 is 2000.00 Limit exceeded for account 100 Enter account, limit, balance: 200 10500.00 4927.39 New credit limit for account 200 is 5250.00 Enter account, limit, balance: 300 1000.00 750.00 New credit limit for account 300 is 500.00 Limit exceeded for account 300  4.18 One interesting application of computers is drawing graphs and bar charts (sometimes called "histograms"). Write a program that reads five numbers (each between 1 and 30). For each number read, your program should print a line containing that number of adjacent asterisks. For example, if your program reads the number seven, it should print *******. 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  /* Exercise 4.18 Solution */ #include                                                                                                                                                                                                                                                          int main( void { int i; int j; int number;  ) /* outer counter */ /* inner counter */ /* current number */  printf( "Enter 5 numbers between 1 and 30: " ); /* loop 5 times */ for ( i = 1; i <= 5; i++ ) { scanf( "%d", &number ); /* print asterisks corresponding to current input */ for ( j = 1; j <= number; j++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter 5 numbers between 1 and 30: 28 5 13 24 7 **************************** ***** ************* ************************ *******  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 67  Chapter 4  4.19  A mail order house sells five different products whose retail prices are shown in the following table:  Product number  Retail price  1  $ 2.98  2  $ 4.50  3  $ 9.98  4  $ 4.49  5  $ 6.87  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 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  /* Exercise 4.19 Solution */ #include                                                                                                                                                                                                                                                              int main( void ) { int product; /* current product number */ int quantity; /* quantity of current product sold */ double total = 0.0; /* current total retail value */ /* 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; case 3: total += quantity * 9.98; /* update total */ break; case 4: total += quantity * 4.49; /* update total */ break; case 5: total += quantity * 6.87; /* update total */ break; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  68 C Program Control: Solutions  41 42 43 44 45 46 47 48 49 50 51 52 53 54 55  Chapter 4  default: printf( "Invalid product code: printf( " Quantity: } /* end switch */  %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  4.20  Complete the following truth tables by filling in each blank with 0 or 1 ANS: .  &&  Condition1  Condition2  Condition1  0  0  0  0  nonzero  0  nonzero  0  0  nonzero  nonzero  1  Condition1  Condition2  Condition1 || Condition2  0  0  0  0  nonzero  1  nonzero  0  1  nonzero  nonzero  1  Condition1  !Condition1  0  1  nonzero  0  Condition2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 69  Chapter 4  4.21 Rewrite the program of Fig. 4.2 so that the initialization of the variable counter is done in the definition instead of the for statement. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  /* Exercise 4.21 Solution */ #include                                                                                                                                                                                                                                                                  int main( void ) { int counter = 1; /* initialize counter */ /* leave first statement empty */ for ( ; counter <= 10; counter++ ) { printf( "%d\n", counter ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  1 2 3 4 5 6 7 8 9 10  4.22  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  Modify the program of Fig. 4.7 so that it calculates the average grade for the class. ANS: /* Exercise 4.22 Solution */ #include                                                                                                                                                                                                                                                                      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 ) { /* determine which grade was input */ switch ( grade ) { case 'A': /* grade was uppercase A */ case 'a': /* grade was lowercase a */ ++aCount; /* update grade A counter */ break; /* exit switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  70 C Program Control: Solutions  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 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  Chapter 4  case 'B': case 'b': ++bCount; break;  /* /* /* /*  grade was uppercase B */ grade was lowercase b */ update grade B counter */ exit switch */  case 'C': case 'c': ++cCount; break;  /* /* /* /*  grade was uppercase C */ grade was lowercase c */ update grade C counter */ exit switch */  case 'D': case 'd': ++dCount; break;  /* /* /* /*  grade was uppercase C */ grade was lowercase c */ update grade C counter */ exit switch */  case 'F': case 'f': ++fCount; break;  /* /* /* /*  grade was uppercase C */ grade was lowercase c */ update grade C counter */ exit switch */  case '\n': case '\t': case ' ': break;  /* /* /* /*  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  grade */ each letter grade are:\n" ); ); ); ); ); );  /* calculate average grade */ averageGrade = ( 4 * aCount + 3 * bCount + 2 * cCount + dCount ( aCount + bCount + cCount + dCount + fCount ); /* output appropriate message for if ( averageGrade > 3.4 ) { printf( "Average grade is A\n" } /* end if */ else if ( averageGrade > 2.4 ) { printf( "Average grade is B\n" } /* end else if */ else if ( averageGrade > 1.4 ) { printf( "Average grade is C\n" } /* end else if */ else if ( averageGrade > 0.4 ) { printf( "Average grade is D\n" } /* end else if */  ) /  average grade */ );  );  );  );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 71  Chapter 4  88 89 90 91 92 93 94  else { printf( "Average grade is F\n" ); } /* end else */ 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.23 Modify the program of Fig. 4.6 so that it uses only integers to calculate the compound interest. [Hint: Treat all monetary amounts as integral numbers of pennies. Then "break" the result into its dollar portion and cents portion by using the division and remainder operations, respectively. Insert a period.] 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  /* Exercise 4.23 Solution */ #include                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                              int main( void ) { int year; int amount; int dollars; int cents; int principal = 100000; double rate = .05;  /* /* /* /* /* /*  year counter */ amount on deposit, in pennies */ dollar portion of amount */ cents portion of amount */ starting principal, in pennies ($1000) */ interest rate */  /* display headers for table */ printf( "%s%21s\n", "Year", "Amount on deposit" ); /* loop 10 times */ for ( year = 1; year <= 10; year++ ) { /* determine new amount (in pennies) */ amount = principal * pow( 1.0 + rate, year ); /* determine cents portion of amount (last two digits) */ cents = amount % 100; /* determine dollars portion of amount */ /* integer division truncates decimal places */ dollars = amount / 100; /* display year, dollar portion followed by period */ printf( "%4d%18d.", year, dollars );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  72 C Program Control: Solutions  33 34 35 36 37 38 39 40 41 42 43 44 45 46  /* display cents portion */ /* if cents portion only 1 digit, insert 0 */ if ( cents < 10 ) { printf("0%d\n", cents); } /* end if */ else { printf("%d\n", cents); } /* end else */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Year 1 2 3 4 5 6 7 8 9 10  4.24  Chapter 4  Amount on deposit 1050.00 1102.50 1157.62 1215.50 1276.28 1340.09 1407.10 1477.45 1551.32 1628.89  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( "%d", i >= 1 && j < 4 ); ANS: 1 d) printf( "%d", m < = 99 && k < m ); ANS: 0 e) printf( "%d", j >= i || k == m ); ANS: 1 f) printf( "%d", k + m < j || 3 - j >= k ); ANS: 0 g) printf( "%d", !m ); ANS: 0 h) printf( "%d", !( j - m ) ); ANS: 1 i) printf( "%d", !( k > m ) ); ANS: 0 j) printf( "%d", !( j > k ) ); ANS: 1  4.25 Print a table of decimal, binary, octal, and hexadecimal equivalents. If you are not familiar with these number systems, read Appendix E first if you would like to attempt this exercise. ANS: see Exercise 4.34 Solution 4.26  Calculate the value of Ï€ from the infinite series 4- + … Ï€ = 4 – 4--- + 4--- – 4--- + 4--- – ----3 5 7 9 11  Print a table that shows the value of Ï€ approximated by one term of this series, by two terms, by three terms, etc. How many terms of this series do you have to use before you first get 3.14? 3.141? 3.1415? 3.14159?  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 73  Chapter 4  ANS: 3.14 occurs at an accuracy of 627, 3.141 occurs at an accuracy of 2458, 3.1415 occurs at an accuracy around 147,000, and 3.14159 occurs at an accuracy around 319,000. 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  /* Exercise 4.26 Solution */ #include                                                                                                                                          int main( void ) { long double pi = 0.0; long double num = 4.0; long double denom = 1.0; long int loop; long int accuracy;  /* /* /* /* /*  approximated value for pi */ numerator */ denominator of current term */ loop counter */ number of terms */  accuracy = 400000; /* set decimal accuracy */ /* display table headers */ printf( "Accuracy set at: %ld\n", accuracy ); printf( "term\t\t pi\n" ); /* loop through each term */ for ( loop = 1; loop <= accuracy; loop++ ) { /* if odd-numbered term, add current term */ if ( loop % 2 != 0 ) { pi += num / denom; } /* end if */ else { /* if even-numbered term, subtract current term */ pi -= num / denom; } /* end else */ /* display number of terms and approximated value for pi with 8 digits of precision */ printf( "%ld\t\t%Lf\n", loop, pi ); denom += 2.0; /* update denominator */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  74 C Program Control: Solutions  Chapter 4  Accuracy set at: 400000 term pi 1 4.000000 2 2.666667 3 3.466667 4 2.895238 5 3.339683 6 2.976046 ... 995 996 997 998 999  3.142598 3.140589 3.142596 3.140591 3.142594  ... 399998 399999 400000  3.141590 3.141595 3.141590  4.27 (Pythagorean Triples) A right triangle can have sides that are all integers. The set of three integer values for the sides of a right triangle is called a Pythagorean triple. These three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Find all Pythagorean triples for side1, side2, and the hypotenuse all no larger than 500. Use a triple-nested for loop that simply tries all possibilities. This is an example of "brute force" computing. It is not aesthetically pleasing to many people. But there are many reasons why these techniques are important. First, with computing power increasing at such a phenomenal pace, solutions that would have taken years or even centuries of computer time to produce with the technology of just a few years ago can now be produced in hours, minutes or even seconds. Recent microprocessor chips can process a billion instructions per second! Second, as you will learn in more advanced computer science courses, there are large numbers of interesting problems for which there is no known algorithmic approach other than sheer brute force. We investigate many kinds of problem-solving methodologies in this book. We will consider many brute force approaches to various interesting problems. 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.27 Solution */ #include                                                                                                                                            int main( void ) { int count = 0; long int side1; long int side2; long int hypotenuse; long int hyptSquared; long int sidesSquared;  /* /* /* /* /* /*  number of triples found */ side1 value counter */ side2 value counter */ hypotenuse value counter */ hypotenuse squared */ sum of squares of sides */  /* side1 values range from 1 to 500 */ for ( side1 = 1; side1 <= 500; side1++ ) { /* side2 values range from current side1 to 500 */ for ( side2 = 1; side2 <= 500; side2++ ) { /* hypotenuse values range from current side2 to 500 */ for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) { /* calculate square of hypotenuse value */ hyptSquared = hypotenuse * hypotenuse;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 75  Chapter 4  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 3 4 5 6 7 8  /* calculate sum of squares of sides */ sidesSquared = side1 * side1 + side2 * side2; /* if hypotenuse squared = side1 squared + side2 squared, Pythagorean triple */ if ( hyptSquared == sidesSquared ) { /* display triple */ printf( "%ld %ld %ld\n", side1, side2, hypotenuse ); ++count; /* update count */ } /* end if */ } /* end for */ } /* end for */ } /* end for */ /* display total number of triples found */ printf( "A total of %d triples were found.\n", count ); return 0; /* indicate successful termination */ } /* end main */ 4 5 3 5 12 13 8 10 24 25 6 10  ... 476 93 485 480 31 481 480 88 488 480 108 492 480 140 500 483 44 485 A total of 772 triples were found.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  76 C Program Control: Solutions  Chapter 4  4.28 A company pays its employees as managers (who receive a fixed weekly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they work and "time-and-a-half"—i.e., 1.5 times their hourly wage—for overtime hours worked), commission workers (who receive a $250 plus 5.7% of their gross weekly sales), or pieceworkers (who receive a fixed amount of money per item for each of the items they produce—each pieceworker in this company works on only one type of item). Write a program to compute the weekly pay for each employee. You do not know the number of employees in advance. Each type of employee has its own pay code: Managers have paycode 1, hourly workers have code 2, commission workers have code 3 and pieceworkers have code 4. Use a switch to compute each employee's pay based on that employee's paycode. Within the switch, prompt the user (i.e., the payroll clerk) to enter the appropriate facts your program needs to calculate each employee's pay based on that employee's paycode. 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  /* Exercise 4.28 Solution */ #include                                                                                                                                              int main( void ) { int payCode; int managers = 0; int hWorkers = 0; int cWorkers = 0; int pWorkers = 0; int pieces; double mSalary; double hSalary; double cSalary; double pSalary; double hours; double otPay; double otHours; double pay;  /* /* /* /* /* /* /* /* /* /* /* /* /* /*  current employee's pay code */ total number of managers */ total number of hourly workers */ total number of commission workers */ total number of pieceworkers */ current pieceworker's number of pieces */ manager's salary */ hourly worker's salary */ commission worker's salary */ pieceworker's salary */ total hours worked */ overtime pay */ overtime hours */ current employee's weekly pay */  /* prompt for first employee input */ printf( "Enter paycode ( -1 to end): " ); scanf( "%d", &payCode ); /* loop while sentinel value not read from user */ while ( payCode != -1 ) { /* switch to appropriate computation according to pay code */ switch ( payCode ) { /* pay code 1 corresponds to manager */ case 1: /*prompt for weekly salary */ printf( "Manager selected.\n" ); printf( "Enter weekly salary: " ); scanf( "%lf", &mSalary ); /* manager's pay is weekly salary */ printf( "The manager's pay is $%.2f\n", mSalary ); ++managers; /* update total number of managers */ break; /* exit switch */ /* pay code 2 corresponds to hourly worker */ case 2: /* prompt for hourly salary */ printf( "Hourly worker selected.\n" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 77  Chapter 4  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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111  printf( "Enter the hourly salary: " ); scanf( "%lf", &hSalary ); /* prompt for number of hours worked */ printf( "Enter the total hours worked: " ); scanf( "%lf", &hours ); /* pay fixed for up to 40 hours, 1.5 for hours over 40 */ if ( hours > 40.0 ) { /* calculate OT hours and total pay */ otHours = hours - 40.0; otPay = hSalary * 1.5 * otHours + hSalary * 40.0; printf( "Worker has worked %.1f overtime hours.\n", otHours ); printf( "Workers pay is $%.2f\n", otPay ); } /* end if */ else { /* no overtime */ pay = hSalary * hours; printf( "Worker's pay is $%.2f\n", pay ); } /* end else */ ++hWorkers; /* update total number of hourly workers */ break; /* exit switch */ /* pay code 3 corresponds to commission worker */ case 3: /* prompt for gross weekly sales */ printf( "Commission worker selected.\n" ); printf( "Enter gross weekly sales: " ); scanf( "%lf", &cSalary ); /* pay $250 plus 5.7% of gross weekly sales */ pay = 250.0 + 0.057 * cSalary; printf( "Commission Worker's pay is $%.2f\n", pay ); ++cWorkers; /* update total number of commission workers */ break; /* exit switch */ /* pay code 4 corresponds to pieceworker */ case 4: /* prompt for number of pieces */ printf( "Piece worker selected.\nEnter number of pieces: " ); scanf( "%d", &pieces ); /* prompt for wage per piece */ printf( "Enter wage per piece: " ); scanf( "%lf", &pSalary ); pay = pieces * pSalary; /* compute pay */ printf( "Piece Worker's pay is $%.2f\n", pay ); ++pWorkers; /* update total number of pieceworkers */ break; /* exit switch */ /* default case */ default : printf( "Invalid pay code.\n" ); break; } /* end switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  78 C Program Control: Solutions  Chapter 4  112 113 /* prompt for next employee input */ 114 printf( "\nEnter paycode ( -1 to end ): " ); 115 scanf( "%d", &payCode ); 116 } /* end while */ 117 118 /* display total counts for each type of employee 119 printf( "\n" ); 120 printf( "Total number of managers paid : 121 printf( "Total number of hourly workers paid : 122 printf( "Total number of commission workers paid: 123 printf( "Total number of piece workers paid : 124 125 return 0; /* indicate successful termination */ 126 127 } /* end main */ Enter Piece Enter Enter Piece  */ %d\n", %d\n", %d\n", %d\n",  managers hWorkers cWorkers pWorkers  ); ); ); );  paycode ( -1 to end): 4 worker selected. number of pieces: 200 wage per piece: 20 Worker's pay is $4000.00  Enter paycode ( -1 to end ): -1 Total Total Total Total  number number number number  of of of of  managers paid : hourly workers paid : commission workers paid: piece workers paid :  0 0 0 1  Enter paycode ( -1 to end): 1 Manager selected. Enter weekly salary: 2500 The manager's pay is $2500.00 Enter paycode ( -1 to end ): 2 Hourly worker selected. Enter the hourly salary: 10.50 Enter the total hours worked: 75 Worker has worked 35.0 overtime hours. Workers pay is $971.25 Enter paycode ( -1 to end ): 3 Commission worker selected. Enter gross weekly sales: 9000 Commission Worker's pay is $763.00 Enter Piece Enter Enter Piece  paycode ( -1 to end ): 4 worker selected. number of pieces: 200 wage per piece: 20 Worker's pay is $4000.00  Enter paycode ( -1 to end ): -1 Total Total Total Total  number number number number  of of of of  managers paid : hourly workers paid : commission workers paid: piece workers paid :  1 1 1 1  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 79  Chapter 4  4.29 (De Morgan's Laws) In this chapter, we discussed the logical operators &&, ||, and !. De Morgan's Laws can sometimes make it more convenient for us to express a logical expression. These laws state that the expression !(condition1 && condition2) is logically equivalent to the expression (!condition1 || !condition2). Also, the expression !(condition1 || condition2) is logically equivalent to the expression (!condition1 && !condition2). Use De Morgan's Laws to write equivalent expressions for each of the following, and then write a program to show that both the original expression and the new expression in each case are equivalent. a) !( x < 5 ) && !( y >= 7 ) b) !( a == b ) || !( g != 5 ) c) !( ( x <= 8 ) && ( y > 4 ) ) d) !( ( i > 4 ) || ( j <= 6 ) ) 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  /* Exercise 4.29 Solution */ #include                                                                                                                                                int main( void { int x = 10; int y = 1; int a = 3; int b = 3; int g = 5; int Y = 1; int i = 2; int j = 9;  ) /* /* /* /* /* /* /* /*  define define define define define define define define  current current current current current current current current  variable variable variable variable variable variable variable variable  value value value value value value value value  */ */ */ */ */ */ */ */  /* display variable values */ printf( "current variable values are: \n" ); printf( "x = %d, y = %d, a = %d,", x, y, a ); printf( " b = %d\n", b ); printf( "g = %d, Y = %d, i = %d,", g, Y, i ); printf( " j = %d\n\n", j ); /* part a */ if ( ( !( x < 5 ) ) ) ) { printf( "!( x " !( ( } /* end if */ else { printf( "!( x " !( ( } /* end else */  && !( y >= 7 ) ) == ( !( ( x < 5 ) || ( y >= 7 ) < 5 ) && !( y >= 7 ) is equivalent to" x < 5 ) || ( y >= 7 ) )\n" );  < 5 ) && !( y >= 7 ) is not equivalent to" x < 5 ) || ( y >= 7 ) )\n" );  /* part b */ if ( ( !( a == b ) || !( ) ) ) { printf( "!( a == b ) " !( ( a == b } /* end if */ else { printf( "!( a == b ) " !( ( a == b } /* end else */  g != 5 ) ) == ( !( ( a == b ) && ( g != 5 ) || !( g != 5 ) is equivalent to" ) && ( g != 5 ) )\n" );  || !( g != 5 ) is not equivalent to" ) && ( g != 5 ) )\n" );  /* part c */ if ( !( ( x <= 8 ) && ( Y > 4 ) ) == ( !( x <= 8 ) || !( Y > 4 ) ) ) { printf( "!( ( x <= 8 ) && ( Y > 4 ) ) is equivalent to" " ( !( x <= 8 ) || !( Y > 4 ) )\n" ); } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  80 C Program Control: Solutions  50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68  Chapter 4  else { printf( "!( ( x <= 8 ) && ( Y > 4 ) ) is not equivalent to" " ( !( x <= 8 ) || !( Y > 4 ) )\n" ); } /* end else */ /* part d */ if ( !( ( i > 4 ) ) ) { printf( "!( ( " ( !( } /* end if */ else { printf( "!( ( " ( !( } /* end else */  || ( j <= 6 ) ) == ( !( i > 4 ) && !( j <= 6 ) i > 4 ) || ( j <= 6 ) ) is equivalent to" i > 4 ) && !( j <= 6 ) )\n" );  i > 4 ) || ( j <= 6 ) ) is not equivalent to" i > 4 ) && !( j <= 6 ) )\n" );  return 0; /* indicate successful termination */ } /* end main */  current variable values are: x = 10, y = 1, a = 3, b = 3 g = 5, Y = 1, i = 2, j = 9 !( !( !( !(  x a ( (  < 5 ) && !( y >= 7 ) is equivalent to !( ( x < 5 ) || ( y >= 7 ) == b ) || !( g != 5 ) is equivalent to !( ( a == b ) && ( g != 5 x <= 8 ) && ( Y > 4 ) ) is equivalent to ( !( x <= 8 ) || !( Y > i > 4 ) || ( j <= 6 ) ) is equivalent to ( !( i > 4 ) && !( j <=  ) ) ) 4 ) ) 6 ) )  4.30 Rewrite the program of Fig. 4.7 by replacing the switch statement with a nested if…else statement; be careful to deal with the default case properly. Then rewrite this new version by replacing the nested if…else statement with a series of if statements; here, too, be careful to deal with the default case properly (this is more difficult than in the nested if…else version). This exercise demonstrates that switch is a convenience and that any switch statement can be written with only single-selection statements. 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.30 Part A Solution */ #include                                                                                                                                                                                                                                                                                                  int main( void ) { int grade; int aCount = 0; int bCount = 0; int cCount = 0; int dCount = 0; int fCount = 0;  /* /* /* /* /* /*  current total A total B total C total D total F  grade */ grades */ grades */ grades */ grades */ grades */  /* prompt user for grades */ printf( "Enter the letter grades." ); printf( " Enter the EOF character to end input:\n" ); /* while EOF not entered by user */ while ( ( grade = getchar() ) != EOF ) { /* Update count for appropriate grade */ if ( grade == 'A' || grade == 'a' ) { ++aCount; } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 81  Chapter 4  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 55 56  else if ( grade == 'B' || grade == 'b' ) { ++bCount; } /* end else if */ else if ( grade == 'C' || grade == 'c' ) { ++cCount; } /* end else if */ else if ( grade == 'D' || grade == 'd' ) { ++dCount; } /* end else if */ else if ( grade == 'F' || grade == 'f' ) { ++fCount; } /* end else if */ else if ( grade == '\n' || grade == ' ' ) { ; /* empty body */ } /* end else if */ else { printf( "Incorrect letter grade entered." ); printf( " Enter a new grade.\n" ); } /* end else */ } /* end while */ /* display totals for each grade */ printf( "\nTotals for each letter grade were:\n" ); 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 ); return 0; /* indicate successful termination */ } /* end main */  Enter the letter grades. Enter the EOF character to end input: A c b d e Incorrect letter grade entered. Enter a new grade. f ^Z Totals for each letter grade were: A: 1 B: 1 C: 1 D: 1 F: 1  1 2 3 4 5 6 7 8 9 10 11  /* Exercise 4.30 Part B Solution */ #include                                                                                                                                                                                                                                                                                                      int main( void ) { int grade; /* current int aCount = 0; /* total A int bCount = 0; /* total B int cCount = 0; /* total C int dCount = 0; /* total D int fCount = 0; /* total  grade */ grades */ grades */ grades */ grades */  F grades */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  82 C Program Control: Solutions  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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69  Chapter 4  /* prompt user for grades */ printf( "Enter the letter grades." ); printf( " Enter the EOF character to end input:\n" ); /* while EOF not entered by user */ while ( ( grade = getchar() ) != EOF ) { /* update count for appropriate grade */ if ( grade == 'A' || grade == 'a' ) { ++aCount; } /* end if */ if ( grade == 'B' || grade == 'b' ) { ++bCount; } /* end if */ if ( grade == 'C' || grade == 'c' ) { ++cCount; } /* end if */ if ( grade == 'D' || grade == 'd' ) { ++dCount; } /* end if */ if ( grade == 'F' || grade == 'f' ) { ++fCount; } /* end if */ if ( grade == '\n' || grade == ' ' ) { ; /* empty body */ } /* end if */ /* default */ if ( grade != grade != grade != grade != grade != grade !=  'a' && 'B' && 'c' && 'd' && 'f' && '\n'&&  grade grade grade grade grade grade  != != != != != !=  'A' 'b' 'C' 'd' 'F' ' '  && && && && && ) {  printf( "Incorrect letter grade entered." ); printf( " Enter a new grade.\n" ); } /* end if */ } /* end while */ /* display totals for each grade */ printf( "\nTotals for each letter grade were:\n" ); 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 ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 83  Chapter 4  Enter the letter grades. Enter the EOF character to end input: A b c s Incorrect letter grade entered. Enter a new grade. d f ^Z Totals for each letter grade were: A: 1 B: 1 C: 1 D: 1 F: 1  4.31 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. * *** ***** ******* ********* ******* ***** *** *  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  /* Exercise 4.31 Solution */ #include                                                                                                                                                                                                                                                                                                          int main( void ) { int line; /* line counter */ int space; /* space counter */ int asterisk; /* asterisk counter */ /* 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 ) { /* print preceding spaces */ for ( space = ( 9 - line ) / 2; space > 0; space-- ) { printf( " " ); } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  84 C Program Control: Solutions  33 34 35 36 37 38 39 40 41 42 43 44  Chapter 4  /* print asterisks */ for ( asterisk = 1; asterisk <= line; asterisk++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  4.32 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 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  /* Exercise 4.32 Solution */ #include                                                                                                                                                        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 ); /* top half */ for ( line = 1; line <= size -  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 ) { /* 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 */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 85  Chapter 4  43 44 45 46 47 48 49  printf( "\n" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter an odd number for the diamond size ( 1-19 ): 13 * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** *  4.33  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  Write a program that prints a table of all the Roman numeral equivalents of the decimal numbers in the range 1 to 100. ANS: /* Exercise 4.33 Solution */ #include                                                                                                                                                          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 ) { /* print appropriate Roman numeral for tens digit */ case 0: break; case 1: printf( "X" ); break; /* exit switch */ case 2: printf( "XX" ); break; /* exit switch */ case 3: printf( "XXX" ); break; /* exit switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  86 C Program Control: Solutions  36 37 38 39 40 41 42 43 44 45 46 47 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 92 93 94 95 96  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 */ 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 ) { /* print appropriate Roman numeral for ones digit */ case 0: printf( "\t\t%4d\n", div * 10 ); break; /* exit switch */ case 1: printf( "I\t\t%4d\n", div * 10 + mod ); break; /* exit switch */ case 2: printf( "II\t\t%4d\n", div * 10 + mod ); break; /* exit switch */ case 3: printf( "III\t\t%4d\n", div * 10 + mod ); break; /* exit switch */ case 4: printf( "IV\t\t%4d\n", div * 10 + mod ); break; /* exit switch */ case 5: printf( "V\t\t%4d\n", div * 10 + mod ); break; /* exit switch */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 4  C Program Control: Solutions 87  Chapter 4  97 case 6: 98 printf( "VI\t\t%4d\n", div * 10 + mod ); 99 break; /* exit switch */ 100 101 case 7: 102 printf( "VII\t\t%4d\n", div * 10 + mod ); 103 break; /* exit switch */ 104 105 case 8: 106 printf( "VIII\t\t%4d\n", div * 10 + mod ); 107 break; /* exit switch */ 108 109 case 9: 110 printf( "IX\t\t%4d\n", div * 10 + mod ); 111 break; /* exit switch */ 112 113 case 10: 114 printf( "X\t\t%4d\n", div * 10 + mod ); 115 break; /* exit switch */ 116 117 default: 118 break; /* exit switch */ 119 } /* end switch */ 120 121 } /* end for */ 122 123 return 0; /* indicate successful termination */ 124 125 } /* end main */ Roman Numeral I II III IV V VI VII VIII IX X  Decimal 1 2 3 4 5 6 7 8 9 10  ... LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C  89 90 91 92 93 94 95 96 97 98 99 100  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  88 C Program Control: Solutions  Chapter 4  4.34 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 E before you attempt this exercise. 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 53 54 55 56 57 58  /* Exercise 4.34 Solution */ #include                                                                                                                                                                                                                                                                                                                      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; /* binary numbers */ printf( "%c", number == 256 ? '1' : '0' ); 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; 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; printf( "%d\t\t", number == 0 ? 0 : number ); /* hexadecimal numbers */ number = loop; temp1 = 16;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 89  Chapter 4  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  if ( number < 4096 && number >= 256 ) { printf( "%d", number / 256 ); } /* end if */ if ( number < 256 && number >= 16 ) { temp1 = number / 16; number %= 16; } /* end if */ else { printf( "0" ); } /* end else */ /* 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 */ /* 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 */  Decimal 1 2 3 4 5 6 7 8 9 10  Binary 000000001 000000010 000000011 000000100 000000101 000000110 000000111 000001000 000001001 000001010  Octal 001 002 003 004 005 006 007 010 011 012  Hexadecimal 01 02 03 04 05 06 07 08 09 0A  011111010 011111011 011111100 011111101 011111110 011111111 100000000  372 373 374 375 376 377 400  FA FB FC FD FE FF 10F  ... 250 251 252 253 254 255 256  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  90 C Program Control: Solutions  Chapter 4  4.35 Describe the process you would use to replace a do…while loop with an equivalent while loop. What problem occurs when you try to replace a while loop with an equivalent do…while loop? Suppose you have been told that you must remove a while loop and replace it with a do…while. What additional control statement would you need to use and how would you use it to ensure that the resulting program behaves exactly as the original? ANS: The body of a do…while loop becomes the body of a while loop, and the contents of the body are repeated before the while loop. In a do…while loop, the body is executed at least once, whereas execution of the body in a while loop depends on the continuation condition. Replacing a while loop with a do…while loop requires an if selection statement. The do…while loop would be the body of the if statement and the condition would be the same as the loop continuation condition in the do…while. 4.36 Write a program that inputs the year in the range 1994 through 1999 and uses for-loop repetition to produce a condensed, neatly printed calendar. Watch out for leap years. 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  /* /* /* /*  Exercise 4.36 Solution */ This is a simple calender solution, that does */ not account for the shifting of dates from */ year to year. */  #include                                                                                                                                                              int main( void ) { int year; int leapYear; int days; int month; int space; int dayPosition; int dayNum;  /* /* /* /* /* /* /*  current year */ leap year, 1 = yes, 0 = no */ total days in current month */ current month */ space counter */ starting day position of year */ counter for days of the month */  /* loop until input is valid */ do { printf( "Enter a calendar year between 1994 and 1999: " ); scanf( "%d", &year ); } while ( year < 1994 || year > 1999 ); /* end do...while */ /* determine starting day position */ switch ( year ) { case 1994: dayPosition = 7; break; /* exit switch */ case 1995: dayPosition = 1; break; /* exit switch */ case 1996: dayPosition = 2; break; /* exit switch */ case 1997: dayPosition = 4; break; /* exit switch */ case 1998: dayPosition = 5; break; /* exit switch */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 91  Chapter 4  47 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107  case 1999: dayPosition = 6; break; /* exit switch */ } /* end switch */ /* check for leap years */ if ( year % 400 == 0 ) { leapYear = 1; } /* end if */ else if ( year % 4 == 0 && year % 100 != 0 ) { leapYear = 1; } /* end else if */ else { leapYear = 0; } /* end else */ /* loop through months and print calendar */ for ( month = 1; month <= 12; month++ ) { /* begin with the month */ switch ( month ) { case 1: printf( "\n\nJanuary %d\n", year ); days = 31; break; /* exit switch */ case 2: printf( "\n\nFebruary %d\n", year ); days = leapYear == 1 ? 29 : 28; break; /* exit switch */ case 3: printf( "\n\nMarch %d\n", year ); days = 31; break; /* exit switch */ case 4: printf( "\n\nApril %d\n", year ); days = 30; break; /* exit switch */ case 5: printf( "\n\nMay %d\n", year ); days = 31; break; /* exit switch */ case 6: printf( "\n\nJune %d\n", year ); days = 30; break; /* exit switch */ case 7: printf( "\n\nJuly %d\n", year ); days = 31; break; /* exit switch */ case 8: printf( "\n\nAugust %d\n", year ); days = 31; break; /* exit switch */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  92 C Program Control: Solutions  108 109 case 9: 110 printf( "\n\nSeptember %d\n", year ); 111 days = 30; 112 break; /* exit switch */ 113 114 case 10: 115 printf( "\n\nOctober %d\n", year ); 116 days = 31; 117 break; /* exit switch */ 118 119 case 11: 120 printf( "\n\nNovember %d\n", year ); 121 days = 30; 122 break; /* exit switch */ 123 124 case 12: 125 printf( "\n\nDecember %d\n", year ); 126 days = 31; 127 break; /* exit switch */ 128 } /* end switch */ 129 130 printf( " S M T W R F S\n" ); /* print heads */ 131 132 /* move to proper space to begin printing month */ 133 for ( space = 1; space < dayPosition; space++ ) { 134 printf( " " ); 135 } /* end for */ 136 137 /* print days of the month */ 138 for ( dayNum = 1; dayNum <= days; dayNum++ ) { 139 printf( "%2d ", dayNum ); 140 141 /* if end of the week, start a new line */ 142 if ( dayPosition % 7 == 0 ) { 143 printf( "\n" ); 144 dayPosition = 1; /* reset dayPosition */ 145 } /* end if */ 146 else { 147 ++dayPosition; 148 } /* end else */ 149 150 } /* end for */ 151 152 } /* end for */ 153 154 return 0; /* indicate successful termination */ 155 156 } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 4  C Program Control: Solutions 93  Chapter 4  Enter a calendar year between 1994 and 1999: 1999 January 1999 S M T W R 3 4 5 6 7 10 11 12 13 14 17 18 19 20 21 24 25 26 27 28 31 February S M T 1 2 7 8 9 14 15 16 21 22 23 28 March S M 1 7 8 14 15 21 22 28 29 . . .  F S 1 2 8 9 15 16 22 23 29 30  1999 W R F S 3 4 5 6 10 11 12 13 17 18 19 20 24 25 26 27  1999 T W R F S 2 3 4 5 6 9 10 11 12 13 16 17 18 19 20 23 24 25 26 27 30 31  4.37 A criticism of the break statement and the continue statement is that each is unstructured. Actually, break statements and continue statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you would remove any break statement from a loop in a program and replace that statement with some structured equivalent. [Hint: The break statement leaves a loop from within the body of the loop. The other way to leave is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates "early exit because of a 'break' condition."] Use the technique you developed here to remove the break statement from the program of Fig. 4.11. 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  /* Exercise 4.37 Solution */ #include                                                                                                                                                                                                                                                                                                                              int main( void ) { int x; /* loop counter */ int breakOut = 1; /* breakout condition */ /* test for breakout condition */ for ( x = 1; x <= 10 && breakOut == 1; x++ ) { /* break out of loop after x = 4 */ if ( x == 4 ) { breakOut = -1; } /* end if */ printf( "%d ", x ); } /* end for */ printf( "\nBroke out of loop at x = %d\n", x ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  94 C Program Control: Solutions  Chapter 4  1 2 3 4 Broke out of loop at x = 5  4.38  What does the following program segment do?  1 2 3 4 5 6 7 8  for ( i = 1; i <= 5; i++ ) { for ( j = 1; j <= 3; j++ ) { for ( k = 1; k <= 4; k++ ) printf( "*" ); printf( "\n" ); } printf( "\n" ); }  ANS:  **** **** **** **** **** **** **** **** **** **** **** **** **** **** ****  4.39 Describe in general how you would remove any continue statement from a loop in a program and replace that statement with some structured equivalent. Use the technique you developed here to remove the continue statement from the program of Fig. 4.12. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  /* Exercise 4.39 Solution */ #include                                                                                                                                                                                                                                                                                                                                  int main( void ) { int x; /* loop counter */ /* loop 10 times */ for ( x = 1; x <= 10; x++ ) { /* if x == 5, skip to next interation */ if ( x == 5 ) { ++x; } /* end if */ printf( "%d ", x ); } /* end for */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Program Control: Solutions 95  Chapter 4  18 19 20 21 22 23  printf( "\nUsed ++x to skip printing the value 5\n" ); return 0; /* indicate successful termination */ } /* end main */  1 2 3 4 6 7 8 9 10 Used ++x to skip printing the value 5  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  96 C Program Control: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 4  5 C Functions: Solutions  SOLUTIONS 5.8  Show the value of x after each of the following statements is performed: a) x = fabs( 7.5 ); ANS: 7.5 b) x = floor( 7.5 ); ANS: 7.0 c) x = fabs( 0.0 ); ANS: 0.0 d) x = ceil( 0.0 ); ANS: 0.0 e) x = fabs( -6.4 ); ANS: 6.4 f) x = ceil( -6.4 ); ANS: -6.0 g) x = ceil( -fabs( -8 + floor( -5.5 ) ) ); ANS: -14.0  5.9 A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of 3 customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format, and should calculate and print the total of yesterday's receipts. The program should use the function calculateCharges to determine the charge for each customer. Your outputs should appear in the following format:  Enter the hours parked for 3 cars: 1.5 4.0 24.0 Car Hours Charge 1 1.5 2.00 2 4.0 2.50 3 24.0 10.00 TOTAL 29.5 14.50  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  98 C Functions: Solutions  Chapter 5  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 53 54 55 56 57 58 59  /* Exercise 5.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                          double calculateCharges( double hours ); /* function prototype */ int main() { double h; double currentCharge; double totalCharges = 0.0; double totalHours = 0.0; int i; int first = 1;  /* /* /* /* /* /*  number of hours for current car */ parking charge for current car */ total charges */ total number of hours */ loop counter */ flag for printing table headers */  printf( "Enter the hours parked for 3 cars: " ); /* loop 3 times for 3 cars */ for ( i = 1; i <= 3; i++ ) { scanf( "%lf", &h ); totalHours += h; /* add current hours to total hours */ /* if first time through loop, display headers */ if ( first ) { printf( "%5s%15s%15s\n", "Car", "Hours", "Charge" ); /* set flag to false to prevent from printing again */ first = 0; } /* end if */ /* calculate current car's charge and update total */ totalCharges += ( currentCharge = calculateCharges( h ) ); /* display row data for current car */ printf( "%5d%15.1f%15.2f\n", i, h, currentCharge ); } /* end for */ /* display row data for totals */ printf( "%5s%15.1f%15.2f\n", "TOTAL", totalHours, totalCharges ); return 0; /* indicate successful termination */ } /* end main */ /* calculateCharges returns charge according to number of hours */ double calculateCharges( double hours ) { double charge; /* calculated charge */ /* $2 for up to 3 hours */ if ( hours < 3.0 ) { charge = 2.0; } /* end if */ /* $.50 for each hour or part thereof in excess of 3 hours */ else if ( hours < 19.0 ) { charge = 2.0 + .5 * ceil( hours - 3.0 ); } /* end else if */ else { /* maximum charge $10 */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 99  Chapter 5  60 61 62 63 64 65 5.10  charge = 10.0; } /* end else */ return charge; /* return calculated charge */ } /* end function calculateCharges */  An application of function floor is rounding a value to the nearest integer. The statement y = floor( x + .5 );  will round the number x to the nearest integer, and assign the result to y. Write a program that reads several numbers and uses the preceding statement to round each of these numbers to the nearest integer. For each number processed, print both the original number and the rounded number. 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  /* Exercise 5.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                  void calculateFloor( void ); /* function prototype */ int main() { calculateFloor(); /* call function calculateFloor */ return 0; /* indicate successful termination */ } /* end main */ /* calculateFloor rounds 5 inputs */ void calculateFloor( void ) { double x; /* current input */ double y; /* current input rounded */ int loop; /* loop counter */ /* loop for 5 inputs */ for ( loop = 1; loop <= 5; loop++ ) { printf( "Enter a floating point value: " ); scanf( "%lf", &x ); /* y holds rounded input */ y = floor( x + .5 ); printf( "%f rounded is %.1f\n\n", x, y ); } /* end for */ } /* end function calculateFloor */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  100 C Functions: Solutions  Chapter 5  Enter a floating point value: 1.5 1.500000 rounded is 2.0 Enter a floating point value: 5.55 5.550000 rounded is 6.0 Enter a floating point value: 73.2341231432 73.234123 rounded is 73.0 Enter a floating point value: 9.0 9.000000 rounded is 9.0 Enter a floating point value: 4 4.000000 rounded is 4.0  5.11  Function floor may be used to round a number to a specific decimal place. The statement y = floor( x * 10 + .5 ) / 10;  rounds x to the tenths position (the first position to the right of the decimal point). The statement y = floor( x * 100 + .5 ) / 100;  rounds x to the hundredths position (i.e., the second position to the right of the decimal point). Write a program that defines four functions to round a number x in various ways a) roundToInteger( number ) b) roundToTenths( number ) c) roundToHundreths( number ) d) roundToThousandths( number ) For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth, and the number rounded to the nearest thousandth. 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  /* Exercise 5.11 Solution */ #include                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                          double double double double  roundToInteger( double n ); roundToTenths( double n ); roundToHundredths( double n ); roundToThousandths( double n );  /* /* /* /*  function function function function  prototype prototype prototype prototype  */ */ */ */  int main() { int i; /* loop counter */ int count; /* number of values to process */ double number; /* current input */ printf( "How many numbers do you want to process? " ); scanf( "%d", &count ); /* loop for inputs */ for ( i = 0; i < count; i++ ) { printf( "Enter number: " ); scanf( "%lf", &number ); /* display number rounded to nearest integer */ printf( "%f rounded to an integer is %f\n", number, roundToInteger( number ) ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 101  Chapter 5  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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71  /* display number rounded to nearest tenth */ printf( "%f rounded to the nearest tenth is %f\n", number, roundToTenths( number ) ); /* display number rounded to nearest hundredth */ printf( "%f rounded to the nearest hundredth is %f\n", number, roundToHundredths( number ) ); /* display number rounded to nearest thousandth */ printf( "%f rounded to the nearest thousandth is %f\n\n", number, roundToThousandths( number ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* roundToInteger rounds n to nearest integer */ double roundToInteger( double n ) { return floor( n + .5 ); } /* end function roundToInteger */ /* roundToTenths rounds n to nearest tenth */ double roundToTenths( double n ) { return floor( n * 10 + .5 ) / 10; } /* end function roundToTenths */ /* roundToHundredths rounds n to nearest hundredth */ double roundToHundredths( double n ) { return floor( n * 100 + .5 ) / 100; } /* end function roundToHundredths */ /* roundToThousandths rounds n to nearest thousandth */ double roundToThousandths( double n ) { return floor( n * 1000 + .5 ) / 1000; } /* end function roundToThousandths */  How many numbers do you want to process? 1 Enter number: 8.54739 8.547390 rounded to an integer is 9.000000 8.547390 rounded to the nearest tenth is 8.500000 8.547390 rounded to the nearest hundredth is 8.550000 8.547390 rounded to the nearest thousandth is 8.547000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  102 C Functions: Solutions  Chapter 5  5.12  Answer each of the following questions. a) What does it mean to choose numbers "at random?" ANS: Every number has an equal chance of being chosen at any time. b) Why is the rand function useful for simulating games of chance? ANS: Because it produces a sequence of pseudo random numbers that when scaled appear to be random. c) Why would you randomize a program by using srand? Under what circumstances is it desirable not to randomize? ANS: Using srand enables the sequence of pseudo random numbers produced by rand to change each time the program is executed. The program should not be randomized while in the debugging stages because repetition is helpful in debugging. d) Why is it often necessary to scale and/or shift the values produced by rand? ANS: To produce random values in a specific range. e) Why is computerized simulation of real-world situations a useful technique? ANS: It enables more accurate predictions of random events such as cars arriving at toll booths and people arriving in lines at a supermarket. The results of a simulation can help determine how many toll booths to have open or how many cashiers to have open at specific times.  5.13  Write statements that assign random integers to the variable n in the following ranges: a) 1 ≤ n ≤ 2 ANS: n = 1 + rand() % 2; b) 1 ≤ n ≤ 100 ANS: n = 1 + rand() % 100; c) 0 ≤ n ≤ 9 ANS: n = rand() % 10; d) 1000 ≤ n ≤ 1112 ANS: n = 1000 + rand() % 113; e) –1 ≤ n ≤ 1 ANS: n = -1 + rand() % 3; f) –3 ≤ n ≤ 11 ANS: n = -3 + rand() % 15;  5.14  For each of the following sets of integers, write a single statement that will print a number at random from the set. a) 2, 4, 6, 8, 10. ANS: printf( "%d\n", 2 * ( 1 + rand() % 5 ) ); b) 3, 5, 7, 9, 11. ANS: printf( "%d\n", 1 + 2 * ( 1 + rand() % 5 ) ); c) 6, 10, 14, 18, 22. ANS: pritnf( "%d\n", 6 + 4 * ( rand() % 5 ) );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 103  Chapter 5  5.15 Define a function called hypotenuse that calculates the length of the hypotenuse of a right triangle when the other two sides are given. Use this function in a program to determine the length of the hypotenuse for each of the following triangles. The function should take two arguments of type double and return the hypotenuse as a double. Test your program with the side values specified in Fig. 5.18.  Triangle  Side 1  Side 2  1  3.0  4.0  2  5.0  12.0  3  8.0  15.0  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  /* Exercise 5.15 Solution */ #include                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                  double hypotenuse( double s1, double s2 ); /* function prototype */ int main() { int i; /* loop counter */ double side1; /* value for first side */ double side2; /* value for second side */ /* loop 3 times */ for ( i = 1; i <= 3; i++ ) { printf( "Enter the sides of the triangle: " ); scanf( "%lf%lf", &side1, &side2 ); /* calculate and display hypotenuse value */ printf( "Hypotenuse: %.1f\n\n", hypotenuse( side1, side2 ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* hypotenuse calculates value of hypotenuse of a right triangle given two side values */ double hypotenuse( double s1, double s2 ) { return sqrt( pow( s1, 2 ) + pow( s2, 2 ) ); } /* end function hypotenuse */  Enter the sides of the triangle: 3.0 4.0 Hypotenuse: 5.0 Enter the sides of the triangle: 5.0 12.0 Hypotenuse: 13.0 Enter the sides of the triangle: 8.0 15.0 Hypotenuse: 17.0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  104 C Functions: Solutions  5.16  Chapter 5  Write a function integerPower( base, exponent ) that returns the value of baseexponent  For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer, and base is an integer. Function integerPower should use for to control the calculation. Do not use any math library functions. 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  /* Exercise 5.16 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                      int integerPower( int b, int e ); int main() { int exp; /* integer exponent */ int base; /* integer base */ printf( "Enter integer base and exponent: " ); scanf( "%d%d", &base, &exp ); printf( "%d to the power %d is: %d\n", base, exp, integerPower( base, exp ) ); return 0; /* indicate successful termination */ } /* end main */ /* integerPower calculates and returns b raised to the e power */ int integerPower( int b, int e ) { int product = 1; /* resulting product */ int i; /* loop counter */ /* multiply product times b (e repetitions) */ for ( i = 1; i <= e; i++ ) { product *= b; } /* end for */ return product; /* return resulting product */ } /* end function integerPower */  Enter integer base and exponent: 5 3 5 to the power 3 is: 125  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 105  Chapter 5  5.17 Write a function multiple that determines for a pair of integers whether the second integer is a multiple of the first. The function should take two integer arguments and return 1 (true) if the second is a multiple of the first, and 0 (false) otherwise. Use this function in a program that inputs a series of pairs of integers. 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  /* Exercise 5.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                          int multiple( int a, int b ); /* function prototype */ int main() { int x; /* first integer */ int y; /* second integer */ int i; /* loop counter */ /* loop 3 times */ for ( i = 1; i <= 3; i++ ) { printf( "Enter two integers: " ); scanf( "%d%d", &x, &y ); /* determine if second is multiple of first */ if ( multiple( x, y ) ) { printf( "%d is a multiple of %d\n\n", y, x ); } /* end if */ else { printf( "%d is not a multiple of %d\n\n", y, x ); } /* end else */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* multiple determines if b is multiple of a */ int multiple( int a, int b ) { return !( b % a ); } /* end function multiple */  Enter two integers: 2 10 10 is a multiple of 2 Enter two integers: 5 17 17 is not a multiple of 5 Enter two integers: 3 696 696 is a multiple of 3  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  106 C Functions: Solutions  Chapter 5  5.18 Write a program that inputs a series of integers and passes them one at a time to function even which uses the remainder operator to determine if an integer is even. The function should take an integer argument and return 1 if the integer is even and 0 otherwise. 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  /* Exercise 5.18 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                              int even( int a ); /* function prototype */ int main() { int x; /* current input */ int i; /* loop counter */ /* loop for 3 inputs */ for ( i = 1; i <= 3; i++ ) { printf( "Enter an integer: " ); scanf( "%d", &x ); /* determine if input is even */ if ( even( x ) ) { printf( "%d is an even integer\n\n", x ); } /* end if */ else { printf( "%d is not an even integer\n\n", x ); } /* end else */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* even returns true if a is even */ int even( int a ) { return !( a % 2 ); } /* end function even */  Enter an integer: 7 7 is not an even integer Enter an integer: 6 6 is an even integer Enter an integer: 10000 10000 is an even integer  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 107  Chapter 5  5.19 Write a function that displays at the left margin of the screen a solid square of asterisks whose side is specified in integer parameter side. For example, if side is 4, the function displays:  Enter side: 4 **** **** **** ****  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  /* Exercise 5.19 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                  void square( int s ); /* function prototype */ int main() { int side; /* input side length */ printf( "Enter side: " ); scanf( "%d", &side ); square( side ); /* display solid square of asterisks */ return 0; /* indicate successful termination */ } /* end main */ /* square displays void square( int s { int i; /* outer int j; /* inner  solid square of asterisks with specified side */ ) loop counter */ loop counter */  /* loop side times for number of rows */ for ( i = 1; i <= s; i++ ) { /* loop side times for number of columns */ for ( j = 1; j <= s; j++ ) { printf( "*" ); } /* end for */ printf( "\n" ); } /* end for */ } /* end function square */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  108 C Functions: Solutions  Chapter 5  5.20 Modify the function created in Exercise 5.19 to form the square out of whatever character is contained in character parameter fillCharacter. Thus if side is 5 and fillCharacter is "#" then this function should print:  Enter a character and the side length: # 5 ##### ##### ##### ##### #####  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  /* Exercise 5.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                      void square( int side, char fillCharacter ); /* function prototype */ int main() { int s; /* side length */ char c; /* fill character */ printf( "Enter a character and the side length: " ); scanf( "%c%d", &c, &s ); square( s, c ); /* display solid square of input character */ return 0; /* indicate successful termination */ } /* end main */ /* square displays solid square of fillCharacter with specified side */ void square( int side, char fillCharacter ) { int loop; /* outer loop counter */ int loop2; /* inner loop counter */ /* loop side times for number of rows */ for ( loop = 1; loop <= side; loop++ ) { /* loop side times for number of columns */ for ( loop2 = 1; loop2 <= side; loop2++ ) { printf( "%c", fillCharacter ); } /* end for */ printf( "\n" ); } /* end for */ } /* end function square */  5.21 Use techniques similar to those developed in Exercises 5.19 and 5.20 to produce a program that graphs a wide range of shapes.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 109  Chapter 5  5.22  Write program segments that accomplish each of the following: a) Calculate the integer part of the quotient when integer a is divided by integer b. b) Calculate the integer remainder when integer a is divided by integer b. c) Use the program pieces developed in a) and b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should be printed as:  4  5  6  2  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  /* Exercise 5.22 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                          int quotient( int a, int b ); /* function prototype */ int remainder( int a, int b ); /* function prototype */ int main() { int number; /* input number */ int divisor = 10000; /* current divisor */ printf( "Enter an integer between 1 and 32767: " ); scanf( "%d", &number ); printf( "The digits in the number are:\n" ); /* determine and print each digit */ while ( number >= 10 ) { /* if number is >= current divisor, determine digit */ if ( number >= divisor ) { /* use quotient to determine current digit */ printf( "%d ", quotient( number, divisor ) ); /* update number to be remainder */ number = remainder( number, divisor ); /* update divisor for next digit */ divisor = quotient( divisor, 10 ); } /* end if */ else { /* if number < current divisor, no digit */ divisor = quotient( divisor, 10 ); } /* end else */ } /* end while */ printf( "%d\n", number ); return 0; /* indicate successful termination */ } /* end main */ /* Part A: determine quotient using integer division */ int quotient( int a, int b ) { return a / b; } /* end function quotient */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  110 C Functions: Solutions  50 51 52 53 54 55 56  /* Part B: determine remainder using the remainder operator */ int remainder( int a, int b ) { return a % b; } /* end function remainder */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 111  Chapter 5  5.23 Write a function that takes the time as three integer arguments (for hours, minutes, and seconds), and returns the number of seconds since the last time the clock "struck 12." Use this function to calculate the amount of time in seconds between two times, both of which are within one 12-hour cycle of the clock. 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  /* Exercise 5.23 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                  /* function prototype */ unsigned seconds( unsigned h, unsigned m, unsigned s ); int main() { int hours; int minutes; int secs; int first; int second; int difference;  /* /* /* /* /* /*  current time's hours */ current time's minutes */ current time's seconds */ first time, in seconds */ second time, in seconds */ difference between two times, in seconds */  printf( "Enter the first time as three integers: " ); scanf( "%d%d%d", &hours, &minutes, &secs ); /* calculate first time in seconds */ first = seconds( hours, minutes, secs ); printf( "Enter the second time as three integers: " ); scanf( "%d%d%d", &hours, &minutes, &secs ); /* calculate second time in seconds */ second = seconds( hours, minutes, secs ); /* calculate difference */ difference = fabs( first - second ); /* display difference */ printf( "The difference between the times is %d seconds\n", difference ); return 0; /* indicate successful termination */ } /* end main */ /* seconds returns number of seconds since clock "struck 12" given input time as hours h, minutes m, seconds s */ unsigned seconds( unsigned h, unsigned m, unsigned s ) { return 3600 * h + 60 * m + s; } /* end function seconds */  Enter the first time as three integers: 4 20 39 Enter the second time as three integers: 7 20 39 The difference between the times is 10800 seconds  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  112 C Functions: Solutions  5.24  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  Chapter 5  Implement the following integer functions: a) Function celsius returns the Celsius equivalent of a Fahrenheit temperature. b) Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature. c) Use these functions to write a program that prints charts showing the Fahrenheit equivalents of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of all Fahrenheit temperatures from 32 to 212 degrees. Print the outputs in a neat tabular format that minimizes the number of lines of output while remaining readable. ANS: /* Exercise 5.24 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                      int celcius( int fTemp ); /* function prototype */ int fahrenheit( int cTemp ); /* function prototype */ int main() { int i; /* loop counter */ /* display table of Fahrenheit equivalents of Celsius temperature */ printf( "Fahrenheit equivalents of Celcius temperatures:\n" ); printf( "Celcius\t\tFahrenheit\n" ); /* display Fahrenheit equivalents of Celsius 0 to 100 */ for ( i = 0; i <= 100; i++ ) { printf( "%d\t\t%d\n", i, fahrenheit( i ) ); } /* end for */ /* display table of Celsius equivalents of Fahrenheit temperature */ printf( "\nCelcius equivalents of Fahrenheit temperatures:\n" ); printf( "Fahrenheit\tCelcius\n" ); /* display Celsius equivalents of Fahrenheit 32 to 212 */ for ( i = 32; i <= 212; i++ ) { printf( "%d\t\t%d\n", i, celcius( i ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* celsius returns Celsius equivalent of fTemp, given in Fahrenheit */ int celcius( int fTemp ) { return ( int ) ( 5.0 / 9.0 * ( fTemp - 32 ) ); } /* end function celsius */ /* fahrenheit returns Fahrenheit equivalent of cTemp, given in Celsius */ int fahrenheit( int cTemp ) { return ( int ) ( 9.0 / 5.0 * cTemp + 32 ); } /* end function fahrenheit */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 113  Chapter 5  Fahrenheit equivalents of Celcius temperatures: Celcius Fahrenheit 0 32 1 33 2 35 3 37 4 39 5 41 6 42 7 44 8 46 9 48 . . . Celcius equivalents of Fahrenheit temperatures: Fahrenheit Celcius 32 0 33 0 34 1 35 1 36 2 37 2 38 3 39 3 40 4 41 5 . . .  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  114 C Functions: Solutions  5.25  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  Write a function that returns the smallest of three floating point numbers. ANS: /* Exercise 5.25 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                          /* function prototype */ double smallest3( double a, double b, double c ); int main() { double x; /* first input */ double y; /* second input */ double z; /* third input */ printf( "Enter three doubleing point values: " ); scanf( "%lf%lf%lf", &x, &y, &z ); /* determine smallest value */ printf( "The smallest value is %f\n", smallest3( x, y, z ) ); return 0; /* indicate successful termination */ } /* end main */ /* smallest3 returns the smallest of a, b and c */ double smallest3( double a, double b, double c ) { double smallest = a; /* assume a is the smallest */ if ( b < smallest ) { /* if b is smaller */ smallest = b; } /* end if */ if ( c < smallest ) { /* if c is smaller */ smallest = c; } /* end if */ return smallest; /* return smallest value */ } /* end function smallest3 */  Enter three doubleing point values: 3.3 4.4 5.5 The smallest value is 3.300000  Enter three doubleing point values: 4.4 5.5 3.3 The smallest value is 3.300000  Enter three doubleing point values: 4.4 3.3 5.5 The smallest value is 3.300000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 115  Chapter 5  5.26 An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number because 6 = 1 + 2 + 3. Write a function perfect that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000. 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  /* Exercise 5.26 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                              int perfect( int value ); /* function prototype */ int main() { int j; /* loop counter */ printf( "For the integers from 1 to 1000:\n" ); /* loop from 2 to 1000 */ for ( j = 2; j <= 1000; j++ ) { /* if current integer is perfect */ if ( perfect( j ) ) { printf( "%d is perfect\n", j ); } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* perfect returns true if value is perfect integer, i.e., if value is equal to sum of its factors */ int perfect( int value ) { int factorSum = 1; /* current sum of factors */ int i; /* loop counter */ /* loop through possible factor values */ for ( i = 2; i <= value / 2; i++ ) { /* if i is factor */ if ( value % i == 0 ) { factorSum += i; /* add to sum */ } /* end if */ } /* end for */ /* return true if value is equal to sum of factors */ if ( factorSum == value ) { return 1; } /* end if */ else { return 0; } /* end else */ } /* end function perfect */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  116 C Functions: Solutions  For the integers from 1 to 1000: 6 is perfect 28 is perfect 496 is perfect  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 117  Chapter 5  5.27 An integer is said to be prime if it is divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not. a) Write a function that determines if a number is prime. b) Use this function in a program that determines and prints all the prime numbers between 1 and 10,000. How many of these 10,000 numbers do you really have to test before being sure that you have found all the primes? c) Initially you might think that n/2 is the upper limit for which you must test to see if a number is prime, but you need only go as high as the square root of n. Why? Rewrite the program, and run it both ways. Estimate the performance improvement. 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  /* Exercise 5.27 Solution Part B Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                  int prime( int n ); int main() { int loop; /* loop counter */ int count = 0; /* total number of primes found */ printf( "The prime numbers from 1 to 10000 are:\n" ); /* loop through 1 to 10000 */ for ( loop = 1; loop <= 10000; loop++ ) { /* if current number is prime */ if ( prime( loop ) ) { ++count; printf( "%6d", loop ); /* new line after 10 values displayed */ if ( count % 10 == 0 ) { printf( "\n" ); } /* end if */ } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* prime returns 1 if n is prime */ int prime( int n ) { int loop2; /* loop counter */ /* loop through possible factors */ for ( loop2 = 2; loop2 <= n / 2; loop2++ ) { /* if factor found, not prime */ if ( n % loop2 == 0 ) { return 0; } /* end if */ } /* end for */ return 1; /* return 1 if prime */ } /* end function prime */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  118 C Functions: Solutions  The prime numbers from 1 to 10000 are: 1 2 3 5 7 11 13 29 31 37 41 43 47 53 71 73 79 83 89 97 101 113 127 131 137 139 149 151 . . . 9733 9739 9743 9749 9767 9769 9781 9811 9817 9829 9833 9839 9851 9857 9887 9901 9907 9923 9929 9931 9941  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  Chapter 5  17 59 103 157  19 61 107 163  23 67 109 167  9787 9859 9949  9791 9871 9967  9803 9883 9973  /* Exercise 5.27 Part C Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                          int prime( int n ); /* function prototype */ int main() { int j; /* loop counter */ int count = 0; /* total number of primes found */ printf( "The prime numbers from 1 to 10000 are:\n" ); /* loop through numbers 1 to 10000 */ for ( j = 1; j <= 10000; j++ ) { /* if current number prime */ if ( prime( j ) ) { ++count; printf( "%5d", j ); /* new line after 10 values displayed */ if ( count % 10 == 0 ) { printf( "\n" ); } /* end if */ } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* prime returns 1 if n is prime */ int prime( int n ) { int i; /* loop counter */ /* loop through possible factors */ for ( i = 2; i <= ( int ) sqrt( n ); i++ ) { /* if factor found, not prime */ if ( n % i == 0 ) { return 0; } /* end if */ } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 119  Chapter 5  49 50 51 52  return 1; } /* end function prime */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  120 C Functions: Solutions  Chapter 5  5.28 Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the function should return 1367. 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 5.28 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                              int reverseDigits( int n ); int main() { int number; /* input number */ printf( "Enter a number between 1 and 9999: " ); scanf( "%d", &number ); /* find number with digits reversed */ printf( "The number with its digits reversed is: %d\n", reverseDigits( number ) ); return 0; /* indicate successful termination */ } /* end main */ /* reverseDigits returns number obtained by reversing digits of n */ int reverseDigits( int n ) { int reverse = 0; /* reversed number */ int divisor = 1000; /* current divisor */ int multiplier = 1; /* current multiplier */ /* loop until single-digit number */ while ( n > 9 ) { /* if n >= current divisor, determine digit */ if ( n >= divisor ) { /* update reversed number with current digit */ reverse += n / divisor * multiplier; n %= divisor; /* update n */ divisor /= 10; /* update divisor */ multiplier *= 10; /* update multiplier */ } /* end if */ else { /* else, no digit */ divisor /= 10; /* update divisor */ } /* end else */ } /* end while */ reverse += n * multiplier; return reverse; /* return reversed number */ } /* end function reverseDigits */  Enter a number between 1 and 9999: 6 The number with its digits reversed is: 6  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 121  Chapter 5  Enter a number between 1 and 9999: 9273 The number with its digits reversed is: 3729  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  122 C Functions: Solutions  Chapter 5  5.29 The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write function gcd that returns the greatest common divisor of two integers. 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  /* Exercise 5.29 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                  int gcd( int x, int y ); /* function prototype */ int main() { int j; /* loop counter */ int a; /* first number */ int b; /* second number */ /* loop for 5 pairs of inputs */ for ( j = 1; j <= 5; j++ ) { printf( "Enter two integers: " ); scanf( "%d%d", &a, &b ); /* find greatest common divisor of a and b */ printf( "The greatest common divisor " "of %d and %d is %d\n\n", a, b, gcd( a, b ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* gcd find greatest common divisor of x and y */ int gcd( int x, int y ) { int i; int greatest = 1; /* current gcd, 1 is minimum */ /* loop from 2 to smaller of x and y */ for ( i = 2; i <= ( ( x < y ) ? x : y ); i++ ) { /* if current i divides both x and y */ if ( x % i == 0 && y % i == 0 ) { greatest = i; /* update greatest common divisor */ } /* end if */ } /* end for */ return greatest; /* return greatest common divisor found */ } /* end function gcd */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 123  Chapter 5  Enter two integers: 75 225 The greatest common divisor of 75 and 225 is 75 Enter two integers: 99 30 The greatest common divisor of 99 and 30 is 3 Enter two integers: 17 22 The greatest common divisor of 17 and 22 is 1 Enter two integers: 100 92 The greatest common divisor of 100 and 92 is 4 Enter two integers: 10005 15 The greatest common divisor of 10005 and 15 is 15  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  124 C Functions: Solutions  Chapter 5  5.30 Write a function qualityPoints that inputs a student's average and returns 4 if a student's average is 90-100, 3 if the average is 80-89, 2 if the average is 70-79, 1 if the average is 60-69, and 0 if the average is lower than 60. 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  /* Exercise 5.30 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                      int qualityPoints( int average ); /* function prototype */ int main() { int average; /* current average */ int loop; /* loop counter */ /* loop for 5 inputs */ for ( loop = 1; loop <= 5; loop++ ) { printf( "\nEnter the student's average: " ); scanf( "%d", &average ); /* determine and display corresponding quality points */ printf( "%d on a 4 point scale is %d\n", average, qualityPoints( average ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* qualityPoints takes average in range 0 to 100 and returns corresponding quality points on 0 to 4 scale */ int qualityPoints( int average ) { /* 90 <= average <= 100 */ if ( average >= 90 ) { return 4; } /* end if */ else if ( average >= 80 ) { return 3; } /* end else if */ else if ( average >= 70 ) { return 2; } /* end else if */ else if ( average >= 60 ) { return 1; } /* end else if */ else { /* 0 <= average < 60 return 0; } /* end else */  /* 80 <= average <= 89 */  /* 70 <= average <= 79 */  /* 60 <= average <= 69 */  */  } /* end function qualityPoints */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 125  Chapter 5  Enter the student's average: 92 92 on a 4 point scale is 4 Enter the student's average: 87 87 on a 4 point scale is 3 Enter the student's average: 75 75 on a 4 point scale is 2 Enter the student's average: 63 63 on a 4 point scale is 1 Enter the student's average: 22 22 on a 4 point scale is 0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  126 C Functions: Solutions  Chapter 5  5.31 Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the coin 100 times, and count the number of times each side of the coin appears. Print the results. The program should call a separate function flip that takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time for a total of approximately 50 heads and 50 tails.] 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 53 54 55  /* Exercise 5.31 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                  int flip(); /* function prototype */ int main() { int loop; /* loop counter */ int headCount = 0; /* total Heads count */ int tailCount = 0; /* total Tails count */ srand( time( NULL ) ); /* seed random number generator */ /* simulate coin toss 100 times */ for ( loop = 1; loop <= 100; loop++ ) { /* simulate coin toss, 0 refers to tails */ if ( flip() == 0 ) { tailCount++; /* update Tails count */ } /* end if */ else { headCount++; /* update Heads count */ } /* end else */ if ( loop % 10 == 0 ) { printf( "\n" ); } /* end if */ } /* end for */ /* display totals */ printf( "\nThe total number of Heads was %d\n", headCount ); printf( "The total number of Tails was %d\n", tailCount ); return 0; /* indicate successful termination */ } /* end main */ /* flip uses random number to simulate coin toss */ int flip() { int HorT = rand() %2; /* scale by 2 for binary result */ /* display result of flip */ if ( HorT == 0 ) { printf( "Tails " ); } /* end if */ else { printf( "Heads " ); } /* end else */ return HorT; /* return result of coin toss */ } /* end function flip */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 127  Chapter 5  Tails Tails Tails Tails Heads Tails Tails Heads Tails Heads  Heads Tails Heads Tails Heads Tails Tails Tails Tails Tails  Tails Tails Heads Heads Heads Tails Tails Tails Tails Tails  Tails Heads Tails Heads Heads Heads Heads Heads Tails Heads  Tails Tails Tails Heads Heads Heads Heads Tails Heads Tails  Tails Heads Heads Heads Tails Tails Tails Tails Tails Tails  Heads Tails Tails Heads Tails Tails Tails Tails Heads Heads  Tails Tails Tails Heads Tails Tails Heads Tails Heads Tails  Tails Heads Tails Tails Tails Tails Tails Heads Tails Tails  Tails Tails Tails Tails Tails Heads Tails Tails Tails Tails  The total number of Heads was 34 The total number of Tails was 66  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  128 C Functions: Solutions  Chapter 5  5.32 Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use rand to produce two positive one-digit integers. It should then type a question such as: How much is 6 times 7?  The student then types the answer. Your program checks the student's answer. If it is correct, print "Very good!" and then ask another multiplication question. If the answer is wrong, print "No. Please try again." and then let the student try the same question again repeatedly until the student finally gets it right. 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  /* Exercise 5.32 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                              void multiplication( void ); /* function prototype */ int main( void ) { srand( time( NULL ) ); /* seed random number generator */ multiplication(); /* begin multiplication practice */ return 0; /* indicate successful termination */ } /* end main */ /* multiplication produces pairs of random numbers and prompts user for product */ void multiplication( void ) { int x; /* first factor */ int y; /* second factor */ int response = 0; /* user response for product */ /* use sentinel-controlled repetition */ printf( "Enter -1 to end.\n" ); /* loop while sentinel while ( response != -1 x = rand() % 10; /* y = rand() % 10; /*  value not read from user */ ) { generate 1-digit random number */ generate another 1-digit random number */  printf( "How much is %d times %d? ", x, y ); scanf( "%d", &response ); /* loop while not sentinel value or correct response */ while ( response != -1 && response != x * y ) { printf( "No. Please try again.\n? " ); scanf( "%d", &response ); } /* end while */ /* correct response */ if ( response != -1 ) { printf( "Very good!\n\n" ); } /* end if */ } /* end while */ printf( "That's all for now. Bye.\n" ); } /* end function multiplication */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 129  Chapter 5  Enter -1 to end. How much is 0 times 7? 0 Very good! How much is 0 times 0? 0 Very good! How much is 2 times 6? 18 No. Please try again. ? 12 Very good! How much is 5 times 0? 0 Very good! How much is 9 times 2? 18 Very good! How much is 6 times 1? -1 That's all for now. Bye.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  130 C Functions: Solutions  Chapter 5  5.33 The use of computers in education is referred to as computer-assisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This can be eliminated by varying the computer's dialogue to hold the student's attention. Modify the program of Exercise 5.32 so the various comments are printed for each correct answer and each incorrect answer as follows: Responses to a correct answer Very good! Excellent! Nice work! Keep up the good work!  Responses to an incorrect answer No. Please try again. Wrong. Try once more. Don't give up! No. Keep trying.  Use the random number generator to choose a number from 1 to 4 to select an appropriate response to each answer. Use a switch statement with printf statements to issue the responses.  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  /* Exercise 5.33 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                          void correctMessage( void ); /* function prototype */ void incorrectMessage( void ); /* function prototype */ void multiplication( void ); /* function prototype */ int main() { srand( time( NULL ) ); /* seed random number generator */ multiplication(); /* begin multiplication practice */ return 0; /* indicate successful termination */ } /* end main */ /* correctMessage randomly chooses response to correct answer */ void correctMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { /* display a random response */ case 0: printf( "Very good!\n\n" ); break; /* exit switch */ case 1: printf( "Excellent!\n\n" ); break; /* exit switch */ case 2: printf( "Nice work!\n\n" ); break; /* exit switch */ case 3: printf( "Keep up the good work!\n\n" ); break; /* exit switch */ } /* end switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 131  Chapter 5  43 44 45 46 47 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 92 93 94 95 96 97 98 99 100 101 102 103  } /* end function correctMessage */ /* incorrectMessage randomly chooses response to incorrect answer */ void incorrectMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { /* display random response */ case 0: printf( "No. Please try again.\n? " ); break; /* exit switch */ case 1: printf( "Wrong. Try once more.\n? " ); break; /* exit switch */ case 2: printf( "Don't give up!\n? " ); break; /* exit switch */ case 3: printf( "No. Keep trying.\n? " ); break; /* exit switch */ } /* end switch */ } /* end function incorrectMessage */ /* multiplication produces pairs of random numbers and prompts user for product */ void multiplication( void ) { int x; /* first factor */ int y; /* second factor */ int response = 0; /* user response for product */ /* use sentinel-controlled repetition */ printf( "Enter -1 to end.\n" ); /* loop while sentinel while ( response != -1 x = rand() % 10; /* y = rand() % 10; /*  value not read from user */ ) { generate 1-digit random number */ generate another 1-digit random number */  printf( "How much is %d times %d? ", x, y ); scanf( "%d", &response ); /* loop while not sentinel value or correct response */ while ( response != -1 && response != x * y ) { incorrectMessage(); scanf( "%d", &response ); } /* end while */ /* correct response */ if ( response != -1 ) { correctMessage(); } /* end if */ } /* end while */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  132 C Functions: Solutions  104 105 printf( "That's all for now. Bye.\n" ); 106 } /* end function multiplication */ Enter -1 to end. How much is 7 times 6? 42 Very good! How much is 8 times 5? 40 Excellent! How much is 7 times 2? 15 No. Please try again. ? 14 Keep up the good work! How much is 9 times 6? 54 Keep up the good work! How much is 3 times 7? -1 That's all for now. Bye.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 133  Chapter 5  5.34 More sophisticated computer-aided instructions systems monitor the student's performance over a period of time. The decision to begin a new topic is often based on the student's success with previous topics. Modify the program of Exercise 5.33 to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75 percent, your program should print "Please ask your instructor for extra help" and then terminate. 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 53  /* Exercise 5.34 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      void multiplication( void ); /* function prototype */ void correctMessage( void ); /* function prototype */ void incorrectMessage( void ); /* function prototype */ int main() { srand( time( NULL ) ); /* seed random number generator */ multiplication(); /* begin multiplication practice */ return 0; /* indicate successful termination */ } /* end main */ /* multiplication produces pairs of random numbers and prompts user for product */ void multiplication( void ) { int i; /* loop counter */ int x; /* first factor */ int y; /* second factor */ int response; /* user response for product */ int right = 0; /* total number of right responses */ int wrong = 0; /* total number of wrong responses */ /* loop 10 times */ for ( i = 1; i <= 10; i++ ) { x = rand() % 10; /* generate 1-digit random number */ y = rand() % 10; /* generate another 1-digit random number */ printf( "How much is %d times %d? ", x, y ); scanf( "%d", &response ); /* loop while not correct response */ while ( response != x * y ) { wrong++; /* update total number of wrong responses */ incorrectMessage(); scanf( "%d", &response ); } /* end while */ right++; /* update total number of correct responses */ correctMessage(); } /* end for */ /* determine if help is needed */ if ( ( double ) right / ( right + wrong ) < .75 ) { printf( "Please ask your instructor for extra help.\n" ); } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  134 C Functions: Solutions  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 108 109  printf( "That's all for now. Bye.\n" ); } /* end function multiplication */ /* correctMessage randomly chooses response to correct answer */ void correctMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { /* display random response */ case 0: printf( "Very good!\n\n" ); break; /* exit switch */ case 1: printf( "Excellent!\n\n" ); break; /* exit switch */ case 2: printf( "Nice work!\n\n" ); break; /* exit switch */ case 3: printf( "Keep up the good work!\n\n" ); break; /* exit switch */ } /* end switch */ } /* end function correctMessage */ /* incorrectMessage randomly chooses response to incorrect answer */ void incorrectMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { /* display random response */ case 0: printf( "No. Please try again.\n? " ); break; /* exit switch */ case 1: printf( "Wrong. Try once more.\n? " ); break; /* exit switch */ case 2: printf( "Don't give up!\n? " ); break; /* exit switch */ case 3: printf( "No. Keep trying.\n? " ); break; /* exit switch */ } /* end switch */ } /* end function incorrectMessage */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 135  Chapter 5  How much is 3 times 9? 27 Excellent! How much is 1 times 3? 3 Very good! How much is 8 times 1? 8 Very good! How much is 3 times 6? 24 No. Please try again. ? 18 Excellent! ... How much is 1 times 9? 9 Very good! How much is 4 times 0? 4 Wrong. Try once more. ? 0 Excellent! How much is 5 times 8? 40 Nice work! That's all for now. Bye.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  136 C Functions: Solutions  Chapter 5  5.35 Write a C program that plays the game of "guess the number" as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then types:  I have a number between 1 and 1000. Can you guess my number? Please type your first guess.  The player then types a first guess. The program responds with one of the following:  1. Excellent! You guessed the number! Would you like to play again (y or n)? 2. Too low. Try again. 3. Too high. Try again.  If the player's guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player "zero in" on the correct answer. [Note: The searching technique employed in this problem is called binary search. We will say more about this in the next problem.] 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  /* Exercise 5.35 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  void guessGame( void ); /* function prototype */ int main() { srand( time( NULL ) ); /* seed random number generator */ guessGame(); return 0; /* indicate successful termination */ } /* end main */ /* guessGame generates numbers between 1 and 1000 and checks user's guess */ void guessGame( void ) { int x; /* randomly generated number */ int guess; /* user's guess */ int response; /* response to continue game, 1=yes, 2=no */ /* loop until user types 2 to quit game */ do { /* generate random number between 1 and 1000 1 is shift, 1000 is scaling factor */ x = 1 + rand() % 1000; /* prompt for guess */ printf( "\nI have a number between 1 and 1000.\n" ); printf( "Can you guess my number?\n" ); printf( "Please type your first guess.\n? " ); scanf( "%d", &guess );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 137  Chapter 5  38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59  /* loop until correct number */ while ( guess != x ) { /* if guess is too low */ if ( guess < x ) { printf( "Too low. Try again.\n? " ); } /* end if */ else { /* guess is too high */ printf( "Too high. Try again.\n? " ); } /* end else */ scanf( "%d", &guess ); } /* end while */ /* prompt for another game */ printf( "\nExcellent! You guessed the number!\n" ); printf( "Would you like to play again?\n" ); printf( "Please type ( 1=yes, 2=no )? " ); scanf( "%d", &response ); } while ( response == 1 ); /* end do...while */ } /* end function guessGame */  I have a number between 1 and 1000. Can you guess my number? Please type your first guess. ? 500 Too low. Try again. ? 750 Too high. Try again. ? 625 Too low. Try again. ? 687 Too high. Try again. ? 656 Too low. Try again. ? 671 Too low. Try again. ? 678 Too high. Try again. ? 675 Too high. Try again. ? 673 Too high. Try again. ? 672 Excellent! You guessed the number! Would you like to play again? Please type ( 1=yes, 2=no )? 2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  138 C Functions: Solutions  5.36  Chapter 5  Modify the program of Exercise 5.35 to count the number of guesses the player makes. If the number is 10 or fewer, print  Either you know the secret or you got lucky! If the player guesses the number in 10 tries, then print Ahah! You know the secret! If the player makes more than 10 guesses, then print You should be able to do better! Why should it take no more  than 10 guesses? Well with each "good guess" the player should be able to eliminate half of the numbers. Now show why any number 1 to 1000 can be guessed in 10 or fewer tries. 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 53  /* Exercise 5.36 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              void guessGame( void ); /* function prototype */ int main() { srand( time( NULL ) ); /* seed random number generator */ guessGame(); return 0; /* indicate successful termination */ } /* end main */ /* guessGame generates numbers between 1 and 1000 and checks user's guess */ void guessGame( void ) { int x; /* randomly generated number */ int guess; /* user's guess */ int total = 1; /* number of guesses */ int response; /* response to continue game, 1=yes, 0=no */ /* loop until user enters 0 to quit game */ do { /* generate random number between 1 and 1000 1 is shift, 1000 is scaling factor */ x = 1 + rand() % 1000; /* prompt for guess */ printf( "\nI have a number between 1 and 1000.\n" ); printf( "Can you guess my number?\n" ); printf( "Please type your first guess.\n? " ); scanf( "%d", &guess ); /* loop while not correct answer */ while ( guess != x ) { /* guess is incorrect; display hint */ if ( guess < x ) { printf( "Too low. Try again.\n? " ); } /* end if */ else { printf( "Too high. Try again.\n? " ); } /* end else */ scanf( "%d", &guess ); total++; } /* end while */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 139  Chapter 5  54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73  printf( "\nExcellent! You guessed the number!\n" ); /* determine if user knows "secret" */ if ( total < 10 ) { printf( "Either you know the secret or you got lucky!\n" ); } /* end if */ else if ( total == 10 ) { printf( "Ahah! You know the secret!\n" ); } /* end else if */ else { printf( "You should be able to do better!\n\n" ); } /* end else */ /* prompt for another game */ printf( "Would you like to play again?\n" ); printf( "Please type ( 1=yes, 2=no )? " ); scanf( "%d", &response ); } while ( response == 1 ); /* end do...while */ } /* end function guessGame */  I have a number between 1 and 1000. Can you guess my number? Please type your first guess. ? 500 Too high. Try again. ? 250 Too high. Try again. ? 125 Too high. Try again. ? 62 Too high. Try again. ? 31 Too low. Try again. ? 46 Too high. Try again. ? 39 Too low. Try again. ? 42 Excellent! You guessed the number! Either you know the secret or you got lucky! Would you like to play again? Please type ( 1=yes, 2=no )? 2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  140 C Functions: Solutions  5.37  Chapter 5  Write a recursive function power( base, exponent ) that when invoked returns baseexponent  For example, power( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. Hint: The recursion step would use the relationship baseexponent = base * baseexponent - 1  and the terminating condition occurs when exponent is equal to 1 because base1 = base  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  /* Exercise 5.37 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  long power( long base, long exponent ); /* function prototype */ int main() { long b; /* base */ long e; /* exponent */ printf( "Enter a base and an exponent: " ); scanf( "%ld%ld", &b, &e ); /* calculate and display b raised to the e power */ printf( "%ld raised to the %ld is %ld\n", b, e, power( b, e ) ); return 0; /* indicate successful termination */ } /* end main */ /* power recursively calculates base raised to the exponent assume exponent >= 1 */ long power( long base, long exponent ) { /* base case: exponent equals 1, return base */ if ( exponent == 1 ) { return base; } /* end if */ else { /* recursive step */ return base * power( base, exponent - 1 ); } /* end else */ } /* end function power */  Enter a base and an exponent: 5 10 5 raised to the 10 is 9765625  5.38  The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, …  begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. a) Write a nonrecursive function fibonacci( n ) that calculates the nth Fibonacci number. b) Determine the largest Fibonacci number that can be printed on your system. Modify the program of part a) to use double instead of int to calculate and return Fibonacci numbers. Let the program loop until it fails because of an excessively high value.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 141  Chapter 5  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  /* Exercise 5.38 Part A Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define MAX 23 /* the maximum number for which the */ /* fibonacci value can be calculated */ /* on 2-byte integer systems */ int fibonacci( int n ); int main() { int loop; /* loop counter */ /* calculate and display Fibonacci value for 0 to MAX */ for ( loop = 0; loop <= MAX; loop++ ) { printf( "fibonacci( %d ) = %d\n", loop, fibonacci( loop ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* fibonacci nonrecursively calculates nth Fibonacci number */ int fibonacci( int n ) { int j; /* loop counter */ int fib[ MAX ]; /* define array of size MAX */ fib[ 0 ] = 0; fib[ 1 ] = 1; /* loop to find nth Fibonacci value */ for ( j = 2; j <= n; j++ ) { fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ]; } /* end for */ return fib[ n ]; /* return nth Fibonacci value */ } /* end function fibonacci */  fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci(  0 ) = 0 1 ) = 1 2 ) = 1 3 ) = 2 4 ) = 3 5 ) = 5 6 ) = 8 7 ) = 13 8 ) = 21 9 ) = 34 10 ) = 55 11 ) = 89 12 ) = 144 13 ) = 233 14 ) = 377 15 ) = 610 16 ) = 987 17 ) = 1597 18 ) = 2584 19 ) = 4181 20 ) = 6765 21 ) = 10946 22 ) = 17711 23 ) = 28658  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  142 C Functions: Solutions  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  /* Exercise 5.38 Part B Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define SIZE 100 double fibonacci( int n ); /* function prototype */ int main() { int loop; /* loop counter */ /* loop SIZE times and calculate Fibonacci values */ for ( loop = 0; loop < SIZE; loop++ ) { printf( "fibonacci( %d ) = %.1f\n", loop, fibonacci( loop ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* fibonacci nonrecursively calculates nth Fibonacci number */ double fibonacci( int n ) { int j; /* loop counter */ double fib[ SIZE ]; /* define double array of size SIZE */ fib[ 0 ] = 0.0; fib[ 1 ] = 1.0; /* loop to find nth Fibonacci value */ for ( j = 2; j <= n; j++ ) { fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ]; } /* end for */ return fib[ n ]; /* return nth Fibonacci value */ } /* end function fibonacci */  fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( . . . fibonacci( fibonacci( fibonacci( fibonacci(  0 ) = 0.0 1 ) = 1.0 2 ) = 1.0 3 ) = 2.0 4 ) = 3.0 5 ) = 5.0 6 ) = 8.0 7 ) = 13.0 8 ) = 21.0 9 ) = 34.0 10 ) = 55.0 11 ) = 89.0 12 ) = 144.0  96 97 98 99  ) ) ) )  = = = =  51680708854858326000.0 83621143489848426000.0 135301852344706760000.0 218922995834555200000.0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 143  Chapter 5  5.39 (Towers of Hanoi) Every budding computer scientist must grapple with certain classic problems, and the Towers of Hanoi (see Fig. 5.19) is one of the most famous of these. Legend has it that in a temple in the Far East, priests are attempting to move a stack of disks from one peg to another. The initial stack had 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from this peg to a second peg under the constraints that exactly one disk is moved at a time, and at no time may a larger disk be placed above a smaller disk. A third peg is available for temporarily holding the disks. Supposedly the world will end when the priests complete their task, so there is little incentive for us to facilitate their efforts. Let us assume that the priests are attempting to move the disks from peg 1 to peg 3. We wish to develop an algorithm that will print the precise sequence of disk-to-disk peg transfers. If we were to approach this problem with conventional methods, we would rapidly find ourselves hopelessly knotted up in managing the disks. Instead, if we attack the problem with recursion in mind, it immediately becomes tractable. Moving n disks can be viewed in terms of moving only n – 1 disks (and hence the recursion) as follows: a) Move n – 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area. b) Move the last disk (the largest) from peg 1 to peg 3. c) Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area.  Fig. 5.18 The Towers of Hanoi for the case with four disks. The process ends when the last task involves moving n = 1 disk, i.e., the base case. This is accomplished by trivially moving the disk without the need for a temporary holding area. Write a program to solve the Towers of Hanoi problem. Use a recursive function with four parameters: a) The number of disks to be moved b) The peg on which these disks are initially threaded c) The peg to which this stack of disks is to be moved d) The peg to be used as a temporary holding area Your program should print the precise instructions it will take to move the disks from the starting peg to the destination peg. For example, to move a stack of three disks from peg 1 to peg 3, your program should print the following series of moves: 1 → 3 (This means move one disk from peg 1 to peg 3.) 1→2 3→2 1→3 2→1 2→3 1→3  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  144 C Functions: Solutions  Chapter 5  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  /* Exercise 5.39 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* function prototype */ void tower( int c, int start, int end, int temp ); int main() { int n; /* number of disks */ printf( "Enter the starting number of disks: " ); scanf( "%d", &n ); /* print instructions for moving disks from peg 1 to peg 3 using peg 2 for temporary storage */ tower( n, 1, 3, 2 ); return 0; /* indicate successful termination */ } /* end main */ /* tower recursively prints instructions for moving disks from start peg to end peg using temp peg for temporary storage */ void tower( int c, int start, int end, int temp ) { /* base case */ if ( c == 1 ) { printf( "%d --> %d\n", start, end ); return; } /* end if */ /* move c - 1 disks from start to temp */ tower( c - 1, start, temp, end ); /* move last disk from start to end printf( "%d --> %d\n", start, end );  */  /* move c - 1 disks from temp to end tower( c - 1, temp, end, start ); } /* end function tower */  */  Enter 1 --> 1 --> 2 --> 1 --> 3 --> 3 --> 1 --> 1 --> 2 --> 2 --> 3 --> 2 --> 1 --> 1 --> 2 -->  the starting number of disks: 4 2 3 3 2 1 2 2 3 3 1 1 3 2 3 3  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 145  Chapter 5  5.40 Any program that can be implemented recursively can be implemented iteratively, although sometimes with considerably more difficulty and considerably less clarity. Try writing an iterative version of the Towers of Hanoi. If you succeed, compare your iterative version with the recursive version you developed in Exercise 5.39. Investigate issues of performance, clarity, and your ability to demonstrate the correctness of the programs. 5.41 (Visualizing Recursion) It is interesting to watch recursion "in action." Modify the factorial function of Fig. 5.14 to print its local variable and recursive call parameter. For each recursive call, display the outputs on a separate line and add a level of indentation. Do your utmost to make the outputs clear, interesting, and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text. ANS: Note: The printf in function printRecursion uses the conversion specification %*d. The * enables the programmer to specify the field width as a variable argument in the printf. In this case variable n is used as the field width, and its value is output. 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  /* Exercise 5.41 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  long factorial( long number ); /* function prototype */ void printRecursion( int n ); /* function prototype */ int main() { int i; /* loop counter */ /* calculate factorial( i ) and display result */ for ( i = 0; i <= 10; i++ ) { printf( "%2d! = %ld\n", i, factorial( i ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* recursive definition of function factorial */ long factorial( long number ) { /* base case */ if ( number <= 1 ) { return 1; } /* end if */ else { /* recursive step */ printRecursion( number ); /* add outputs and indentation */ return ( number * factorial( number - 1 ) ); } /* end else */ } /* end function factorial */ /* printRecursion adds outputs and indentation to help visualize recursion */ void printRecursion( int n ) { printf( "number = %*d\n", n, n ); } /* end function printRecursion */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  146 C Functions: Solutions  0! = 1 1! = 1 number = 2 2! = 2 number = 3 number = 2 3! = 6 number = 4 number = 3 number = 2 4! = 24 number = 5 number = 4 number = 3 number = 2 5! = 120 . . . number = 9 number = 8 number = 7 number = 6 number = 5 number = 4 number = 3 number = 2 9! = 362880 number = 10 number = 9 number = 8 number = 7 number = 6 number = 5 number = 4 number = 3 number = 2 10! = 3628800  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 147  Chapter 5  5.42 The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd( x, y ) is x; otherwise gcd( x, y ) is gcd( y, x % y ) where % is the remainder operator. 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  /* Exercise 5.42 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* function prototype */ unsigned int gcd( unsigned int xMatch, unsigned int yMatch ); int main() { unsigned int x; /* first integer */ unsigned int y; /* second integer */ unsigned int gcDiv; /* greatest common divisor of x and y */ printf( "Enter two integers: " ); scanf( "%u%u", &x, &y ); gcDiv = gcd( x, y ); printf( "Greatest common divisor of %u and %u is %u\n", x, y, gcDiv ); return 0; /* indicate successful termination */ } /* end main */ /* gcd recursively finds greatest common divisor of xMatch and yMatch */ unsigned int gcd( unsigned int xMatch, unsigned int yMatch ) { /* base case */ if ( yMatch == 0 ) { return xMatch; } /* end if */ else { /* recursive step */ return gcd( yMatch, xMatch % yMatch ); } /* end else */ } /* end function gcd */  Enter two integers: 10112 50500 Greatest common divisor of 10112 and 50500 is 4  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  148 C Functions: Solutions  Chapter 5  5.43 Can main be called recursively? Write a program containing a function main. Include static local variable count initialized to 1. Postincrement and print the value of count each time main is called. Run your program. What happens? ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  /* Exercise 5.43 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { static int count = 1; /* static local variable count */ printf( "%d\n", count ); count++; main(); /* recursively call int main() */ return 0; /* indicate successful termination */ } /* end main */  1 2 3 4 5 6 7 8 9 10 ...  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 149  Chapter 5  5.44 Exercises 5.32 through 5.34 developed a computer-assisted instruction program to teach an elementary school student multiplication. This exercise suggests enhancements to that program. a) Modify the program to allow the user to enter a grade-level capability. A grade level of 1 means to use only single-digit numbers in the problems, a grade level of two means to use numbers as large as two-digits, etc. 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 53 54 55 56 57 58 59 60 61  /* Exercise 5.44 Part A Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int randValue( int level ); void multiplication( void ); void correctMessage( void ); void incorrectMessage( void );  /* /* /* /*  function function function function  prototype prototype prototype prototype  */ */ */ */  int main() { srand( time( NULL ) ); /* seed random number generator */ multiplication(); /* being multiplication practice */ return 0; /* indicate successful termination */ } /* end main */ /* randValue generates random numbers based on grade level */ int randValue( int level ) { /* level determines size of random number */ switch ( level ) { case 1: return rand() % 10; case 2: return rand() % 100; case 3: return rand() % 1000; default: return rand() % 10; } /* end switch */ } /* end function randValue */ /* multiplication produces pairs of random numbers and prompts user for product; level determines size of numbers */ void multiplication( void ) { int i; /* loop counter */ int x; /* first factor */ int y; /* second factor */ int gradeLevel; /* grade-level capability */ int right = 0; /* total number of right responses */ int wrong = 0; /* total number of wrong responses */ unsigned int response; /* user response for product */ printf( "Enter the grade-level ( 1 to 3 ): " ); scanf( "%d", &gradeLevel ); /* loop 10 times */ for ( i = 1; i <= 10; i++ ) { /* generate random numbers depending on level */ x = randValue( gradeLevel ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  150 C Functions: Solutions  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129  y = randValue( gradeLevel ); printf( "How much is %d times %d? ", x, y ); scanf( "%u", &response ); /* loop while response is incorrect */ while ( response != x * y ) { ++wrong; /* update total number of wrong answers */ incorrectMessage(); scanf( "%u", &response ); } /* end while */ ++right; /* update total number of right answers */ correctMessage(); } /* end for */ /* if < 75% right */ if ( ( double ) right / ( right + wrong) < .75 ) { printf( "Please ask your instructor for extra help.\n" ); } /* end if */ printf( "That's all for now. Bye.\n" ); } /* end function multiplication */ /* correctMessage randomly chooses response to correct answer */ void correctMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { case 0: printf( "Very good!\n\n" ); break; /* exit switch */ case 1: printf( "Excellent!\n\n" ); break; /* exit switch */ case 2: printf( "Nice work!\n\n" ); break; /* exit switch */ case 3: printf( "Keep up the good work!\n\n" ); break; /* exit switch */ } /* end switch */ } /* end function correctMessage */ /* incorrectMessage randomly chooses response to incorrect answer */ void incorrectMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { case 0: printf( "No. Please try again.\n? " ); break; /* exit switch */ case 1: printf( "Wrong. Try once more.\n? " ); break; /* exit switch */ case 2: printf( "Don't give up!\n? " ); break; /* exit switch */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 151  Chapter 5  130 131 case 3: 132 printf( "No. Keep trying.\n? " ); 133 break; /* exit switch */ 134 } /* end switch */ 135 136 } /* end function incorrectMessage */ Enter the grade-level ( 1 to 3 ): 1 How much is 6 times 0? 0 Keep up the good work! How much is 6 times 3? 18 Keep up the good work! ...  Enter the grade-level ( 1 to 3 ): 2 How much is 5 times 63? 315 Excellent! How much is 29 times 13? 392 No. Please try again. ? 377 Excellent! ...  Enter the grade-level ( 1 to 3 ): 3 How much is 799 times 343? 274057 Keep up the good work! How much is 201 times 349? 0 Don't give up! ...  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  152 C Functions: Solutions  Chapter 5  b) Modify the program to allow the user to pick the type of arithmetic problems he or she wishes to study. An option of 1 means addition problems only, 2 means subtraction problems only, 3 means multiplication problems only, 4 means division problems only, and 5 means to randomly intermix problems of all these types. 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 53 54 55 56 57 58 59 60 61 62 63  /* Exercise 5.44 Part B Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int menu( void ); void arithmetic( void ); void correctMessage( void ); void incorrectMessage( void );  /* /* /* /*  function function function function  prototype prototype prototype prototype  */ */ */ */  int main() { srand( time( NULL ) ); /* seed random number generator */ arithmetic(); /* begin arithmetic process */ return 0; /* indicate successful termination */ } /* end main */ /* menu displays user menu of choices */ int menu( void ) { int choice; /* user's choice */ /* display menu and read user's choice */ do { printf( "Choose type of problem to study.\n" ); printf( "Enter: 1 for addition, 2 for subtraction\n" ); printf( "Enter: 3 for multiplication, 4 for division\n" ); printf( "Enter: 5 for a combination of 1 through 4\n " ); printf( "? " ); scanf( "%d", &choice ); } while ( choice < 1 || choice > 5 ); /* end do...while */ return choice; /* return user's choice */ } /* end function menu */ /* incorrectMessage randomly chooses response to incorrect answer */ void incorrectMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { case 0: printf( "No. Please try again.\n? " ); break; /* exit switch */ case 1: printf( "Wrong. Try once more.\n? " ); break; /* exit switch */ case 2: printf( "Don't give up!\n? " ); break; /* exit switch */ case 3: printf( "No. Keep trying.\n? " ); break; /* exit switch */ } /* end switch */ } /* end function incorrectMessage */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 153  Chapter 5  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131  /* correctMessage randomly chooses response to correct answer */ void correctMessage( void ) { /* generate random number between 0 and 3 */ switch ( rand() % 4 ) { case 0: printf( "Very good!\n\n" ); break; /* exit switch */ case 1: printf( "Excellent!\n\n" ); break; /* exit switch */ case 2: printf( "Nice work!\n\n" ); break; /* exit switch */ case 3: printf( "Keep up the good work!\n\n" ); break; /* exit switch */ } /* end switch */ } /* end function correctMessage */ void arithmetic( void { int i; /* int x; /* int y; /* int response; /* int answer; /* int selection; /* int right = 0; /* int wrong = 0; /* int type; /* int problemMix; /* char operator; /*  ) loop counter */ first number */ second number */ user response for product */ correct answer */ menu selection */ total correct responses */ total incorrect responses */ type of problems chosen */ random choice of type of problem */ arithmetic operator */  selection = menu(); type = selection; /* loop 10 times */ for ( i = 1; i <= 10; i++ ) { x = rand() % 10; /* generate first random number */ y = rand() % 10; /* generate second random number */ /* if option 5, randomly select type */ if ( selection == 5 ) { problemMix = 1 + rand() % 4; type = problemMix; } /* end if */ /* generate answer and define operator depending on option */ switch ( type ) { /* option 1: addition */ case 1: operator = '+'; answer = x + y; break; /* exit switch */ /* option 2: subtraction */ case 2: operator = ''-';  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  154 C Functions: Solutions  132 answer = x - y; 133 break; /* exit switch */ 134 135 /* option 3: multiplication */ 136 case 3: 137 operator = '*'; 138 answer = x * y; 139 break; /* exit switch */ 140 141 /* option 4: integer division */ 142 case 4: 143 operator = '/'; 144 145 /* eliminate divide by zero error */ 146 if ( y == 0 ) { 147 y = 1; 148 answer = x / y; 149 } /* end if */ 150 else { 151 x *= y; /* create "nice" division */ 152 answer = x / y; 153 } /* end else */ 154 155 break; /* exit switch */ 156 } /* end switch */ 157 158 printf( "How much is %d %c %d? ", x, operator, y ); 159 160 scanf( "%d", &response ); 161 162 /* while not correct answer */ 163 while ( response != answer ) { 164 ++wrong; 165 incorrectMessage(); 166 scanf( "%d", &response ); 167 } /* end while */ 168 169 ++right; 170 correctMessage(); 171 } /* end for */ 172 173 /* if < 75% right, suggest help */ 174 if ( ( double ) right / ( right + wrong) < .75 ) { 175 printf( "Please ask your instructor for extra help.\n" ); 176 } /* end if */ 177 178 printf( "That's all for now. Bye.\n" ); 179 } /* end function arithmetic */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 155  Chapter 5  Choose type of problem to study. Enter: 1 for addition, 2 for subtraction Enter: 3 for multiplication, 4 for division Enter: 5 for a combination of 1 through 4 ? 5 How much is 9 * 9? 81 Nice work! How much is 3 - 1? 2 Keep up the good work! How much is 1 * 3? 3 Nice work! . . . How much is 1 - 9? -8 Nice work! That's all for now. Bye.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  156 C Functions: Solutions  Chapter 5  5.45 Write function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. 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  /* Exercise 5.45 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* function prototype */ double distance( double xOne, double yOne, double xTwo, double yTwo ); int main() { double x1; double y1; double x2; double y2; double dist;  /* /* /* /* /*  x coordinate of first point */ y coordinate of first point */ x coordinate of second point */ y coordinate of second point */ distance between two points */  /* prompt for first point coordinates */ printf( "Enter the first point: " ); scanf( "%lf%lf", &x1, &y1 ); /* prompt for second point coordinates */ printf( "Enter the second point: " ); scanf( "%lf%lf", &x2, &y2 ); dist = distance( x1, y1, x2, y2 ); /* calculate distance */ printf( "Distance between ( %.2f, %.2f )" " and ( %.2f, %.2f ) is %.2f\n", x1, y1, x2, y2, dist ); return 0; /* indicate successful termination */ } /* end main */ /* distance calculates distance between 2 points given by (xOne, yOne) and (xTwo, yTwo) */ double distance( double xOne, double yOne, double xTwo, double yTwo ) { double distance; /* distance between two points */ distance = sqrt( pow( xOne - xTwo, 2 ) + pow( yOne - yTwo, 2 ) ); return distance; } /* end function distance */  Enter the first point: 3 4 Enter the second point: 0 0 Distance between ( 3.00, 4.00 ) and ( 0.00, 0.00 ) is 5.00  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 157  Chapter 5  5.46 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  What does the following program do? #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* function main begins program execution */ int main() { int c; /* variable to hold character input by user */ if ( ( c = getchar() ) != EOF ) { main(); printf( "%c", c ); } /* end if */ return 0; /* indicates successful termination */ } /* end main */  ANS: Inputs a character and recursively calls main() until the EOF character is entered. Every character entered is then output in reverse order.  a b c c b a  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  158 C Functions: Solutions  5.47 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  What does the following program do? #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int mystery( int a, int b ); /* function prototype */ /* function main begins program execution */ int main() { int x; /* first integer */ int y; /* second integer */ printf( "Enter two integers: " ); scanf( "%d%d", &x, &y ); printf( "The result is %d\n", mystery( x, y ) ); return 0; /* indicates successful termination */ } /* end main */ /* Parameter b must be a positive integer to prevent infinite recursion */ int mystery( int a, int b ) { /* base case */ if ( b == 1 ) { return a; } /* end if */ else { /* recursive step */ return a + mystery( a, b - 1 ); } /* end else */ } /* end function mystery */  ANS: The problem mimics multiplication by adding up a, b times.  Enter two integers: 87 6 The result is 522  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 159  Chapter 5  5.48 After you determine what the program of Exercise 5.47 does, modify the program to function properly after removing the restriction of the second argument being nonnegative. 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  /* Exercise 5.48 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int mystery( int a, int b ); /* function prototype */ int main() { int x; /* first integer */ int y; /* second integer */ printf( "Enter two integers: " ); scanf( "%d%d", &x, &y ); printf( "The result is %d\n", mystery( x, y ) ); return 0; /* indicate successful termination */ } /* end main */ /* mystery multiplies a * b using recursion */ int mystery( int a, int b ) { /* if a and if ( ( a < a *= -1; b *= -1; } /* end if  b or just b are negative */ 0 && b < 0 ) || b < 0 ) { /* multiply a and b by -1 to make positive */ */  /* base case */ if ( b == 1 ) { return a; } /* end if */ else { /* recursive step */ return a + mystery( a, b - 1 ); } /* end else */ } /* end function mystery */  Enter two integers: -97 6 The result is -582  Enter two integers: 97 -6 The result is -582  Enter two integers: -97 -6 The result is 582  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  160 C Functions: Solutions  Chapter 5  5.49 Write a program that tests as many of the math library functions in Fig. 5.2 as you can. Exercise each of these functions by having your program print out tables of return values for a diversity of argument values. 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 53 54 55 56 57 58 59 60 61 62 63  /* Exercise 5.49 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int loop; /* integer loop counter */ int count; /* loop counter */ double loop2; /* double loop counter */ /* loop and test each math function */ for ( count = 1; count < 14; count++) { /* test math function based on count */ switch ( count ) { /* print table headers */ case 1: printf( "funct " ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10d ", loop ); } /* end for */ break; /* exit switch */ /* display sqrt for range of values */ case 2: printf( "\nsqrt() " ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10.2lf ", sqrt( loop ) ); } /* end for */ break; /* exit switch */ /* display exp for range of values */ case 3: printf( "exp() " ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10.2lf ", exp( loop ) ); } /* end for */ break; /* exit switch */ /* display natural log for range of values */ case 4: printf( "log() " ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10.2lf ", log( loop ) ); } /* end for */ break; /* exit switch */ /* display log base 10 for range of values */ case 5: printf( "log10() " ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10.2lf ", log10( loop ) ); } /* end for */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 161  Chapter 5  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130  break; /* exit switch */ /* display pow function, test with 2 as base */ case 6: printf( "pow( 2,x )" ); for ( loop = 1; loop < 6; loop++ ) { printf( "%10.2lf ", pow( 2, loop ) ); } /* end for */ break; /* exit switch */ /* display table headers */ case 7: printf( "\n\nfunct " ); for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { printf( "%10.2lf ", loop2 ); } /* end for */ break; /* exit switch */ /* display fabs for range of values */ case 8: printf( "\nfabs() " ); for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { printf( "%10.2lf ", fabs( loop2 ) ); } /* end for */ break; /* exit switch */ /* display ceil for range of values */ case 9: printf( "ceil() " ); for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { printf( "%10.2lf ", ceil( loop2 ) ); } /* end for */ break; /* exit switch */ /* display floor for range of values */ case 10: printf( "floor() " ); for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { printf( "%10.2lf ", floor( loop2 ) ); } /* end for */ break; /* exit switch */ /* display sin for range of values */ case 11: printf( "sin() " ); for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { printf( "%10.2lf ", sin( loop2 ) ); } /* end for */ break; /* exit switch */ /* display cos for range of values */ case 12: printf( "cos() " );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  162 C Functions: Solutions  Chapter 5  131 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 132 printf( "%10.2lf ", cos( loop2 ) ); 133 } /* end for */ 134 135 break; /* exit switch */ 136 137 /* display tan for range of values */ 138 case 13: 139 printf( "tan() " ); 140 141 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 142 printf( "%10.2lf ", tan( loop2 ) ); 143 } /* end for */ 144 145 break; /* exit switch */ 146 } /* end switch */ 147 148 printf( "\n" ); 149 } /* end for */ 150 151 return 0; /* indicate successful termination */ 152 153 } /* end main */ funct  1  sqrt() exp() log() log10() pow( 2,x )  funct fabs() ceil() floor() sin() cos() tan()  5.50  2  3  4  5  1.00 2.72 0.00 0.00 2.00  1.41 7.39 0.69 0.30 4.00  1.73 20.09 1.10 0.48 8.00  2.00 54.60 1.39 0.60 16.00  2.24 148.41 1.61 0.70 32.00  -1.50  -0.40  0.70  1.80  2.90  1.50 -1.00 -2.00 -1.00 0.07 -14.10  0.40 0.00 -1.00 -0.39 0.92 -0.42  0.70 1.00 0.00 0.64 0.76 0.84  1.80 2.00 1.00 0.97 -0.23 -4.29  2.90 3.00 2.00 0.24 -0.97 -0.25  Find the error in each of the following program segments and explain how to correct it: a) double cube( float ); /* function prototype */ ... cube( float number ) /* function definition */ { return number * number * number; }  ANS: Function definition is missing return type. double cube( float );  /* function prototype */  ... double cube( float number ) /* function definition */ { return number * number * number; } b) register auto int x = 7;  ANS: Too many storage class definitions. Auto class definition is not necessary. register int x = 7; /* auto removed */ c) int randomNumber = srand();  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 163  Chapter 5  ANS: srand() seeds the random number generator, and has a void return type. Function rand() produces random numbers. int randomNumber = rand(); d) double y = 123.45678; int x; x = y; printf( "%f\n", (double) x ); ANS: Decimal value is lost when a double is assigned to an integer. Type-casting the int to double cannot bring back the original decimal value. Only 123.000000 can be printed. double y = 123.45678; double x; x = y; printf( "%f\n", x ); e) double square( double number ) { double number; return number * number; }  ANS: number is defined twice. double square( double number ) { return number * number; } f) int sum( int n ) { if ( n == 0 ) return 0; else return n + sum( n ); } ANS: Infinite recursion. int sum( int { if ( n == return else return }  n ) 0 ) 0; n + sum( n - 1 );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  164 C Functions: Solutions  Chapter 5  5.51 Modify the craps program of Fig. 5.10 to allow wagering. Package as a function the portion of the program that runs one game of craps. Initialize variable bankBalance to 1000 dollars. Prompt the player to enter a wager. Use a while loop to check that wager is less than or equal to bankBalance and if not prompt the user to reenter wager until a valid wager is entered. After a correct wager is entered, run one game of craps. If the player wins, increase bankBalance by wager and print the new bankBalance. If the player loses, decrease bankBalance by wager, print the new bankBalance, check if bankBalance has become zero, and if so print the message "Sorry. You busted!" As the game progresses, print various messages to create some "chatter" such as "Oh, you're going for broke, huh?", or "Aw cmon, take a chance!", or "You're up big. Now's the time to cash in your chips!". 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 53 54 55 56  /* Exercise 5.51 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* enumeration constants represent game status */ enum Status { CONTINUE, WON, LOST }; int rollDice( void ); /* function prototype */ enum Status craps( void ); /* function prototype */ void chatter( void ); /* function prototype */ int main() { enum Status result; /* result of current game */ int wager = 0; /* wager for current game */ int bankBalance = 1000; /* current bank balance */ srand( time( NULL ) ); /* seed random number generator */ /* display current balance and prompt for wager */ printf( "You have $%d in the bank.\n", bankBalance ); printf( "Place your wager: " ); scanf( "%d", &wager ); /* loop while not valid wager */ while( wager <= 0 || wager > 1000 ) { printf( "Please bet a valid amount.\n" ); scanf( "%d", &wager ); } /* end while */ result = craps(); /* play game of craps */ /* if player lost current game */ if ( result == LOST ) { /* decrease balance by wager and display new balance */ bankBalance -= wager; printf( "Your new bank balance is $%d\n", bankBalance ); /* if balance is 0 */ if ( bankBalance == 0 ) { printf( "Sorry. You are Busted! Thank You For Playing.\n" ); } /* end if */ } /* end if */ else { /* player won game */ /* increase balance by wager and display new balance */ bankBalance += wager; printf( "Your new bank balance is $%d\n", bankBalance ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Functions: Solutions 165  Chapter 5  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125  /* roll dice, calculate sum and display results */ int rollDice( void ) { int die1; /* first die value */ int die2; /* second die value */ int workSum; /* sum of dice */ die1 = 1 + rand() % 6; /* pick random die1 value */ die2 = 1 + rand() % 6; /* pick random die2 value */ workSum = die1 + die2; /* sum die1 and die2 */ /* display results of this roll */ printf( "Player rolled %d + %d = %d\n", die1, die2, workSum ); return workSum; /* return sum of dice */ } /* end function rollDice */ /* craps plays one game of enum Status craps( void ) { enum Status gameStatus; int sum; int myPoint;  craps, returns result of game */ /* can contain CONTINUE, WON or LOST */ /* current roll of dice */ /* point value */  sum = rollDice(); /* first roll of dice */ /* determine game status and point based on sum of dice */ switch ( sum ) { /* win on first roll */ case 7: case 11: gameStatus = WON; chatter(); break; /* exit switch */ /* lose on first roll */ case 2: case 3: case 12: gameStatus = LOST; chatter(); break; /* exit switch */ /* remember point */ default: gameStatus = CONTINUE; myPoint = sum; printf( "Point is %d\n", myPoint ); chatter(); break; /* exit switch */ } /* end switch */ /* while game not complete */ while ( gameStatus == CONTINUE ) { chatter(); sum = rollDice(); /* roll dice again */ /* determine game status */ if ( sum == myPoint ) { gameStatus = WON; /* win by making point */ } /* end if */ else { if ( sum == 7 ) { gameStatus = LOST; /* lose by rolling 7 */ } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  166 C Functions: Solutions  126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181  } /* end else */ } /* end while */ /* display won or lost message and return status */ if ( gameStatus == WON ) { printf( "Player wins\n" ); return WON; } /* end if */ else { printf( "Player loses\n" ); return LOST; } /* end else */ } /* end function craps */ /* chatter displays messages at random to create "chatter" */ void chatter( void ) { int select; /* random number */ select = 1 + rand() % 6; /* choose message at random */ switch ( select ) { case 1: printf( "Oh, you're going for broke, huh?\n" ); break; /* exit switch */ case 2: printf( "Aw cmon, take a chance!\n" ); break; /* exit switch */ case 3: printf( "Hey, I think this guy is going to break the bank!!\n" ); break; /* exit switch */ case 4: printf( "You're up big. Now's the time to cash in your chips!\n" ); break; /* exit switch */ case 5: printf( "Way too lucky! Those dice have to be loaded!\n" ); break; /* exit switch */ case 6: printf( "Bet it all! Bet it all!\n" ); break; /* exit switch */ default: break; /* exit switch */ } /* end switch */ } /* end function chatter */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  C Functions: Solutions 167  Chapter 5  You have $1000 in the bank. Place your wager: 1000 Player rolled 4 + 5 = 9 Point is 9 You're up big. Now's the time to cash in your chips! Oh, you're going for broke, huh? Player rolled 5 + 6 = 11 Hey, I think this guy is going to break the bank!! Player rolled 3 + 1 = 4 Bet it all! Bet it all! Player rolled 5 + 5 = 10 Aw cmon, take a chance! Player rolled 6 + 6 = 12 Bet it all! Bet it all! Player rolled 2 + 1 = 3 Hey, I think this guy is going to break the bank!! Player rolled 5 + 6 = 11 Hey, I think this guy is going to break the bank!! Player rolled 2 + 1 = 3 Aw cmon, take a chance! Player rolled 2 + 4 = 6 You're up big. Now's the time to cash in your chips! Player rolled 2 + 3 = 5 Oh, you're going for broke, huh? Player rolled 6 + 3 = 9 Player wins Your new bank balance is $2000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  168 C Functions: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 5  6 C Arrays: Solutions  EXERCISES 6.6  Fill in the blanks in each of the following: a) C stores lists of values in . ANS: arrays. b) The elements of an array are related by the fact that they . ANS: have the same name and type. c) When referring to an array element, the position number contained within parentheses is called a(n) . ANS: subscript. d) The names of the five elements of array p are , , , and . ANS: p[ 0 ], p[ 1 ], p[ 2 ], p[ 3 ], p[ 4 ]. e) The contents of a particular element of an array is called the of that element. ANS: value. f) Naming an array, stating its type and specifying the number of elements in the array is called the array. ANS: defining. g) The process of placing the elements of an array into either ascending or descending order is called . ANS: sorting. h) In a double-subscripted array, the first subscript (by convention) identifies the of an element and the second of an element. subscript (by convention) identifies the ANS: row, column. i) An m-by-n array contains rows, columns and elements. ANS: m, n, m * n. j) The name of the element in row 3 and column 5 of array d is . ANS: d[ 3 ][ 5 ].  6.7  State which of the following are true and which are false. If false, explain why. a) To refer to a particular location or element within an array, we specify the name of the array and the value of the particular element. ANS: False. We specify the name and the subscript of the element. b) An array definition reserves space for the array. ANS: True. c) To indicate that 100 locations should be reserved for integer array p, the programmer writes the definition p[ 100 ];  ANS: True. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  170 C Arrays: Solutions  Chapter 6  d) A C program that initializes the elements of a 15-element array to zero must contain one for statement. ANS: False. The elements of an array can be initialized in the definition. e) A C program that totals the elements of a double-subscripted array must contain nested for statements. ANS: False. It is possible to total the elements of a double-subscripted array by enumerating all the elements in an assignment statement. f) The mean, median and mode of the following set of values are 5, 6 and 7, respectively: 1, 2, 5, 6, 7, 7, 7. ANS: True. 6.8  Write statements to accomplish each of the following: a) Display the value of the seventh element of character array f. ANS: printf( "%c\n", f[ 6 ] ); b) Input a value into element 4 of single-subscripted floating-point array b. ANS: scanf( "%f", &b[ 4 ] ); c) Initialize each of the 5 elements of single-subscripted integer array g to 8. ANS: for ( loop = 0; loop <= 4; loop++ ) g[ loop ] = 8; d) Total the elements of floating-point array c of 100 elements.  ANS: for ( loop = 0; loop <= 99; loop++ ) sum += c[ loop ]; e) Copy array a into the first portion of array b. Assume double a[ 11 ], b[ 34 ];  ANS: for ( loop = 0; loop <= 10; loop++ ) b[ loop ] = a[ loop ];  f) Determine and print the smallest and largest values contained in 99-element floating-point array w. ANS: smallest = largest = w[ 0 ]; for ( loop = 1; loop <= 98; loop++ ) if ( w[ loop ] < smallest ) smallest = w[ loop ]; else if ( w[ loop ] > largest ) largest = w[ loop ];  6.9  Consider a 2-by-5 integer array t. a) Write a definition for t. ANS: int t[ 2 ][ 5 ]; b) How many rows does t have? ANS: 2 c) How many columns does t have? ANS: 5 d) How many elements does t have? ANS: 10 e) Write the names of all the elements in the second row of t. ANS: t[ 1 ][ 0 ], t[ 1 ][ 1 ], t[ 1 ][ 2 ], t[ 1 ][ 3 ], t[ 1 ][ 4 ]. f) Write the names of all the elements in the third column of t. ANS: t[ 0 ][ 2 ], t[ 1 ][ 2 ]. g) Write a single statement that sets the element of t in row 1 and column 2 to zero. ANS: t[ 1 ][ 2 ] = 0; h) Write a series of statements that initialize each element of t to zero. Do not use a repetition structure. ANS: t[ t[ t[ t[ t[ t[  0 0 0 0 0 1  ][ ][ ][ ][ ][ ][  0 1 2 3 4 0  ] ] ] ] ] ]  = = = = = =  0; 0; 0; 0; 0; 0;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 171  Chapter 6  t[ t[ t[ t[  1 1 1 1  ][ ][ ][ ][  1 2 3 4  ] ] ] ]  = = = =  0; 0; 0; 0; Write a nested for statement that initializes each element of t to zero.  i) ANS:  for ( i = 0; i <= 1; i++ ) for ( j = 0; j <= 4; j++) t[ i ][ j ] = 0;  j) Write a statement that inputs the values for the elements of t from the terminal. ANS: for ( i = 0; i <= 1; i++ ) for ( j = 0; j <= 4; j++) { printf( "Enter an integer: " ); scanf( "%d", &t[ i ][ j ] ) }  k) Write a series of statements that determine and print the smallest value in array t. ANS: smallest = t[ 0 ][ 0 ]; for ( i = 0; i <= 1; i++ ) for ( j = 0; j <= 4; j++) if ( t[ i ][ j ] < smallest ) smallest = t[ i ][ j ]; printf( " smallest is %d\n", smallest );  l) Write a statement that displays the elements of the first row of t. ANS: for ( i = 0; i <= 4; i++ ) printf( "%d ", t[ 0 ][ i ] );  m) Write a statement that totals the elements of the fourth column of t. ANS: sum = t[ 0 ][ 3 ] + t[ 1 ][ 3 ]; n) Write a series of statements that print the array t in tabular format. List the column subscripts as headings across the top and list the row subscripts at the left of each row. ANS: printf( "  0\t1\t2\t3\t4\n" );  for ( i = 0; i <= 1; i++ ) { printf( "%d ", i ); for ( j = 0; j <= 4; j++ ) printf( "%d\t", t[ i ][ j ] ); printf( "\n" ); }  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  172 C Arrays: Solutions  Chapter 6  6.10 Use a single-subscripted array to solve the following problem. A company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9 percent of their gross sales for that week. For example, a salesperson who grosses $3000 in sales in a week receives $200 plus 9 percent of $3000, or a total of $470. Write a C program (using an array of counters) that determines how many of the salespeople earned salaries in each of the following ranges (assume that each salesperson's salary is truncated to an integer amount): a) $200–299 b) $300–399 c) $400–499 d) $500–599 e) $600–699 f) $700–799 g) $800–899 h) $900–999 i) $1000 and over 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  /* Exercise 6.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int salaries[ 11 ] = { 0 }; /* array to hold salary counts */ int sales; /* current employee's sales */ double salary; /* current employee's salary */ double i = 0.09; /* commission percentage */ /* prompt user for gross sales */ printf( "Enter employee gross sales ( -1 to end ): " ); scanf( "%d", &sales ); /* while sentinel value not read from user */ while ( sales != -1 ) { /* calculate salary based on sales */ salary = 200.0 + sales * i; printf( "Employee Commission is $%.2f\n", salary ); /* update appropriate salary range */ if ( salary >= 200 && salary < 1000 ) { ++salaries[ ( int ) salary / 100 ]; } /* end if */ else if ( salary >= 1000 ) { ++salaries[ 10 ]; } /* end else if */ /* prompt user for another employee sales amount */ printf( "\nEnter employee gross sales ( -1 to end ): " ); scanf( "%d", &sales ); } /* end while */ /* display table of ranges and employees in each range */ printf( "\nEmployees in the range:\n" ); printf( "$200-$299 : %d\n", salaries[ 2 ] ); printf( "$300-$399 : %d\n", salaries[ 3 ] ); printf( "$400-$499 : %d\n", salaries[ 4 ] ); printf( "$500-$599 : %d\n", salaries[ 5 ] ); printf( "$600-$699 : %d\n", salaries[ 6 ] ); printf( "$700-$799 : %d\n", salaries[ 7 ] ); printf( "$800-$899 : %d\n", salaries[ 8 ] ); printf( "$900-$999 : %d\n", salaries[ 9 ] ); printf( "Over $1000: %d\n", salaries[ 10 ] ); return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 173  Chapter 6  Enter employee gross sales ( -1 to end ): 3000 Employee Commission is $470.00 Enter employee gross sales ( -1 to end ): 1000 Employee Commission is $290.00 Enter employee gross sales ( -1 to end ): 10000 Employee Commission is $1100.00 Enter employee gross sales ( -1 to end ): 8000 Employee Commission is $920.00 Enter employee gross sales ( -1 to end ): 200 Employee Commission is $218.00 Enter employee gross sales ( -1 to end ): 7000 Employee Commission is $830.00 Enter employee gross sales ( -1 to end ): -1 Employees in the range: $200-$299 : 2 $300-$399 : 0 $400-$499 : 1 $500-$599 : 0 $600-$699 : 0 $700-$799 : 0 $800-$899 : 1 $900-$999 : 1 Over $1000: 1  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  174 C Arrays: Solutions  Chapter 6  6.11 The bubble sort presented in Fig. 6.15 is inefficient for large arrays. Make the following simple modifications to improve the performance of the bubble sort. a) After the first pass, the largest number is guaranteed to be in the highest-numbered element of the array; after the second pass, the two highest numbers are "in place," and so on. Instead of making nine comparisons on every pass, modify the bubble sort to make eight comparisons on the second pass, seven on the third pass and so on. b) The data in the array may already be in the proper order or near-proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass if any swaps have been made. If none has been made, then the data must already be in the proper order, so the program should terminate. If swaps have been made, then at least one more pass is needed. 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  /* Exercise 6.11 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define MAX 10 int main() { /* initialize array a with initializer list */ int a[ MAX ] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; int i; /* loop counter */ int pass; /* loop counter */ int hold; /* temporary variable for swapping */ int swap; /* flag to break loop if elements are sorted */ printf( "Data items in original order\n" ); /* display original, unsorted array */ for ( i = 0; i < MAX; i++ ) { printf( "%4d", a[ i ] ); } /* end for */ printf( "\n\n" ); /* begin sorting the array */ for ( pass = 1; pass < MAX; pass++ ) { swap = 0; /* traverse and compare unsorted part of array */ for ( i = 0; i < MAX - pass; i++ ) { /* compare adjacent array elements */ if ( a[ i ] > a[ i + 1 ] ) { swap = 1; /* raise flag if any elements are swapped */ hold = a[ i ]; a[ i ] = a[ i + 1 ]; a[ i + 1 ] = hold; } /* end if */ } /* end for */ printf( "After Pass %d: ", pass ); /* display array after each pass */ for ( i = 0; i <= MAX-pass; i++ ) { printf( " %d", a[ i ] ); } /* end for */ printf( "\n" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 175  Chapter 6  50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68  /* break loop if array is sorted */ if ( !swap ) { break; } /* end if */ } /* end for */ printf( "\nData items in ascending order\n" ); /* display array in sorted order */ for ( i = 0; i < 10; i++ ) { printf( "%4d", a[ i ] ); } /* end for */ printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */  Data items in original order 10 9 8 7 6 5 4 After After After After After After After After After  Pass Pass Pass Pass Pass Pass Pass Pass Pass  1: 2: 3: 4: 5: 6: 7: 8: 9:  9 8 7 6 5 4 3 2 1  8 7 6 5 4 3 2 1 2  7 6 5 4 3 2 1 3  6 5 4 3 2 1 4  3 5 4 3 2 1 5  Data items in ascending order 1 2 3 4 5 6 7  6.12  4 3 2 1 6  8  2 3 2 1 7  1 2 1 8  9  1 9  10  10  Write single statements that perform each of the following single-subscripted array operations: a) Initialize the 10 elements of integer array counts to zeros. ANS: for ( i = 0; i <= 9; i++ ) counts[ i ] = 0;  b) Add 1 to each of the 15 elements of integer array bonus. ANS: for ( i = 0; i <= 14; i++ ) ++bonus[ i ];  c) Read the 12 values of floating-point array monthlyTemperatures from the keyboard. ANS: for ( i = 0; i <= 11; i++ ) { printf( "Enter a temperature: " ); scanf( "%f", &monthlyTemperatures[ i ] ); } d) Print the 5 values of integer array bestScores in column format.  ANS: for ( i = 0; i <= 4; i++ ) { printf( "%d\t", bestScores[ i ] );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  176 C Arrays: Solutions  6.13  Chapter 6  Find the error(s) in each of the following statements: a) Assume: char str[ 5 ]; scanf( "%s", str );  /* User types hello */  ANS: str needs a minimum length of 6; one element for each letter in hello and an element for the terminating NULL character. b) Assume: int a[ 3 ]; printf( "$d  %d  %d\n", a[ 1 ], a[ 2 ], a[ 3 ] );  ANS: printf( "%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] ); c) double f[ 3 ] = { 1.1, 10.01, 100.001, 1000.0001 }; ANS: Too many variables defined. double f[ 3 ] = { 1.1, 10.01, 100.01 };  d) Assume: double d[ 2 ][ 10 ]; d[ 1, 9 ] = 2.345;  ANS: d[ 1 ][ 9 ] = 2.345;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 177  Chapter 6  6.14  Modify the program of Fig. 6.16 so function mode is capable of handling a tie for the mode value. Also modify function median so the two middle elements are averaged in an array with an even number of elements. 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 53 54 55 56 57 58 59 60 61 62 63  /* Exercise 6.14 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define SIZE 100 void mean( int answer[] ); /* function prototype */ void median( int answer[] ); /* function prototype */ void mode( int freq[], int answer[] ); /* function prototype */ int main() { /* array of responses */ int response[ SIZE ] = { 6, 7, 6, 7, 6, 7, 5, 7, 7, 4, int frequency[ 10 ] = { 0};  7, 8, 7, 8, 7, 8, 6, 8, 4, 5, /*  8, 9, 9, 5, 8, 9, 9, 8, 8, 7, 9, 8, 7, 2, 9, 6, 4, 2, 6, 1, array  8, 9, 3, 9, 8, 9, 5, 8, 5, 6, of  7, 8, 9, 8, 7, 8, 9, 8, 7, 8, 9, 7, 7, 9, 8, 8, 9, 7, 3, 9, 4, 7, 8, 9, 3, 8, 7, 5, 7, 8, response  8, 9, 7, 1, 1, 7, 1, 9, 9, 2, 5, 3, 6, 4, 7, 1, 5, 6, 7, 9}; frequencies */  mean( response ); /* process mean */ median( response ); /* process median */ mode( frequency, response ); /* process mode */ return 0; /* indicates successful termination */ } /* end main */ /* calculate average of all response values */ void mean( int answer[] ) { int j; /* loop counter */ int total = 0; /* total of all response values */ printf( "%s\n%s\n%s\n", "******", " Mean", "******" ); /* total response values */ for ( j = 0; j <= SIZE - 1; j++ ) { total += answer[ j ]; } /* end for */ /* output results */ printf( "The mean is the average value of the data\n" ); printf( "items. The mean is equal to the total of\n" ); printf( "all the data items divided by the number\n" ); printf( "of data items ( %d ). ,", SIZE ); printf( "The mean value for this run is: " ); printf( "%d / %d = %.4f\n\n", total, SIZE, ( double ) total / SIZE ); } /* end function mean */ /*sort an array and determine median element's value */ void median( int answer[] ) { int loop; /* loop counter */ int pass; /* loop counter */ int hold; /* temporary variable for swapping */ int firstRow; /* flag to indicate first row of array */  printf( "\n%s\n%s\n%s\n", "******", "Median", "******" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  178 C Arrays: Solutions  64 printf( "The unsorted array of responses is\n" ); 65 66 /* display unsorted array */ 67 for ( loop = 0, firstRow = 1; loop <= SIZE - 1; loop++ ) { 68 69 /* start a new line */ 70 if ( loop % 20 == 0 && !firstRow ) { 71 printf( "\n" ); 72 } /* end if */ 73 74 printf( "%2d", answer[ loop ] ); 75 firstRow = 0; 76 } /* end for */ 77 78 printf( "\n\n" ); 79 80 /* sort array */ 81 for ( pass = 0; pass <= SIZE - 2; pass++ ) { 82 83 /* compare elements and swap if necessary */ 84 for ( loop = 0; loop <= SIZE - 2; loop++ ) { 85 86 /* swap elements */ 87 if ( answer[ loop ] > answer[ loop + 1 ] ) { 88 hold = answer[ loop ]; 89 answer[ loop ] = answer[ loop + 1 ]; 90 answer[ loop + 1 ] = hold; 91 } /* end if */ 92 93 } /* end for */ 94 95 } /* end for */ 96 97 printf( "The sorted array is\n" ); 98 99 /* display sorted array */ 100 for ( loop = 0, firstRow = 1; loop <= SIZE - 1; loop++ ) { 101 102 /* start a new line */ 103 if ( loop % 20 == 0 && !firstRow ) { 104 printf( "\n" ); 105 } /* end if */ 106 107 printf( "%2d", answer[ loop ] ); 108 firstRow = 0; 109 } /* end for */ 110 111 printf( "\n\n" ); 112 113 /* even number of elements */ 114 if ( SIZE % 2 == 0 ) { 115 printf( "The median is the average of elements %d", 116 ( SIZE + 1 ) / 2 ); 117 printf( " and %d of", 1 + ( SIZE + 1 ) / 2 ); 118 printf( " the sorted %d element array.\n", SIZE ); 119 printf( "For this run the median is " ); 120 printf( "%.1f\n\n", ( double )( answer[ ( SIZE + 1 ) / 2 ] + 121 answer[ ( SIZE + 1 ) / 2 + 1 ] ) / 2 ); 122 } /* end if */ 123 else { /* odd number of elements */ 124 printf( "The median is element %d of ", ( SIZE + 1 ) / 2 ); 125 printf( "the sorted %d element array.\n", SIZE ); 126 printf( "For this run the median is " ); 127 printf( "%d\n\n", answer[ ( SIZE + 1 ) / 2 - 1 ] ); 128 } /* end else */ 129 130 } /* end function median */ 131 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 179  Chapter 6  132 /* determine most frequent response */ 133 void mode( int freq[], int answer[] ) 134 { 135 int rating; /* loop counter */ 136 int loop; /* loop counter */ 137 int largest = 0; /* represents largest frequency */ 138 int array[ 10 ] = { 0}; /* array used to hold largest frequencies */ 139 int count = 0; /* flag to count number of modes */ 140 141 printf( "\n%s\n%s\n%s\n", "******", " Mode", "******" ); 142 143 /* set all frequencies to 0 */ 144 for ( rating = 1; rating <= 9; rating++ ) { 145 freq[ rating ] = 0; 146 } /* end for */ 147 148 /* traverse array and increment corresponding frequency */ 149 for ( loop = 0; loop <= SIZE - 1; loop++ ) { 150 ++freq[ answer[ loop ] ]; 151 } /* end for */ 152 153 printf( "%s%11s%19s\n\n", "Response", "Frequency", "Histogram" ); 154 printf( "%54s\n", "1 1 2 2" ); 155 printf( "%54s\n\n", "5 0 5 0 5" ); 156 157 /* display values and frequency */ 158 for ( rating = 1; rating <= 9; rating++ ) { 159 printf( "%8d%11d ", rating, freq[ rating ] ); 160 161 /* test if current frequency is greater than largest frequency */ 162 if ( freq[ rating ] > largest ) { 163 largest = freq[ rating ]; 164 165 /* set values of array to 0 */ 166 for ( loop = 0; loop < 10; loop++ ) { 167 array[ loop ] = 0; 168 } /* end for */ 169 170 /* add new largest frequency to array */ 171 array[ rating ] = largest; 172 ++count; 173 } /* end if */ 174 /* if current frequency equals largest, add current to array */ 175 else if ( freq[ rating ] == largest ) { 176 array[ rating ] = largest; 177 ++count; 178 } /* end else if */ 179 180 /* display histogram */ 181 for ( loop = 1; loop <= freq[ rating ]; loop++ ) { 182 printf( "*" ); 183 } /* end for */ 184 185 printf( "\n" ); 186 } /* end for */ 187 188 printf( "\n" ); 189 190 /* if more than one mode */ 191 if ( count > 1 ) { 192 printf( "The modes are: " ); 193 } /* end if */ 194 else { /* only one mode */ 195 printf( "The mode is: " ); 196 } /* end else */ 197 198 /* display mode(s) */ 199 for ( loop = 1; loop <= 9; loop++ ) { © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  180 C Arrays: Solutions  Chapter 6  200 201 if ( array[ loop ] != 0 ) { 202 printf( "%d with a frequency of %d\n\t\t", loop, array[ loop ] ); 203 } /* end if */ 204 205 } /* end for */ 206 207 printf( "\n" ); 208 } /* end function mode */ ****** Mean ****** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items ( 100 ). ,The mean value for this run is: 662 / 100 = 6.6200 ****** Median ****** The unsorted 6 7 8 9 8 7 6 7 8 9 3 9 6 7 8 7 8 7 5 6 7 2 5 3 7 4 4 2 5 3 The sorted 1 1 1 1 1 5 5 5 5 5 7 7 7 7 7 8 8 8 8 8 9 9 9 9 9  array 8 9 8 8 7 1 9 8 9 9 4 6 8 7 5  array 2 2 2 6 6 6 7 7 7 8 8 8 9 9 9  of responses is 9 7 8 9 5 9 8 7 7 7 8 9 8 9 8 9 2 7 8 9 8 9 8 9 4 7 8 9 6 8 7 8 6 4 5 6 1 6 5 7  is 3 3 6 6 7 7 8 8 9 9  3 6 7 8 9  3 6 7 8 9  4 6 7 8 9  4 6 7 8 9  4 7 7 8 9  4 7 7 8 9  4 7 7 8 9  8 7 7 9 8  7 1 5 7 7  1 9 3 1 9  5 7 8 8 9  5 7 8 8 9  5 7 8 8 9  The median is the average of elements 50 and 51 of the sorted 100 element array. For this run the median is 7.0 ****** Mode ****** Response  Frequency  Histogram 5  1 2 3 4 5 6 7 8 9  5 3 4 5 8 9 23 23 20  The modes are:  1 0  1 5  2 0  2 5  ***** *** **** ***** ******** ********* *********************** *********************** ********************  7 with a frequency of 23 8 with a frequency of 23  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 181  Chapter 6  6.15 Use a single-subscripted array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it is not a duplicate of a number already read. Provide for the "worst case" in which all 20 numbers are different. Use the smallest possible array to solve this problem. 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  /* Exercise 6.15 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define MAX 20 int main() { int a[ MAX ] = { 0 }; /* array for user input */ int i; /* loop counter */ int j; /* loop counter */ int k = 0; /* number of values currently entered */ int duplicate; /* flag for duplicate values */ int value; /* current value */ printf( "Enter 20 integers between 10 and 100:\n" ); /* get 20 integers from user */ for ( i = 0; i <= MAX - 1; i++ ) { duplicate = 0; scanf( "%d", &value ); /* test if integer is a duplicate */ for ( j = 0; j < k; j++ ) { /* if duplicate, raise flag and break loop */ if ( value == a[ j ] ) { duplicate = 1; break; } /* end if */ } /* end for */ /* if number is not a duplicate enter it in array */ if ( !duplicate ) { a[ k++ ] = value; } /* end if */ } /* end for */ printf( "\nThe nonduplicate values are:\n" ); /* display array of nonduplicates */ for ( i = 0; a[ i ] != 0; i++ ) { printf( "%d ", a[ i ] ); } /* end for */ printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */  Enter 20 integers between 10 and 100: 10 11 12 13 14 15 16 17 18 19 20 21 10 11 12 13 14 15 16 17 The nonduplicate values are: 10 11 12 13 14 15 16 17  18  19  20  21  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  182 C Arrays: Solutions  Chapter 6  6.16 Label the elements of 3-by-5 double-subscripted array sales to indicate the order in which they are set to zero by the following program segment: for ( row = 0; row <= 2; row++ ) for ( column = 0; column <= 4; column++ ) sales[ row ][ column ] = 0;  ANS: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)  sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[ sales[  0 0 0 0 0 1 1 1 1 1 2 2 2 2 2  ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][  0 1 2 3 4 0 1 2 3 4 0 1 2 3 4  ] ] ] ] ] ] ] ] ] ] ] ] ] ] ]  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 183  Chapter 6  6.17 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  What does the following program do? /* ex06_17.c */ /* What does this program do? */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define SIZE 10 int whatIsThis( const int b[], int p ); /* function prototype */ /* function main begins program execution */ int main() { int x; /* holds return value of function whatIsThis */ /* initialize array a */ int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; x = whatIsThis( a, SIZE ); printf( "Result is %d\n", x ); return 0; /* indicates successful termination */ } /* end main */ /* what does this function do? */ int whatIsThis( const int b[], int p ) { /* base case */ if ( p == 1 ) { return b[ 0 ]; } /* end if */ else { /* recursion step */ return b[ p - 1 ] + whatIsThis( b, p - 1 ); } /* end else */ } /* end function whatIsThis */  ANS: The program recursively sums the elements in a.  Result is 55  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  184 C Arrays: Solutions  6.18 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  Chapter 6  What does the following program do? /* ex06_18.c */ /* What does this program do? */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define SIZE 10 /* function prototype */ void someFunction( const int b[], int startIndex, int size ); /* function main begins program execution */ int main() { int a[ SIZE ] = { 8, 3, 1, 2, 6, 0, 9, 7, 4, 5 }; /* initialize a */ printf( "Answer is:\n" ); someFunction( a, 0, SIZE ); printf( "\n" ); return 0; /* indicates successful termination */ } /* end main */ /* What does this function do? */ void someFunction( const int b[], int startIndex, int size ) { if ( startIndex < size ) { someFunction( b, startIndex + 1, size ); printf( "%d ", b[ startIndex ] ); } /* end if */ } /* end function someFunction */  ANS: The program recursively outputs the values of a in reverse order. Answer is: 5 4 7 9  0  6  2  1  3  8  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 185  Chapter 6  6.19  Write a program that simulates the rolling of two dice. The program should use rand to roll the first die, and should use rand again to roll the second die. The sum of the two values should then be calculated. [Note: Since each die can show an integer value from 1 to 6, then the sum of the two values will vary from 2 to 12 with 7 being the most frequent sum and 2 and 12 being the least frequent sums.] Figure 6.23 shows the 36 possible combinations of the two dice. Your program should roll the two dice 36,000 times. Use a single-subscripted array to tally the numbers of times each possible sum appears. Print the results in a tabular format. Also, determine if the totals are reasonable; i.e., there are six ways to roll a 7, so approximately one sixth of all the rolls should be 7.  1  2  3  4  5  6  1  2  3  4  5  6  7  2  3  4  5  6  7  8  3  4  5  6  7  8  9  4  5  6  7  8  9  10  5  6  7  8  9  10 11  6  7  8  9  10 11 12  Fig. 6.23 The 36 possible outcomes of rolling two dice. 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  /* Exercise 6.19 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { long i; int j; int x; int y; int sum[ 13 ] = { 0 };  /* /* /* /* /*  loop counter */ loop counter */ first die */ second die */ count occurrences of each combination */  /* array expected contains counts for the expected number of times each sum occurs in 36 rolls of the dice */ int expected[ 13 ] = { 0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; srand( time( NULL ) ); /* seed random number generator */ /* roll dice 36,000 times */ for ( i = 1; i <= 36000; i++ ) { x = 1 + rand() % 6; y = 1 + rand() % 6; ++sum[ x + y ]; } /* end for */ printf( "%10s%10s%10s%10s\n", "Sum", "Total", "Expected", "Actual" ); /* display results of rolling dice */ for ( j = 2; j <= 12; j++ ) { printf( "%10d%10d%9.3f%%%9.3f%%\n", j, sum[ j ], 100.0 * expected[ j ] / 36, 100.0 * sum[ j ] / 36000 ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  186 C Arrays: Solutions  Sum 2 3 4 5 6 7 8 9 10 11 12  Total 1018 2008 3020 4024 4891 6011 5065 3984 2970 1989 1020  Chapter 6  Expected 2.778% 5.556% 8.333% 11.111% 13.889% 16.667% 13.889% 11.111% 8.333% 5.556% 2.778%  Actual 2.828% 5.578% 8.389% 11.178% 13.586% 16.697% 14.069% 11.067% 8.250% 5.525% 2.833%  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 187  Chapter 6  6.20  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 53 54 55 56 57 58  Write a program that runs 1000 games of craps (without human intervention) and answers each of the following questions: a) How many games are won on the first roll, second roll, …, twentieth roll and after the twentieth roll? b) How many games are lost on the first roll, second roll, …, twentieth roll and after the twentieth roll? c) What are the chances of winning at craps? [Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?] d) What is the average length of a game of craps? e) Do the chances of winning improve with the length of the game? ANS: /* Exercise 6.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          enum Outcome { CONTINUE, WIN, LOSE }; int rollDice( void ); /* function prototype */ int main() { enum Outcome gameStatus; int sum; int myPoint; int i; int roll; int length = 0; int wins[ 22 ] = { 0 }; int losses[ 22 ] = { 0 }; int winSum = 0; int loseSum = 0;  /* /* /* /* /* /* /* /* /* /*  game status indicator */ sum of rolled dice */ current point */ game counter */ roll counter */ average length of game */ wins per roll */ losses per roll */ total wins */ total losses */  srand( time( NULL ) ); /* play 1000 times */ for ( i = 1; i <= 1000; i++ ) { sum = rollDice(); roll = 1; /* test if game won or lost on first roll */ switch ( sum ) { case 7: case 11: gameStatus = WIN; break; /* exit switch */ case 2: case 3: case 12: gameStatus = LOSE; break; /* exit switch */ default: gameStatus = CONTINUE; myPoint = sum; break; /* exit switch */ } /* end switch */ /* continue while game not won or lost */ while ( gameStatus == 0 ) { sum = rollDice(); roll++; /* win on next roll */ if ( sum == myPoint ) { gameStatus = WIN; } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  188 C Arrays: Solutions  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125  Chapter 6  else { /* lose on next roll */ if ( sum == 7 ) { gameStatus = LOSE; } /* end if */ } /* end else */ } /* end while */ /* if more than 21 rolls taken, set number of rolls to 21 */ if ( roll > 21 ) { roll = 21; } /* end if */ /* determine how many rolls were taken and increment corresponding counter in wins or losses array */ if ( gameStatus == WIN ) { wins[ roll ]++; winSum++; } /* end if */ else { losses[ roll ]++; loseSum++; } /* end else */ } /* end for */ printf( "Games won or lost after the 20th roll\n" "are displayed as the 21st roll.\n\n" ); /* display number of games won and lost for each number of rolls */ for ( i = 1; i <= 21; i++ ) { printf( "%3d games won and %3d games lost on roll %d.\n", wins[ i ], losses[ i ], i ); } /* end for */ /* calculate chances of winning */ printf( "\nThe chances of winning are %d/%d = %.2f%%\n", winSum, winSum + loseSum, 100.0 * winSum / ( winSum + loseSum ) ); /* calculate for ( i = 1; length += } /* end for  average length of game */ i <= 21; i++ ) { wins[ i ] * i + losses[ i ] * i; */  printf( "The average game length is %.2f rolls.\n", length / 1000.0 ); return 0; /* indicate successful termination */ } /* end main */ /* function to simulate dice rolling */ int rollDice( void ) { int die1; /* first die */ int die2; /* second die */ int workSum; /* dice sum */ die1 = 1 + rand() % 6; die2 = 1 + rand() % 6; workSum = die1 + die2; return workSum; /* return total of two dice */ } /* end function rollDice */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 189  Chapter 6  Games won or lost after the 20th roll are displayed as the 21st roll. 212 63 54 45 40 17 9 10 7 3 6 4 1 1 0 1 0 0 1 0 0  games games games games games games games games games games games games games games games games games games games games games  won won won won won won won won won won won won won won won won won won won won won  and 102 games lost on roll 1. and 109 games lost on roll 2. and 92 games lost on roll 3. and 70 games lost on roll 4. and 54 games lost on roll 5. and 34 games lost on roll 6. and 21 games lost on roll 7. and 11 games lost on roll 8. and 9 games lost on roll 9. and 2 games lost on roll 10. and 12 games lost on roll 11. and 4 games lost on roll 12. and 1 games lost on roll 13. and 0 games lost on roll 14. and 1 games lost on roll 15. and 1 games lost on roll 16. and 0 games lost on roll 17. and 1 games lost on roll 18. and 1 games lost on roll 19. and 0 games lost on roll 20. and 1 games lost on roll 21.  The chances of winning are 474/1000 = 47.40% The average game length is 3.36 rolls.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  190 C Arrays: Solutions  Chapter 6  6.21 (Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. The president has asked you to program the new system. You are to write a program to assign seats on each flight of the airline's only plane (capacity: 10 seats). Your program should display the following menu of alternatives: Please type 1 for "first class" Please type 2 for "economy"  If the person types 1, then your program should assign a seat in the first class section (seats 1-5). If the person types 2, then your program should assign a seat in the economy section (seats 6-10). Your program should then print a boarding pass indicating the person's seat number and whether it is in the first class or economy section of the plane. Use a single-subscripted array to represent the seating chart of the plane. Initialize all the elements of the array to 0 to indicate that all seats are empty. As each seat is assigned, set the corresponding elements of the array to 1 to indicate that the seat is no longer available. Your program should, of course, never assign a seat that has already been assigned. When the first class section is full, your program should ask the person if it is acceptable to be placed in the economy section (and vice versa). If yes, then make the appropriate seat assignment. If no, then print the message "Next flight leaves in 3 hours." 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  /* Exercise 6.21 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { int plane[ 11 ] = { 0 }; /* seats on the plane */ int i = 0; /* counter */ int firstClass= 1; /* first class seats start at 1 */ int economy = 6; /* economy seats start at 6 */ int choice; /* user's choice */ char response[ 2 ]; /* user's response */ /* loop 10 times */ while ( i < 10 ) { printf( "\n%s\n%s\n? ", "Please type 1 for \"first class\"", "Please type 2 for \"economy\"" ); scanf( "%d", &choice ); /* if user selects first class */ if ( choice == 1 ) { /* if seat are available in first class */ if ( !plane[ firstClass ] && firstClass <= 5 ) { printf( "Your seat assignment is %d\n", firstClass ); plane[ firstClass++ ] = 1; i++; } /* end if */ /* if no first class seats, but economy seats available */ else if ( firstClass > 5 && economy <= 10 ) { /* ask if passenger would like to sit in economy */ printf( "The first class section is full.\n" ); printf( "Would you like to sit in the economy" ); printf( " section ( Y or N )? " ); scanf( "%s", response ); /* if response is yes, then assign seat */ if ( toupper( response[ 0 ] ) == 'Y' ) { printf( "Your seat assignment is %d\n", economy ); plane[ economy++ ] = 1; i++; } /* end if */ else { /* print next departure */ printf( "Next flight leaves in 3 hours.\n" ); } /* end else */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 191  Chapter 6  47 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 92 93 94  } /* end else if */ else { /* print next departure */ printf( "Next flight leaves in 3 hours.\n" ); } /* end else */ } /* end if */ else { /* if user selects economy */ /* if seats available, assign seat */ if ( !plane[ economy ] && economy <= 10 ) { printf( "Your seat assignment is %d\n", economy ); plane[ economy++ ] = 1; i++; } /* end if */ /* if only first class seats are available */ else if ( economy > 10 && firstClass <= 5 ) { /* ask if first class is suitable */ printf( "The economy section is full.\n" ); printf( "Would you like to sit in first class" ); printf( " section ( Y or N )? " ); scanf( "%s", response ); /* if response is yes, assign seat */ if ( toupper( response[ 0 ] ) == 'Y' ) { printf( "Your seat assignment is %d\n", firstClass ); plane[ firstClass++ ] = 1; i++; } /* end if */ else { /* print next departure */ printf( "Next flight leaves in 3 hours.\n" ); } /* end else */ } /* end else if */ else { /* print next departure */ printf( "Next flight leaves in 3 hours.\n" ); } /* end else */ } /* end else */ } /* end while */ printf( "\nAll seats for this flight are sold.\n" ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  192 C Arrays: Solutions  Please type 1 for "first class" Please type 2 for "economy" ? 2 Your seat assignment is 6 Please type 1 for "first class" Please type 2 for "economy" ? 1 Your seat assignment is 1 Please type 1 for "first class" Please type 2 for "economy" ? 2 Your seat assignment is 7 . . . Please type 1 for "first class" Please type 2 for "economy" ? 1 The first class section is full. Would you like to sit in the economy section ( Y or N )? n Next flight leaves in 3 hours. Please type 1 for "first class" Please type 2 for "economy" ? 1 The first class section is full. Would you like to sit in the economy section ( Y or N )? y Your seat assignment is 9 Please type 1 for "first class" Please type 2 for "economy" ? 2 Your seat assignment is 10 All seats for this flight are sold.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 193  Chapter 6  6.22 Use a double-subscripted array to solve the following problem. A company has four salespeople (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each different type of product sold. Each slip contains: a) The salesperson number b) The product number c) The total dollar value of that product sold that day Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume that the information from all of the slips for last month is available. Write a program that will read all this information for last month's sales and summarize the total sales by salesperson by product. All totals should be stored in the double-subscripted array sales. After processing all the information for last month, print the results in tabular format with each of the columns representing a particular salesperson and each of the rows representing a particular product. Cross total each row to get the total sales of each product for last month; cross total each column to get the total sales by salesperson for last month. Your tabular printout should include these cross totals to the right of the totaled rows and to the bottom of the totaled columns. 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  /* Exercise 6.22 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { /* total sales for each salesperson and each product */ double sales[ 4 ][ 5 ] = { 0.0 }; double productSales[ 5 ] = { 0.0 }; /* total product sales */ double value; /* current sales */ double totalSales; /* total overall sales */ int salesPerson; /* current salesperson */ int product; /* current product */ int i; /* loop counter */ int j; /* loop counter */ printf( "Enter the salesperson, product, and total sales.\n" ); printf( "Enter -1 for the salesperon to end input.\n" ); scanf( "%d", &salesPerson ); /* continue receiving input for each salesperson while -1 is not entered */ while ( salesPerson != -1 ) { scanf( "%d%lf", &product, &value ); sales[ salesPerson ][ product ] = value; scanf( "%d", &salesPerson ); } /* end while */ /* display table */ printf( "\n%s\n%s\n%s\n%s\n%s\n", "The total sales for each salesperson", "are displayed at the end of each", "row, and the total sales for each", "product are displayed at the bottom ", "of each column.\n" ); printf( " %8d%8d%8d%8d%8d\n", 1, 2, 3, 4, 5 ); /* display salespeople and sales */ for ( i = 0; i <= 3; i++ ) { totalSales = 0.0; printf( "%d", i); /* add total sales and display individual sales */ for ( j = 0; j <= 4; j++ ) { totalSales += sales[ i][ j ]; printf( "%8.2f", sales[ i ][ j ] ); productSales[ j ] += sales[ i ][ j ]; } /* end for */ printf( "%8.2f\n", totalSales ); } /* end for */ printf( " " );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  194 C Arrays: Solutions  52 53 54 55 56 57 58 59  Chapter 6  /* display total product sales */ for ( j = 0; j <= 4; j++ ) { printf( "%8.2f", productSales[ j ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter the salesperson, product, and total sales. Enter -1 for the salesperon to end input. 0 0 1.00 0 1 2.00 0 2 3.00 0 3 4.00 0 4 5.00 1 0 1.00 1 1 2.00 1 2 3.00 1 3 4.00 1 4 5.00 2 0 1.00 2 1 2.00 2 2 3.00 2 3 4.00 2 4 5.00 3 0 1.00 3 1 2.00 3 2 3.00 3 3 4.00 3 4 5.00 -1 The total sales for each are displayed at the end row, and the total sales product are displayed at of each column. 0 1 2 3  1 1.00 1.00 1.00 1.00 4.00  2 2.00 2.00 2.00 2.00 8.00  3 3.00 3.00 3.00 3.00 12.00  salesperson of each for each the bottom 4 4.00 4.00 4.00 4.00 16.00  5 5.00 5.00 5.00 5.00 20.00  15.00 15.00 15.00 15.00  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 195  Chapter 6  6.23 (Turtle Graphics) The Logo language, which is particularly popular among personal computer users, made the concept of turtle graphics famous. Imagine a mechanical turtle that walks around the room under the control of a C program. The turtle holds a pen in one of two positions, up or down. While the pen is down, the turtle traces out shapes as it moves; while the pen is up, the turtle moves about freely without writing anything. In this problem you will simulate the operation of the turtle and create a computerized sketchpad as well. Use a 50-by-50 array floor which is initialized to zeros. Read commands from an array that contains them. Keep track of the current position of the turtle at all times and whether the pen is currently up or down. Assume that the turtle always starts at position 0,0 of the floor with its pen up. The set of turtle commands your program must process are shown in Fig. 6.24. Command  Meaning  1  Pen up Pen down Turn right Turn left Move forward 10 spaces (or a number other than 10) Print the 20-by-20 array End of data (sentinel)  2 3 4 5,10 6 9  Suppose that the turtle is somewhere near the center of the floor. The following "program" would draw and print a 12-by 12square: 2 5,12 3 5,12 3 5,12 3 5,12 1 6 9  As the turtle moves with the pen down, set the appropriate elements of array floor to 1s. When the 6 command (print) is given, wherever there is a 1 in the array, display an asterisk, or some other character you choose. Wherever there is a zero, display a blank. Write a program to implement the turtle graphics capabilities discussed here. Write several turtle graphics programs to draw interesting shapes. Add other commands to increase the power of your turtle graphics language. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  /* Exercise 6.23 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define TRUE 1 #define FALSE 0 #define MAX 100 /* the maximum number of commands */ /* function prototypes */ void getCommands( int commands[][ 2 ] ); int turnRight( int d ); int turnLeft( int d ); void movePen( int down, int a[][ 50 ], int dir, int dist ); void printArray( int a[][ 50 ] ); int main() { int floor[ 50 ][ 50 ] = { 0 }; int penDown = FALSE; int command;  /* floor grid */ /* pen down flag */  /* current command */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  196 C Arrays: Solutions  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 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  int direction = 0; /* direction indicator */ int commandArray[ MAX ][ 2 ] = { 0 }; /* array of commands */ int distance; /* distance to move */ int count = 0; /* command counter */ getCommands( commandArray ); command = commandArray[ count ][ 0 ]; /* continue receiving input while -9 is not entered */ while ( command != 9 ) { /* determine what command was entered and perform action */ switch ( command ) { case 1: penDown = FALSE; break; /* exit switch */ case 2: penDown = TRUE; break; /* exit switch */ case 3: direction = turnRight( direction ); break; /* exit switch */ case 4: direction = turnLeft( direction ); break; /* exit switch */ case 5: distance = commandArray[ count ][ 1 ]; movePen( penDown, floor, direction, distance ); break; /* exit switch */ case 6: printf( "\nThe drawing is:\n\n" ); printArray( floor ); break; /* exit switch */ } /* end switch */ command = commandArray[ ++count ][ 0 ]; } /* end while */ return 0; /* indicate successful termination */ } /* end main */ /* getCommands prompts user for commands */ void getCommands( int commands[][ 2 ] ) { int i; /* counter */ int tempCommand; /* temporary command holder */ printf( "Enter command ( 9 to end input ): " ); scanf( "%d", &tempCommand ); /* recieve commands until -9 or 100 commands are entered */ for ( i = 0; tempCommand != 9 && i < MAX; i++ ) { commands[ i ][ 0 ] = tempCommand; /* ignore comma after 5 is entered */ if ( tempCommand == 5 ) { scanf( ",%d", &commands[ i ][ 1 ] ); } /* end if */ printf( "Enter command ( 9 to end input ): " ); scanf( "%d", &tempCommand ); } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 197  Chapter 6  89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156  commands[ i ][ 0 ] = 9; /* last command */ } /* end function getCommands */ /* turnRight turns turtle to the right */ int turnRight( int d ) { return ++d > 3 ? 0 : d; } /* end function turnRight */ /* turnLeft turns turtle to the left */ int turnLeft( int d ) { return --d < 0 ? 3 : d; } /* end function turnLeft */ /* movePen moves the pen */ void movePen( int down, int a[][ 50 ], int dir, int dist ) { int i; /* loop counter */ int j; /* loop counter */ static int xPos = 0; /* x coordinate */ static int yPos = 0; /* y coordinate */ /* determine which way to move pen */ switch ( dir ) { case 0: /* move to the right */ /* move dist spaces or until edge of floor */ for ( j = 1; j <= dist && yPos + j < 50; j++ ) { /* draw 1 if pen is down */ if ( down ) { a[ xPos ][ yPos + j ] = 1; } /* end if */ } /* end for */ yPos += j - 1; break; /* exit switch */ case 1: /* move down */ /* move dist spaces or until edge of floor */ for ( i = 1; i <= dist && xPos + i < 50; i++ ) { /* draw 1 if pen is down */ if ( down ) { a[ xPos + i ][ yPos ] = 1; } /* end if */ } /* end for */ xPos += i - 1; break; /* exit switch */ case 2: /* move to the left */ /* move dist spaces or until edge of floor */ for ( j = 1; j <= dist && yPos - j >= 0; j++ ) { /* draw 1 if pen is down */ if ( down ) { a[ xPos ][ yPos - j ] = 1; } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  198 C Arrays: Solutions  157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198  Chapter 6  } /* end for */ yPos -= j - 1; break; /* exit switch */ case 3: /* move up */ /* move dist spaces or until edge of floor */ for ( i = 1; i <= dist && xPos - i >= 0; i++ ) { /* draw 1 if pen is down */ if ( down ) { a[ xPos - i ][ yPos ] = 1; } /* end if */ } /* end for */ xPos -= i - 1; break; /* exit switch */ } /* end switch */ } /* end function movePen */ /* printArray prints void printArray( int { int i; /* counter int j; /* counter  array drawing */ a[][ 50 ] ) */ */  /* loop through array */ for ( i = 0; i < 50; i++ ) { /* loop through array */ for ( j = 0; j < 50; j++ ) { putchar( a[ i ][ j ] ? '*' : ' ' ); } /* end for */ putchar( '\n' ); } /* end for */ } /* end function printArray */  Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter  command command command command command command command command command command command  ( ( ( ( ( ( ( ( ( ( (  9 9 9 9 9 9 9 9 9 9 9  to to to to to to to to to to to  end end end end end end end end end end end  input input input input input input input input input input input  ): ): ): ): ): ): ): ): ): ): ):  2 5,12 3 5,12 3 5,12 3 5,12 1 6 9  The drawing is: ************* * * * * * * * * * * * * * * * * * * * * * * *************  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 199  Chapter 6  6.24 (Knight's Tour) One of the more interesting puzzlers for chess buffs is the Knight's Tour problem, originally proposed by the mathematician Euler. The question is this: Can the chess piece called the knight move around an empty chessboard and touch each of the 64 squares once and only once? We study this intriguing problem in depth here. The knight makes L-shaped moves (over two in one direction and then over one in a perpendicular direction). Thus, from a square in the middle of an empty chessboard, the knight can make eight different moves (numbered 0 through 7) as shown in Fig. 6.25. a) Draw an 8-by-8 chessboard on a sheet of paper and attempt a Knight's Tour by hand. Put a 1 in the first square you move to, a 2 in the second square, a 3 in the third, etc. Before starting the tour, estimate how far you think you will get, remembering that a full tour consists of 64 moves. How far did you get? Were you close to the estimate? b) Now let us develop a program that will move the knight around a chessboard. The board itself is represented by an 8by-8 double-subscripted array board. Each of the squares is initialized to zero. We describe each of the eight possible moves in terms of both their horizontal and vertical components. For example, a move of type 0 as shown in Fig. 6.25 consists of moving two squares horizontally to the right and one square vertically upward. Move 2 consists of moving one square horizontally to the left and two squares vertically upward. Horizontal moves to the left and vertical moves upward are indicated with negative numbers. The eight moves may be described by two single-subscripted arrays, horizontal and vertical, as follows: 0  1  2  3  4  5  7  6  0 2  1 2  3  0  3 4 5  1  K 4  7 5  6  6 7  horizontal[ horizontal[ horizontal[ horizontal[ horizontal[ horizontal[ horizontal[ horizontal[  0 1 2 3 4 5 6 7  ] ] ] ] ] ] ] ]  = = = = = = = =  vertical[ vertical[ vertical[ vertical[ vertical[ vertical[ vertical[ vertical[  ] ] ] ] ] ] ] ]  = = = = = = = =  -1 -2 -2 -1 1 2 2 1  0 1 2 3 4 5 6 7  2 1 -1 -2 -2 -1 1 2  Let the variables currentRow and currentColumn indicate the row and column of the knight's current position on the board. To make a move of type moveNumber, where moveNumber is between 0 and 7, your program uses the statements  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  200 C Arrays: Solutions  Chapter 6  currentRow += vertical[ moveNumber ]; currentColumn += horizontal[ moveNumber ];  Keep a counter that varies from 1 to 64. Record the latest count in each square the knight moves to. Remember to test each potential move to see if the knight has already visited that square. And, of course, test every potential move to make sure that the knight does not land off the chessboard. Now write a program to move the knight around the chessboard. Run the program. How many moves did the knight make? c) After attempting to write and run a Knight's Tour program, you have probably developed some valuable insights. We will use these to develop a heuristic (or strategy) for moving the knight. Heuristics do not guarantee success, but a carefully developed heuristic greatly improves the chance of success. You may have observed that the outer squares are in some sense more troublesome than the squares nearer the center of the board. In fact, the most troublesome, or inaccessible, squares are the four corners. Intuition may suggest that you should attempt to move the knight to the most troublesome squares first and leave open those that are easiest to get to so that when the board gets congested near the end of the tour there will be a greater chance of success. We may develop an "accessibility heuristic" by classifying each of the squares according to how accessible they are and always moving the knight to the square (within the knight's L-shaped moves, of course) that is most inaccessible. We label a double-subscripted array accessibility with numbers indicating from how many squares each particular square is accessible. On a blank chessboard, the center squares are therefore rated as 8s, the corner squares are rated as 2s, and the other squares have accessibility numbers of 3, 4, or 6 as follows: 2 3 4 4 4 4 3 2  3 4 6 6 6 6 4 3  4 6 8 8 8 8 6 4  4 6 8 8 8 8 6 4  4 6 8 8 8 8 6 4  4 6 8 8 8 8 6 4  3 4 6 6 6 6 4 3  2 3 4 4 4 4 3 2  Now write a version of the Knight's Tour program using the accessibility heuristic. At any time, the knight should move to the square with the lowest accessibility number. In case of a tie, the knight may move to any of the tied squares. Therefore, the tour may begin in any of the four corners. [Note: As the knight moves around the chessboard, your program should reduce the accessibility numbers as more and more squares become occupied. In this way, at any given time during the tour, each available square's accessibility number will remain equal to precisely the number of squares from which that square may be reached.] Run this version of your program. Did you get a full tour? Now modify the program to run 64 tours, one from each square of the chessboard. How many full tours did you get? d) Write a version of the Knight's Tour program which, when encountering a tie between two or more squares, decides what square to choose by looking ahead to those squares reachable from the "tied" squares. Your program should move to the square for which the next move would arrive at a square with the lowest accessibility number. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  /* Exercise 6.24 Part C Solution */ /* Knight's Tour - access version */ /* runs one tour */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define TRUE 1 #define FALSE 0 /* function prototypes */ void clearBoard( int workBoard[][ 8 ] ); void printBoard( int workBoard[][ 8 ] ); int validMove( int row, int column, int workBoard[][ 8 ] ); int main() { int board[ 8 ][ 8 ]; /* chess board */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 201  Chapter 6  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 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  /* array of accesibility */ int access[ 8 ][ 8 ] = { 2, 3, 4, 4, 4, 4, 3, 2, /* eight horizontal int horizontal[ 8 ] int vertical[ 8 ] = int currentRow; int currentColumn; int moveNumber = 0; int testRow; int testColumn; int minRow; int minColumn; int minAccess = 9; int accessNumber; int moveType; int done;  3, 4, 6, 6, 6, 6, 4, 3,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  3, 4, 6, 6, 6, 6, 4, 3,  2, 3, 4, 4, 4, 4, 3, 2 };  and vertical moves for the knight */ = { 2, 1, -1, -2, -2, -1, 1, 2 }; { -1, -2, -2, -1, 1, 2, 2, 1 }; /* current row */ /* current column */ /* move counter */ /* possible next row */ /* possible next column */ /* row with minimum access number */ /* column with minimum access number */ /* impossible access number */ /* current access number */ /* current move type */ /* flag to indicate end */  srand( time( NULL ) ); clearBoard( board ); /* initialize array board */ currentRow = rand() % 8; currentColumn = rand() % 8; board[ currentRow ][ currentColumn ] = ++moveNumber; done = FALSE; /* continue while knight still has valid moves */ while ( !done ) { accessNumber = minAccess; /* loop through all move types */ for ( moveType = 0; moveType < 8; moveType++ ) { testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; /* make sure move is valid */ if ( validMove( testRow, testColumn, board ) ) { /* if move is valid and has lowest accessNumber, set square to accessNumber */ if ( access[ testRow ][ testColumn ] < accessNumber ) { accessNumber = access[ testRow ][ testColumn ]; minRow = testRow; minColumn = testColumn; } /* end if */ --access[ testRow ][ testColumn ]; } /* end if */ } /* end for */ /* end if knight has no moves */ if ( accessNumber == minAccess ) { done = TRUE; } /* end if */ else { currentRow = minRow; currentColumn = minColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  202 C Arrays: Solutions  88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155  Chapter 6  } /* end while */ printf( "The tour ended with %d moves.\n", moveNumber ); /* determine and print if a full tour was made */ if ( moveNumber == 64 ) { printf( "This was a full tour!\n\n" ); } /* end if */ else { printf( "This was not a full tour.\n\n" ); } /* end else */ printf( "The board for this test is:\n\n" ); printBoard( board ); return 0; /* indicate successful termination */ } /* end main */ /* function to clear chess board */ void clearBoard( int workBoard[][ 8 ] ) { int row; /* row counter */ int col; /* column counter */ /* set all squares to zero */ for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++ ) { workBoard[ row ][ col ] = 0; } /* end for */ } /* end for */ } /* end function clearBoard */ /* function to print chess board */ void printBoard( int workBoard[][ 8 ] ) { int row; /* row counter */ int col; /* column counter */ printf( "  0  1  2  3  4  5  6  7\n" );  /* print squares */ for ( row = 0; row < 8; row++ ) { printf( "%d", row ); for ( col = 0; col < 8; col++ ) { printf( "%3d", workBoard[ row ][ col ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\n" ); } /* end function printBoard */ /* function to determine if move is legal */ int validMove( int row, int column, int workBoard[][ 8 ] ) { /* NOTE: This test stops as soon as it becomes false */ return ( row >= 0 && row <= 7 && column >= 0 && column <= 7 && workBoard[ row ][ column ] == 0 ); } /* end function validMove */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 203  Chapter 6  The tour ended with 64 moves. This was a full tour! The board for this test is: 0 1 2 3 4 5 6 7  0 33 20 31 6 35 10 61 8  1 30 5 34 21 60 7 52 11  2 19 32 49 36 51 62 9 64  3 4 29 22 59 48 57 12 53  4 23 18 37 50 39 54 63 56  5 28 3 26 47 58 45 42 13  6 17 24 1 38 15 40 55 44  7 2 27 16 25 46 43 14 41  6.25 (Knight's Tour: Brute Force Approaches) In Exercise 6.24 we developed a solution to the Knight's Tour problem. The approach used, called the "accessibility heuristic," generates many solutions and executes efficiently. As computers continue increasing in power, we will be able to solve many problems with sheer computer power and relatively unsophisticated algorithms. Let us call this approach "brute force" problem solving. a) Use random number generation to enable the knight to walk around the chess board (in its legitimate L-shaped moves, of course) at random. Your program should run one tour and print the final chessboard. How far did the knight get? 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  /* Exercise 6.25 Part A Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define NO 0 #define YES 1 /* function prototypes */ int validMove( int row, int column, int workBoard[][ 8 ] ); void printBoard( int board[][ 8 ] ); int main() { int currentRow; int currentColumn; int moveType; int moveNumber = 0; int testRow; int testColumn; int count; int done; int goodMove; /* horizontal and int horizontal[ 8 int vertical[ 8 ] int board[ 8 ][ 8  /* /* /* /* /* /* /* /* /*  current row */ current column */ current move type */ move counter */ possible next row */ possible next column */ counter */ flag to indicate end */ result of call to validMove */  vertical moves for the knight, and board */ ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; = { -1, -2, -2, -1, 1, 2, 2, 1 }; ] = { 0 };  srand( time( NULL ) ); currentRow = rand() % 8; currentColumn = rand() % 8; board[ currentRow ][ currentColumn ] = ++moveNumber; done = NO; /* continue while knight can still move */ while ( !done ) { moveType = rand() % 8; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ];  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  204 C Arrays: Solutions  42 43 44 45 46 47 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108  goodMove = validMove( testRow, testColumn, board ); /* test if desired move is valid */ if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; } /* end if */ else { /* if move is not legal try another random move */ for ( count = 0; count < 7 && !goodMove; count++ ) { moveType = ++moveType % 8; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; goodMove = validMove( testRow, testColumn, board ); /* test if new move is good */ if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; } /* end if */ } /* end for */ /* if no valid moves, knight can no longer move */ if ( !goodMove ) { done = YES; } /* end if */ } /* end else */ /* if 64 moves have been made, a full tour is complete */ if ( moveNumber == 64 ) { done = YES; } /* end if */ } /* end while */ printf( "The tour has ended with %d moves.\n", moveNumber ); /* test if full tour was made */ if ( moveNumber == 64 ) { printf( "This was a full tour!\n" ); } /* end if */ else { printf( "This was not a full tour.\n" ); } /* end else */ printf( "The board for this random test was:\n\n" ); printBoard( board ); /* print the board */ return 0; /* indicate successful termination */ } /* end main */ /* function to test whether a square is on the board and has not been visited yet */ int validMove( int row, int column, int workBoard[][ 8 ] ) { /* NOTE: This test stops as soon as it becomes false */ return ( row >= 0 && row < 8 && column >= 0 && column < 8 && workBoard[ row ][ column ] == 0 ); } /* end function validMove */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 205  Chapter 6  109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130  /* function to print the chess board */ void printBoard( int board[][ 8 ] ) { int row; /* row counter */ int col; /* column counter */ printf( "  0  1  2  3  4  5  6  7\n" );  /* print the rows and columns of the chess board */ for ( row = 0; row < 8; row++ ) { printf( "%d", row ); for ( col = 0; col < 8; col++ ) { printf( "%3d", board[ row ][ col ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\n" ); } /* end function printBoard */  The tour has ended with 32 moves. This was not a full tour. The board for this random test was: 0 1 2 3 4 5 6 7  0 1 2 3 4 5 6 7 13 0 0 0 11 28 0 32 0 0 12 29 24 31 8 0 0 14 0 0 27 10 25 6 18 0 16 23 30 7 0 9 15 0 19 0 0 26 5 0 20 17 0 0 22 0 2 0 0 0 21 0 0 0 0 4 0 0 0 0 0 3 0 1  b) Most likely, the preceding program produced a relatively short tour. Now modify your program to attempt 1000 tours. Use a single-subscripted array to keep track of the number of tours of each length. When your program finishes attempting the 1000 tours, it should print this information in neat tabular format. What was the best result? ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  /* Exercise 6.25 Part B Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define NO 0 #define YES 1 int validMove( int, int, int [][ 8 ] ); int main() { int currentRow; int currentColumn; int moveType; int moveNumber; int testRow; int testColumn; int count; int i; int row; int col;  /* /* /* /* /* /* /* /* /*  current row */ current column */ current move type */ move counter */ possible next row */ possible next column */ counter */ counter */ row */  /* column */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  206 C Arrays: Solutions  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 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  Chapter 6  int done; /* flag to indicate end */ int goodMove; /* result of call to validMove */ int board[ 8 ][ 8 ]; /* chess board */ int moveTotal[ 65 ] = { 0 }; /* array of tour totals */ /* horizontal and vertical moves for the knight */ int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; srand( time( NULL ) ); /* attempt 1000 tours */ for ( i = 0; i < 1000; i++ ) { /* set all squares equal to 0 */ for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++ ) { board[ row ][ col ] = 0; } /* end for */ } /* end for */ moveNumber = 0; currentRow = rand() % 8; currentColumn = rand() % 8; board[ currentRow ][ currentColumn ] = ++moveNumber; done = NO; /* continue while knight still has valid moves */ while ( !done ) { moveType = rand() % 8; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; goodMove = validMove( testRow, testColumn, board ); /* if desired move is valid, move knight to square */ if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; } /* end if */ else { /* if move is invalid, test other possible moves */ for ( count = 0; count < 7 && !goodMove; count++ ) { moveType = ++moveType % 8; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; goodMove = validMove( testRow, testColumn, board ); /* if move is valid, move knight to square */ if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; } /* end if */ } /* end for */ /* if no valid moves, while loop exits */ if ( !goodMove ) { done = YES; } /* end if */ } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 207  Chapter 6  91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130  /* if full tour is made, while loop exits */ if ( moveNumber == 64 ) { done = YES; } /* end if */ } /* end while */ ++moveTotal[ moveNumber ]; } /* end for */ /* dislay how many tours of each move number were made */ for ( i = 1; i < 65; i++ ) { if ( moveTotal[ i ] ) { printf( "There were %d tours of %d moves.\n", moveTotal[ i ], i ); } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* function to determine if a move is legal */ int validMove( int testRow, int testColumn, int board[][ 8 ] ) { /* test if square is on board and if knight has previously visited it */ if ( testRow >= 0 && testRow < 8 && testColumn >= 0 && testColumn < 8 ) { return board[ testRow ][ testColumn ] != 0 ? NO : YES; } /* end if */ else { return NO; } /* end else */ } /* end function validMove */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  208 C Arrays: Solutions  There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There There  were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were were  Chapter 6  1 tours of 4 moves. 3 tours of 5 moves. 2 tours of 6 moves. 3 tours of 7 moves. 2 tours of 8 moves. 4 tours of 10 moves. 5 tours of 11 moves. 4 tours of 12 moves. 5 tours of 13 moves. 7 tours of 14 moves. 7 tours of 15 moves. 9 tours of 16 moves. 8 tours of 17 moves. 10 tours of 18 moves. 9 tours of 19 moves. 9 tours of 20 moves. 11 tours of 21 moves. 19 tours of 22 moves. 17 tours of 23 moves. 18 tours of 24 moves. 12 tours of 25 moves. 20 tours of 26 moves. 14 tours of 27 moves. 18 tours of 28 moves. 22 tours of 29 moves. 21 tours of 30 moves. 31 tours of 31 moves. 28 tours of 32 moves. 25 tours of 33 moves. 32 tours of 34 moves. 26 tours of 35 moves. 40 tours of 36 moves. 38 tours of 37 moves. 38 tours of 38 moves. 37 tours of 39 moves. 33 tours of 40 moves. 35 tours of 41 moves. 34 tours of 42 moves. 33 tours of 43 moves. 36 tours of 44 moves. 30 tours of 45 moves. 35 tours of 46 moves. 26 tours of 47 moves. 37 tours of 48 moves. 22 tours of 49 moves. 17 tours of 50 moves. 20 tours of 51 moves. 21 tours of 52 moves. 17 tours of 53 moves. 19 tours of 54 moves. 14 tours of 55 moves. 3 tours of 56 moves. 7 tours of 57 moves. 3 tours of 59 moves. 3 tours of 60 moves.  c) Most likely, the preceding program gave you some "respectable" tours but no full tours. Now "pull all the stops out" and simply let your program run until it produces a full tour. [Caution: This version of the program could run for hours on a powerful computer.] Once again, keep a table of the number of tours of each length and print this table when the first full tour is found. How many tours did your program attempt before producing a full tour? How much time did it take? d) Compare the brute force version of the Knight's Tour with the accessibility heuristic version. Which required a more careful study of the problem? Which algorithm was more difficult to develop? Which required more computer power? Could we be certain (in advance) of obtaining a full tour with the accessibility heuristic approach? Could we be certain (in advance) of obtaining a full tour with the brute force approach? Argue the pros and cons of brute force problem solving in general.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 209  Chapter 6  6.26 (Eight Queens) Another puzzler for chess buffs is the Eight Queens problem. Simply stated: Is it possible to place eight queens on an empty chessboard so that no queen is "attacking" any other—that is, so that no two queens are in the same row, the same column, or along the same diagonal? Use the kind of thinking developed in Exercise 6.24 to formulate a heuristic for solving the Eight Queens problem. Run your program. [Hint: It is possible to assign a numeric value to each square of the chessboard indicating how many squares of an empty chessboard are "eliminated" once a queen is placed in that square. For example, each of the four corners would be assigned the value 22, as in Fig. Fig. 6.26.]  * * * * * * * * * * * * * * * * * * * * * *  Fig. 6.26 The 22 squares eliminated by placing a queen in the upper-left corner. Once these "elimination numbers" are placed in all 64 squares, an appropriate heuristic might be: Place the next queen in the square with the smallest elimination number. Why is this strategy intuitively appealing? 6.27 (Eight Queens: Brute Force Approaches) In this problem you will develop several brute force approaches to solving the Eight Queens problem introduced in Exercise 6.26. a) Solve the Eight Queens problem, using the random brute force technique developed in Exercise 6.25. b) Use an exhaustive technique (i.e., try all possible combinations of eight queens on the chessboard). c) Why do you suppose the exhaustive brute force approach may not be appropriate for solving the Knight's Tour problem? d) Compare and contrast the random brute force and exhaustive brute force approaches in general.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  210 C Arrays: Solutions  Chapter 6  6.28 (Duplicate elimination) In Chapter 12, we explore the high-speed binary search tree data structure. One feature of a binary search tree is that duplicate values are discarded when insertions are made into the tree. This is referred to as duplicate elimination. Write a program that produces 20 random numbers between 1 and 20. The program should store all nonduplicate values in an array. Use the smallest possible array to accomplish this task. 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  /* Exercise 6.28 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define SIZE 20 int main() { int loop; int randNumber; int loop2; int subscript = 0; int duplicate; int array[ SIZE ] = { 0 };  /* /* /* /* /* /*  loop counter */ current random number */ loop counter */ array subscript counter */ duplicate flag */ array of random numbers */  srand( time( NULL ) ); /* loop 20 times */ for ( loop = 0; loop <= SIZE - 1; loop++ ) { duplicate = 0; randNumber = 1 + rand() % 20; /* generate random number */ /* loop through current numbers in array */ for ( loop2 = 0; loop2 <= subscript; loop2++ ) { /* compare randNumber with previous numbers */ if ( randNumber == array[ loop2 ] ) { duplicate = 1; break; } /* end if */ } /* end for */ /* if not a duplicate */ if ( !duplicate ) { array[ subscript++ ] = randNumber; } /* end if */ } /* end while */ printf( "Non-repetitive array values are:\n" ); /* display array */ for ( loop = 0; array[ loop ] != 0; loop++ ) { printf( "\t\t\t\tArray[ %d ] = %d\n", loop, array[ loop ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 211  Chapter 6  Non-repetitive array values are: Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[ Array[  0 ] = 11 1 ] = 17 2 ] = 3 3 ] = 18 4 ] = 9 5 ] = 2 6 ] = 20 7 ] = 4 8 ] = 1 9 ] = 10 10 ] = 7 11 ] = 13 12 ] = 19 13 ] = 6 14 ] = 8 15 ] = 16  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  212 C Arrays: Solutions  Chapter 6  6.29 (Knight's Tour: Closed Tour Test) In the Knight's Tour, a full tour is when the knight makes 64 moves touching each square of the chess board once and only once. A closed tour occurs when the 64th move is one move away from the location in which the knight started the tour. Modify the Knight's Tour program you wrote in Exercise 6.24 to test for a closed tour if a full tour has occurred. 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 53 54 55 56 57 58 59 60 61  /* Exercise 6.29 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define TRUE 1 #define FALSE 0 /* function prototypes */ void clearBoard( int workBoard[][ 8 ] ); void printBoard( int workBoard[][ 8 ] ); int validMove( int row, int column, int workBoard[][ 8 ] ); int main( void ) { int int int int int int int int int int int int int int int  firstMoveRow; firstMoveCol; closedTour = 0; currentRow; currentColumn; moveNumber = 0; testRow; testColumn; minRow; minColumn; minAccess = 9; accessNumber; moveType; done; board[ 8 ][ 8 ];  /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*  starting row */ starting column */ closed tour flag */ current row */ current column */ move counter */ possible next row */ possible next column */ minimum row access number */ minimum column access number */ access number reset */ current access number */ current move type */ flag to indicate end */ chess board */  /* horizontal and vertical moves for the knight */ int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; /* access grid */ int access[ 8 ][ 8 ] = { 2, 3, 4, 4, 4, 4, 3, 2,  3, 4, 6, 6, 6, 6, 4, 3,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  4, 6, 8, 8, 8, 8, 6, 4,  3, 4, 6, 6, 6, 6, 4, 3,  2, 3, 4, 4, 4, 4, 3, 2 };  srand( time( NULL ) ); clearBoard( board ); /* initialize array board */ currentRow = rand() % 8; currentColumn = rand() % 8; firstMoveRow = currentRow; /* store first moves row */ firstMoveCol = currentColumn; /* store first moves col */ board[ currentRow ][ currentColumn ] = ++moveNumber; done = FALSE; /* loop while knight can still move */ while ( !done ) { accessNumber = minAccess; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 213  Chapter 6  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129  /* test what moves knight can make */ for ( moveType = 0; moveType < 8; moveType++ ) { testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; /* if the knight can make a valid move */ if ( validMove( testRow, testColumn, board ) ) { /* if move has lowest accessNumber, move to that space */ if ( access[ testRow ][ testColumn ] < accessNumber ) { accessNumber = access[ testRow ][ testColumn ]; minRow = testRow; minColumn = testColumn; } /* end if */ --access[ testRow ][ testColumn ]; } /* end if */ } /* end for */ /* if knight cannot access any more squares, loop terminates */ if ( accessNumber == minAccess ) { done = TRUE; } /* end if */ else { currentRow = minRow; currentColumn = minColumn; board[ currentRow ][ currentColumn ] = ++moveNumber; /* check for closed tour */ if ( moveNumber == 64 ) { /* loop through possible next moves */ for ( moveType = 0; moveType < 8; moveType++ ) { testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; /* test if knight is one move away from start */ if ( testRow == firstMoveRow && testColumn == firstMoveCol ) { closedTour = 1; } /* end if */ } /* end for */ } /* end if */ } /* end else */ } /* end while */ printf( "The tour ended with %d moves.\n", moveNumber ); /* display results of tour */ if ( moveNumber == 64 && closedTour == 1 ) { printf( "This was a closed tour!\n\n" ); } /* end if */ else if ( moveNumber == 64 ) { printf( "This was a full tour!\n\n" ); } /* end else if */ else { printf( "This was not a full tour.\n\n" ); } /* end else */ printf( "The board for this test is:\n\n" ); printBoard( board );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  214 C Arrays: Solutions  130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182  Chapter 6  return 0; /* indicate successful termination */ } /* end main */ /* function to clear the chess board */ void clearBoard( int workBoard[][ 8 ] ) { int row; /* row counter */ int col; /* col counter */ /* set all values on board to 0 */ for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++ ) { workBoard[ row ][ col ] = 0; } /* end for */ } /* end for */ } /* end function clearBoard */ /* function to print the chesboard */ void printBoard( int workBoard[][ 8 ] ) { int row; /* row counter */ int col; /* column counter */ printf( "  0  1  2  3  4  5  6  7\n" );  /* print rows of chessboard */ for ( row = 0; row < 8; row++ ) { printf( "%d", row ); /* print columns of chess board */ for ( col = 0; col < 8; col++ ) { printf( "%3d", workBoard[ row ][ col ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\n" ); } /* end function printBoard */ /* function to determine if a move is valid */ int validMove( int row, int column, int workBoard[][ 8 ] ) { /* NOTE: This test stops as soon as it becomes false */ return ( row >= 0 && row < 8 && column >= 0 && column < 8 && workBoard[ row ][ column ] == 0 ); } /* end function validMove */  The tour ended with 64 moves. This was a full tour! The board for this test is: 0 1 2 3 4 5 6 7  0 32 35 12 59 54 37 10 63  1 13 58 33 36 11 62 51 38  2 34 31 60 55 50 53 64 9  3 57 14 49 46 61 26 39 52  4 30 47 56 25 40 45 8 23  5 15 18 41 48 27 24 5 2  6 42 29 20 17 44 3 22 7  7 19 16 43 28 21 6 1 4  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 215  Chapter 6  6.30 (The Sieve of Eratosthenes) A prime integer is any integer that can be divided evenly only by itself and 1. The Sieve of Eratosthenes is a method of finding prime numbers. It works as follows: 1) Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will remain 1. All other array elements will eventually be set to zero. 2) Starting with array subscript 2 (subscript 1 must be prime), every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all elements beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.). For array subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.). When this process is complete, the array elements that are still set to one indicate that the subscript is a prime number. These subscripts can then be printed. Write a program that uses an array of 1000 elements to determine and print the prime numbers between 1 and 999. Ignore element 0 of the array. 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  /* Exercise 6.30 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define SIZE 1000 int main() { int array[ SIZE ]; /* array to indicate prime numbers */ int loop; /* loop counter */ int loop2; /* loop counter */ int count = 0; /* total prime numbers */ /* set all array elements to 1 */ for ( loop = 0; loop < SIZE; loop++ ) { array[ loop ] = 1; } /* end for */ /* test for multiples of current subscript */ for ( loop = 1; loop < SIZE; loop++ ) { /* start with array subscript two */ if ( array[ loop ] == 1 && loop != 1 ) { /* loop through remainder of array */ for ( loop2 = loop; loop2 <= SIZE; loop2++ ) { /* set to zero all multiples of loop */ if ( loop2 % loop == 0 && loop2 != loop ) { array[ loop2 ] = 0; } /* end if */ } /* end for */ } /* end if */ } /* end for */ /* display prime numbers in the range 2 - 197 */ for ( loop = 2; loop < SIZE; loop++ ) { if ( array[ loop ] == 1 ) { printf( "%3d is a prime number.\n", loop ); ++count; } /* end if */ } /* end for */ printf( "A total of %d prime numbers were found.\n", count ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  216 C Arrays: Solutions  2 3 5 7 11 13 17 19  is is is is is is is is  a a a a a a a a  prime prime prime prime prime prime prime prime  . . . 971 is a prime 977 is a prime 983 is a prime 991 is a prime 997 is a prime A total of 168  Chapter 6  number. number. number. number. number. number. number. number.  number. number. number. number. number. prime numbers were found.  6.31 (Bucket Sort) A bucket sort begins with an single-subscripted array of positive integers to be sorted, and a double-subscripted array of integers with rows subscripted from 0 to 9 and columns subscripted from 0 to n - 1 where n is the number of values in the array to be sorted. Each row of the double-subscripted array is referred to as a bucket. Write a function bucketSort that takes an integer array and the array size as arguments. The algorithm is as follows: 1) Loop through the single-subscripted array and place each of its values in a row of the bucket array based on its ones digit. For example, 97 is placed in row 7, 3 is placed in row 3 and 100 is placed in row 0. 2) Loop through the bucket array and copy the values back to the original array. The new order of the above values in the single-subscripted array is 100, 3 and 97. 3) Repeat this process for each subsequent digit position (tens, hundreds, thousands, etc.) and stop when the leftmost digit of the largest number has be processed. On the second pass of the array, 100 is placed in row 0, 3 is placed in row 0 (it had only one digit) and 97 is placed in row 9. The order of the values in the single-subscripted array is 100, 3 and 97. On the third pass, 100 is placed in row 1, 3 is placed in row zero and 97 is placed in row zero (after 3). The bucket sort is guaranteed to have all the values properly sorted after processing the leftmost digit of the largest number. The bucket sort knows it is done when all the values are copied into row zero of the double-subscripted array. Note that the double-subscripted array of buckets is ten times the size of the integer array being sorted. This sorting technique provides better performance than a bubble sort, but requires much larger storage capacity. Bubble sort requires only one additional memory location for the type of data being sorted. Bucket sort is an example of a space-time trade-off. It uses more memory, but performs better. This version of the bucket sort requires copying all the data back to the original array on each pass. Another possibility is to create a second double-subscripted bucket array and repeatedly move the data between the two bucket arrays until all the data is copied into row zero of one of the arrays. Row zero then contains the sorted array. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  /* Exercise 6.31 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* symbolic constant SIZE must be defined as the array size for bucketSort to work */ #define SIZE 12 /* function prototypes */ void bucketSort( int a[] ); void distributeElements( int a[], int buckets[][ SIZE ], int digit ); void collectElements( int a[], int buckets[][ SIZE ] ); int numberOfDigits( int b[], int arraySize ); void zeroBucket( int buckets[][ SIZE ] ); int main() { /* array to be sorted */ int array[ SIZE ] = { 19, 13, 5, 27, 1, 26, 31, 16, 2, 9, 11, 21 }; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 217  Chapter 6  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 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  int i; /* loop counter */ printf( "Array elements in original order:\n" ); /* display the unsorted array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", array[ i ] ); } /* end for */ putchar( '\n' ); bucketSort( array ); /* sort the array */ printf( "\nArray elements in sorted order:\n" ); /* display sorted array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", array[ i ] ); } /* end for */ putchar( '\n' ); return 0; /* indicate successful termination */ } /* end main */ /* Perform the bucket sort algorithm void bucketSort( int a[] ) { int totalDigits; int i; int bucket[ 10 ][ SIZE ] = { 0 };  */ /* largest # of digits in array */ /* loop counter */ /* initialize bucket array */  totalDigits = numberOfDigits( a, SIZE ); /* put elements in buckets for sorting one sorted, get elements from buckets */ for ( i = 1; i <= totalDigits; i++ ) { distributeElements( a, bucket, i ); collectElements( a, bucket ); /* set all bucket contents to zero */ if ( i != totalDigits ) { zeroBucket( bucket ); } /* end if */ } /* end for */ } /* end function bucketSort */ /* Determine the number of digits in the largest number */ int numberOfDigits( int b[], int arraySize ) { int largest = b[ 0 ]; /* assume first element is largest */ int i; /* loop counter */ int digits = 0; /* total number of digits */ /* find largest array element */ for ( i = 1; i < arraySize; i++ ) { if ( b[ i ] > largest ) { largest = b[ i ]; } /* end if */ } /* end for */ /* find number of digits of largest element */ while ( largest != 0 ) { ++digits;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  218 C Arrays: Solutions  88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154  Chapter 6  largest /= 10; } /* end while */ return digits; /* return number of digits */ } /* end function numberOfDigits */ /* Distribute elements into buckets based on specified digit */ void distributeElements( int a[], int buckets[][ SIZE ], int digit ) { int divisor = 10; /* used to get specific digit */ int i; /* loop counter */ int bucketNumber; /* current bucket number */ int elementNumber; /* current element number */ /* determine the divisor */ for ( i = 1; i < digit; i++ ) { divisor *= 10; } /* end for */ /* bucketNumber example for hundreds digit: */ /* ( 1234 % 1000 - 1234 % 100 ) / 100 --> 2 */ for ( i = 0; i < SIZE; i++ ) { bucketNumber = ( a[ i ] % divisor - a[ i ] % ( divisor / 10 ) ) / ( divisor / 10 ); /* retrieve value in buckets[ bucketNumber ][ 0 ] to determine */ /* which element of the row to store a[ i ] in. */ elementNumber = ++buckets[ bucketNumber ][ 0 ]; buckets[ bucketNumber ][ elementNumber ] = a[ i ]; } /* end for */ } /* end function distributeElements */ /* Return elements to void collectElements( { int i; int j; int subscript = 0;  original array */ int a[], int buckets[][ SIZE ] ) /* loop counter */ /* loop counter */ /* current subscript */  /* retrieve elements from buckets */ for ( i = 0; i < 10; i++ ) { for ( j = 1; j <= buckets[ i ][ 0 ]; j++ ) { a[ subscript++ ] = buckets[ i ][ j ]; } /* end for */ } /* end for */ } /* end function collectElements */ /* Set all buckets to zero */ void zeroBucket( int buckets[][ SIZE ] ) { int i; /* loop counter */ int j; /* loop counter */ for ( i = 0; i < 10; i++ ) { for ( j = 0; j < SIZE; j++ ) { buckets[ i ][ j ] = 0; } /* end for */ } /* end for */ } /* end function zeroBucket */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 219  Chapter 6  Array elements in original order: 19 13 5 27 1 26 31 16 2 9 11 21 Array elements in sorted order: 1 2 5 9 11 13 16 19 21 26 27 31  RECURSION EXERCISES 6.32 (Selection Sort) A selection sort searches an array looking for the smallest element in the array. When the smallest element is found, it is swapped with the first element of the array. The process is then repeated for the subarray beginning with the second element of the array. Each pass of the array results in one element being placed in its proper location. This sort requires similar processing capabilities to the bubble sort—for an array of n elements, n – 1 passes must be made, and for each subarray, n – 1 comparisons must be made to find the smallest value. When the subarray being processed contains one element, the array is sorted. Write a recursive function selectionSort to perform this algorithm. 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  /* Exercise 6.32 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #define MAXRANGE 1000 #define SIZE 10 void selectionSort( int array[], int size ); /* function prototype */ int main() { int sortThisArray[ SIZE ] = { 0 }; /* array to be sorted */ int loop; /* loop counter */ srand( time( NULL ) ); /* seed random number generator */ /* fill array with random numbers between 1-1000 */ for ( loop = 0; loop < SIZE; loop++ ) { sortThisArray[ loop ] = 1 + rand() % MAXRANGE; } /* end for */ printf( "\nUnsorted array is:\n" ); /* display unsorted array */ for ( loop = 0; loop < SIZE; loop++ ) { printf( " %d ", sortThisArray[ loop ] ); } /* end for */ selectionSort( sortThisArray, SIZE ); /* sort array */ printf( "\n\nSorted array is:\n" ); /* display sorted array */ for ( loop = 0; loop < SIZE; loop++ ) { printf( " %d ", sortThisArray[ loop ] ); } /* end for */ printf( "\n\n" ); return 0; /* indicate successful termination */ } /* end main */ /* function to sort an array */ void selectionSort( int array[], int size ) { int temp; /* temporary variable used for swapping */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  220 C Arrays: Solutions  49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70  Chapter 6  int loop; /* loop counter */ /* sort array until only one element is left */ if ( size >= 1 ) { /* find smallest element and put it in first position */ for ( loop = 0; loop <= size - 1; loop++ ) { /* swap elements */ if ( array[ loop ] < array[ 0 ] ) { temp = array[ loop ]; array[ loop ] = array[ 0 ]; array[ 0 ] = temp; } /* end if */ } /* end for */ /* recursive call to selectionSort */ selectionSort( &array[ 1 ], size - 1 ); } /* end for */ } /* end function selectionSort */  Unsorted array is: 629 748 87 955 Sorted array is: 11 87 287 377  484 484  505 505  799 629  377 748  11  287  799  955  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 221  Chapter 6  6.33 (Palindromes) A palindrome is a string that is spelled the same way forwards and backwards. Some examples of palindromes are: "radar," "able was i ere i saw elba," and, if you ignore blanks, "a man a plan a canal panama." Write a recursive function testPalindrome that returns 1 if the string stored in the array is a palindrome and 0 otherwise. The function should ignore spaces and punctuation in the string. 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 53 54 55 56 57 58 59 60 61 62  /* Exercise 6.33 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define SIZE 80 /* function prototype */ int testPalindrome( char array[], int left, int right ); int main() { char c; char string[ SIZE ]; char copy[ SIZE ]; int count = 0; int copyCount; int i;  /* /* /* /* /* /*  temporarily holds keyboard input */ original string */ copy of string without spaces */ length of string */ length of copy */ counter */  printf( "Enter a sentence:\n" ); /* get sentence to test from user */ while ( ( c = getchar() ) != '\n' && count < SIZE ) { string[ count++ ] = c; } /* end while */ string[ count ] = '\0'; /* terminate string */ /* make a copy of string without spaces */ for ( copyCount = 0, i = 0; string[ i ] != '\0'; i++ ) { if ( string[ i ] != ' ' ) { copy[ copyCount++ ] = string[ i ]; } /* end if */ } /* end for */ /* print whether or not the sentence is a palindrome */ if ( testPalindrome( copy, 0, copyCount - 1 ) ) { printf( "\"%s\" is a palindrome\n", string ); } /* end if */ else { printf( "\"%s\" is not a palindrome\n", string ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* function to see if the sentence is a palindrome */ int testPalindrome( char array[], int left, int right ) { /* test array to see if a palindrome */ if ( left == right || left > right ) { return 1; } /* end if */ else if ( array[ left ] != array[ right ] ) { return 0; } /* end else if */ else { return testPalindrome( array, left + 1, right - 1 ); } /* end else */ } /* end function testPalindrome */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  222 C Arrays: Solutions  Enter a sentence: able was i ere i saw elba "able was i ere i saw elba" is a palindrome  Enter a sentence: hi there "hi there" is not a palindrome  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 223  Chapter 6  6.34 (Linear Search) Modify the program of Fig. 6.18 to use a recursive linearSearch function to perform the linear search of the array. The function should receive an integer array and the size of the array as arguments. If the search key is found, return the array subscript; otherwise, return –1. 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 53 54  /* Exercise 6.34 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define SIZE 100 /* function prototypes */ int linearSearch( int array[], int key, int low, int high ); int main() { int array[ SIZE ]; /* array to be searched */ int loop; /* loop counter */ int searchKey; /* element to search for */ int element; /* result of linear search */ /* initialize array elements */ for ( loop = 0; loop < SIZE; loop++ ) { array[ loop ] = 2 * loop; } /* end for */ /* obtain search key from user */ printf( "Enter the integer search key: " ); scanf( "%d", &searchKey ); /* search array for search key */ element = linearSearch( array, searchKey, 0, SIZE - 1 ); /* display message if search key was found */ if ( element != -1 ) { printf( "Found value in element %d\n", element ); } /* end if */ else { printf( "Value not found\n" ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* function to search array for specified key */ int linearSearch( int array[], int key, int low, int high ) { /* recursively search array */ if ( array[ low ] == key ) { return low; } /* end if */ else if ( low == high ) { return -1; } /* end else if */ else { /* recursive call */ return linearSearch( array, key, low + 1, high ); } /* end else */ } /* end function linearSearch */  Enter the integer search key: 8 Found value in element 4  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  224 C Arrays: Solutions  Enter the integer search key: 48 Found value in element 24  Enter the integer search key: 99 Value not found  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 225  Chapter 6  6.35 (Binary Search) Modify the program of Fig. 6.19 to use a recursive binarySearch function to perform the binary search of the array. The function should receive an integer array and the starting subscript and ending subscript as arguments. If the search key is found, return the array subscript; otherwise, return –1. 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 53 54 55 56 57 58 59 60 61  /* Exercise 6.35 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define SIZE 15 /* function prototypes */ int binarySearch( int b[], int searchKey, int low, int high ); void printHeader( void ); void printRow( int b[], int low, int mid, int high ); int main() { int a[ SIZE ]; /* array to be searched */ int i; /* loop counter */ int key; /* search key */ int result; /* result of search */ /* initialize array elements */ for ( i = 0; i < SIZE; i++ ) { a[ i ] = 2 * i; } /* end for */ /* obtain key from user */ printf( "Enter a number between 0 and 28: " ); scanf( "%d", &key ); printHeader(); /* search array for key */ result = binarySearch( a, key, 0, SIZE - 1 ); /* display results of the search */ if ( result != -1 ) { printf( "\n%d found in array element %d\n", key, result ); } /* end if */ else { printf( "\n%d not found\n", key ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* function to search array for specified key */ int binarySearch( int b[], int searchKey, int low, int high ) { int middle; /* middle of array */ /* find middle of array and print current subarray */ if ( low <= high ) { middle = ( low + high ) / 2; printRow( b, low, middle, high ); /* determine if middle element is the key and if not, recursively call binarySearch */ if ( searchKey == b[ middle ] ) { return middle; } /* end if */ else if ( searchKey < b[ middle ] ) { /* recursive call on bottom half of array */ return binarySearch( b, searchKey, low, middle - 1 ); } /* end else if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  226 C Arrays: Solutions  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 108 109 110 111 112 113 114 115 116 117  else { /* recursive call on upper half of array */ return binarySearch( b, searchKey, middle + 1, high ); } /* end else */ } /* end if */ return -1; /* searchKey not found */ } /* end function binarySearch */ /* Print a header for the output */ void printHeader( void ) { int i; /* loop counter */ printf( "\nSubscripts:\n" ); /* print subscripts of array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d ", i ); } /* end for */ printf( "\n" ); /* print dividing line */ for ( i = 1; i <= 4 * SIZE; i++ ) { printf( "-" ); } /* end for */ printf( "\n" ); } /* end function printHeader */ /* print one row of output showing the current part of the array being processed. */ void printRow( int b[], int low, int mid, int high ) { int i; /* loop counter */ /* print subarray currently being processed */ for ( i = 0; i < SIZE; i++ ) { if ( i < low || i > high ) { printf( " " ); } /* end if */ else if ( i == mid ) { /* mark middle value */ printf( "%3d*", b[ i ] ); } /* end else if */ else { printf( "%3d ", b[ i ] ); } /* end else */ } /* end for */ printf( "\n" ); } /* end function printRow */  Enter a number between 0 and 28: 17 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 16 18 20 22* 24 26 28 16 18* 20 16* 17 not found  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  C Arrays: Solutions 227  Chapter 6  Enter a number between 0 and 28: 10 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 8 10* 12 10 found in array element 5  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  228 C Arrays: Solutions  6.36  Chapter 6  (Eight Queens) Modify the Eight Queens program you created in Exercise 6.26 to solve the problem recursively.  6.37 (Print an array) Write a recursive function printArray that takes an array and the size of the array as arguments, and returns nothing. The function should stop processing and return when it receives an array of size zero. 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 6.37 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define SIZE 10 /* function prototype */ void printArray( int array[], int low, int high ); int main() { int array[ SIZE ]; /* array to be printed */ int loop; /* loop counter */ srand( time( NULL ) ); /* initialize array elements to random numbers */ for ( loop = 0; loop < SIZE; loop++ ) { array[ loop ] = 1 + rand() % 500; } /* end for */ printf( "Array values printed in main:\n" ); /* print array elements */ for ( loop = 0; loop < SIZE; loop++ ) { printf( "%d ", array[ loop ] ); } /* end for */ printf( "\n\nArray values printed in printArray:\n" ); printArray( array, 0, SIZE - 1 ); printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */ /* function to recursively print an array */ void printArray( int array[], int low, int high ) { /* print first element of array passed */ printf( "%d ", array[ low ] ); /* return if array only has 1 element */ if ( low == high ) { return; } /* end if */ else { /* call printArray with new subarray */ printArray( array, low + 1, high ); } /* end else */ } /* end function printArray */  Array values printed in main: 22 180 7 321 486 366 69  304  273  213  Array values printed in printArray: 22 180 7 321 486 366 69 304 273  213  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 229  Chapter 6  6.38 (Print a string backwards) Write a recursive function stringReverse that takes a character array as an argument, prints it back to front and returns nothing. The function should stop processing and return when the terminating null character of the string is encountered. 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  /* Exercise 6.38 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define SIZE 30 void stringReverse( char strArray[] ); /* function prototype */ int main() { int loop; /* loop counter */ /* initialize string strArray */ char strArray[ SIZE ] = "Print this string backwards."; /* display original string */ for ( loop = 0; loop < SIZE; loop++ ) { printf( "%c", strArray[ loop ] ); } /* end for */ printf( "\n" ); stringReverse( strArray ); /* reverse the string */ printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */ /* function to reverse a string */ void stringReverse( char strArray[] ) { /* return when null character is encountered */ if ( strArray[ 0 ] == '\0' ) { return; } /* end if */ /* recursively call stringReverse with new substring */ stringReverse( &strArray[ 1 ] ); printf( "%c", strArray[ 0 ] ); /* output string elements */ } /* end function stringReverse */  Print this string backwards. .sdrawkcab gnirts siht tnirP  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  230 C Arrays: Solutions  Chapter 6  6.39 (Find the minimum value in an array) Write a recursive function recursiveMinimum that takes an integer array and the array size as arguments and returns the smallest element of the array. The function should stop processing and return when it receives an array of one element. 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 53 54 55 56 57 58 59  /* Exercise 6.39 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define SIZE 10 #define MAXRANGE 1000 /* function prototype */ int recursiveMinimum( int array[], int low, int high ); int main() { int array[ SIZE ]; /* array to be searched */ int loop; /* loop counter */ int smallest; /* smallest element */ srand( time( NULL ) ); /* initialize elements of array to random numbers */ for ( loop = 0; loop < SIZE; loop++ ) { array[ loop ] = 1 + rand() % MAXRANGE; } /* end for */ printf( "Array members are:\n" ); /* display array */ for ( loop = 0; loop < SIZE; loop++ ) { printf( " %d ", array[ loop ] ); } /* end for */ /* find and display smallest array element */ printf( "\n" ); smallest = recursiveMinimum( array, 0, SIZE - 1 ); printf( "\nSmallest element is: %d\n", smallest ); return 0; /* indicate successful termination */ } /* end main */ /* function to recursively find minimum array element */ int recursiveMinimum( int array[], int low, int high ) { static int smallest = MAXRANGE; /* largest possible value */ /* if first element of array is smallest so far, set smallest equal to that element */ if ( array[ low ] < smallest ) { smallest = array[ low ]; } /* end if */ /* if only one element in array, return smallest */ if ( low == high ) { return smallest; } /* end if */ else { /* recursively call recursiveMinimum with new subarray */ return recursiveMinimum( array, low + 1, high ); } /* end else */ } /* end function recursiveMinimum */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Arrays: Solutions 231  Chapter 6  Array members are: 666 251 624 359  577  837  992  197  249  492  Smallest element is: 197  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  232 C Arrays: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 6  7 Pointers: Solutions  SOLUTIONS 7.7  7.8  Answer each of the following: a) The operator returns the location in memory where its operand is stored. ANS: address (&). b) The operator returns the value of the object to which its operand points. ANS: indirection (*). c) To simulate call-by-reference when passing a nonarray variable to a function, it is necessary to pass the the variable to the function. ANS: address.  of  State whether the following are true or false. If false, explain why. a) Two pointers that point to different arrays cannot be compared meaningfully. ANS: True. It is not possible to know where these arrays will be stored in advance. b) Because the name of an array is a pointer to the first element of the array, array names may be manipulated in precisely the same manner as pointers. ANS: False. Array names cannot be modified to point to another location in memory.  7.9 Answer each of the following. Assume that unsigned integers are stored in 2 bytes and that the starting address of the array is at location 1002500 in memory. a) Define an array of type unsigned int called values with five elements, and initialize the elements to the even integers from 2 to 10. Assume the symbolic constant SIZE has been defined as 5. ANS: unsigned int values[ SIZE ] = { 2, 4, 6, 8, 10 }; b) Define a pointer vPtr that points to an object of type unsigned int. ANS: unsigned int *vPtr; c) Print the elements of array values using array subscript notation. Use a for statement and assume integer control variable i has been defined. ANS: for ( i = 0; i < SIZE; i++ ) printf( "%d ", values[ i ] ); d) Give two separate statements that assign the starting address of array values to pointer variable vPtr. ANS: 1) vPtr = values; 2) vPtr = &values[ 0 ];  e) Print the elements of array values using pointer/offset notation.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  234 Pointers: Solutions  Chapter 7  ANS: for ( i = 0; i < SIZE; i++ ) printf( "%d", *( vPtr + i ) ); f) Print the elements of array values using pointer/offset notation with the array name as the pointer. ANS: for ( i = 0; i < SIZE; i++ ) printf( "%d", *( values + i ) ); g) Print the elements of array values by subscripting the pointer to the array. ANS: for ( i = 0; i < SIZE; i++ ) printf( "%d", vPtr[ i ] ); h) Refer to element 5 of array values using array subscript notation, pointer/offset notation with the array name as the pointer, pointer subscript notation, and pointer/offset notation. ANS: values[ 4 ], *( values + 4 ), vPtr[ 4 ], *( vPtr + 4 ). i) What address is referenced by vPtr + 3? What value is stored at that location? ANS: 1002506; 8. j) Assuming vPtr points to values[ 4 ], what address is referenced by vPtr -= 4. What value is stored at that location? ANS: 1002500; 2. 7.10  For each of the following, write a single statement that performs the indicated task. Assume that long integer variables  value1 and value2 have been defined and that value1 has been initialized to 200000. a) Define the variable lPtr to be a pointer to an object of type long. ANS: long *lPtr; b) Assign the address of variable value1 to pointer variable lPtr. ANS: lPtr = &value1; c) Print the value of the object pointed to by lPtr. ANS: printf( "%ld\n", *lPtr ); d) Assign the value of the object pointed to by lPtr to variable value2. ANS: value2 = *lPtr; e) Print the value of value2. ANS: printf( "%ld\n", value2 ); f) Print the address of value1. ANS: printf( "%p\n", &value1 ); g) Print the address stored in lPtr. Is the value printed the same as the address of value1? ANS: printf( "%p\n", lPtr); /* The value is the same */  7.11  Do each of the following. a) Write the function header for function zero, which takes a long integer array parameter bigIntegers and does not return a value. ANS: void zero( long int *bigIntegers); b) Write the function prototype for the function in Part a. ANS: void zero( long int * ); c) Write the function header for function add1AndSum, which takes an integer array parameter oneTooSmall and returns an integer. ANS: int add1AndSum( int *oneTooSmall ); d) Write the function prototype for the function described in Part c. ANS: int add1AndSum( int * );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 235  Chapter 7  Note: Exercise 7.12 through Exercise 7.15 are reasonably challenging. Once you have done these problems, you ought to be able to implement most popular card games easily. 7.12 Modify the program in Fig. 7.24 so that the card-dealing function deals a five-card poker hand. Then write the following additional functions: a) Determine if the hand contains a pair. b) Determine if the hand contains two pairs. c) Determine if the hand contains three of a kind (e.g., three jacks). d) Determine if the hand contains four of a kind (e.g., four aces). e) Determine if the hand contains a flush (i.e., all five cards of the same suit). f) Determine if the hand contains a straight (i.e., five cards of consecutive face values). 7.13 Use the functions developed in Exercise 7.12 to write a program that deals two five-card poker hands, evaluates each hand, and determines which is the better hand. 7.14 Modify the program developed in Exercise 7.13 so that it can simulate the dealer. The dealer's five-card hand is dealt "face down" so the player cannot see it. The program should then evaluate the dealer's hand, and based on the quality of the hand, the dealer should draw one, two or three more cards to replace the corresponding number of unneeded cards in the original hand. The program should then re-evaluate the dealer's hand. [Caution: This is a difficult problem!] 7.15 Modify the program developed in Exercise 7.14 so that it can handle the dealer's hand automatically, but the player is allowed to decide which cards of the player's hand to replace. The program should then evaluate both hands and determine who wins. Now use this new program to play 20 games against the computer. Who wins more games, you or the computer? Have one of your friends play 20 games against the computer. Who wins more games? Based on the results of these games, make appropriate modifications to refine your poker playing program (this, too, is a difficult problem). Play 20 more games. Does your modified program play a better game? 7.16 In the card shuffling and dealing program of Fig. 7.24, we intentionally used an inefficient shuffling algorithm that introduced the possibility of indefinite postponement. In this problem, you will create a high-performance shuffling algorithm that avoids indefinite postponement. Modify the program of Fig. 7.24 as follows. Begin by initializing the deck array as shown in Fig. 7.29. Modify the shuffle function to loop row-by-row and column-by-column through the array touching every element once. Each element should be swapped with a randomly selected element of the array. Print the resulting array to determine if the deck is satisfactorily shuffled (as in Fig. 7.30, for example). You may want your program to call the shuffle function several times to ensure a satisfactory shuffle. Unshuffled deck array  0  1  2  3  4  5  6  7  8  9  10  11  12  0  1  2  3  4  5  6  7  8  9  10  11  12  13  1  14  15  16  17  18  19  20  21  22  23  24  25  26  2  27  28  29  30  31  32  33  34  35  36  37  38  39  3  40  41  42  43  44  45  46  47  48  49  50  51  52  Fig. 7.29 Unshuffled deck array. Sample shuffled deck array  0  1  2  3  4  5  6  7  8  9  10  11  12  0  19  40  27  25  36  46  10  34  35  41  18  2  44  1  13  28  14  16  21  30  8  11  31  17  24  7  1  2  12  33  15  42  43  23  45  3  29  32  4  47  26  3  50  38  52  39  48  51  9  5  37  49  22  6  20  Fig. 7.30  Sample shuffled deck array. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  236 Pointers: Solutions  Chapter 7  Note that although the approach in this problem improves the shuffling algorithm, the dealing algorithm still requires searching the deck array for card 1, then card 2, then card 3, and so on. Worse yet, even after the dealing algorithm locates and deals the card, the algorithm continues searching through the remainder of the deck. Modify the program of Fig. 7.24 so that once a card is dealt, no further attempts are made to match that card number, and the program immediately proceeds with dealing the next card. In Chapter 10, we develop a dealing algorithm that requires only one operation per card. 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 53  /* Exercise 7.16 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* function prototypes */ void shuffle( int workDeck[][ 13 ] ); void deal( int workDeck[][ 13 ], char *workFace[], char *workSuit[] ); int main() { int card = 1; int row; int column; int deck[ 4 ][ 13 ];  /* /* /* /*  card counter */ loop counter */ loop counter */ array of cards */  /* define arrays of card suits and faces */ char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"}; char *face[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; srand( time( NULL ) ); /* initialize deck */ for ( row = 0; row <= 3; row++ ) { for ( column = 0; column <= 12; column++ ) { deck[ row ][ column ] = card++; } /* end for */ } /* end for */ shuffle( deck ); deal( deck, face, suit ); return 0; /* indicate successful termination */ } /* end main */ /* introduce another way to shuffle */ void shuffle( int workDeck[][ 13 ] ) { int temp; /* temporary holder */ int row; /* loop counter */ int column; /* loop counter */ int randRow; /* random suit */ int randColumn; /* random face */ /* run through the loop and touch every element once */ for ( row = 0; row <= 3; row++ ) { for ( column = 0; column <= 12; column++ ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 237  Chapter 7  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  /* generate a random card */ randRow = rand() % 4; randColumn = rand() % 13; /* swap random card with current card */ temp = workDeck[ row ][ column ]; workDeck[ row ][ column ] = workDeck[ randRow ][ randColumn ]; workDeck[ randRow ][ randColumn ] = temp; } /* end for */ } /* end for */ } /* end function shuffle */ /* deal the cards */ void deal( int workDeck2[][ 13 { int card; /* card counter int row; /* loop counter int column; /* loop counter  ], char *workFace[], char *workSuit[] ) */ */ */  /* loop through and print the cards */ for ( card = 1; card <= 52; card++ ) { /* loop through rows */ for ( row = 0; row <= 3; row++ ) { /* loop through columns */ for ( column = 0; column <= 12; column++ ) { /* if current card equals card then deal */ if ( workDeck2[ row ][ column ] == card ) { printf( "%5s of %-8s", workFace[ column ], workSuit[ row ] ); card % 2 == 0 ? putchar( '\n' ) : putchar( '\t' ); break; /* break loop */ } /* end if */ } /* end for */ } /* end for */ } /* end for */ } /* end function deal */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  238 Pointers: Solutions  Eight Five Eight Deuce Seven Four Six Ten Four Jack Deuce Three Nine King Five Four King Deuce Ace Eight Nine Three Queen Queen Five Jack  of of of of of of of of of of of of of of of of of of of of of of of of of of  Spades Hearts Diamonds Hearts Clubs Clubs Spades Hearts Diamonds Diamonds Spades Hearts Hearts Spades Spades Spades Diamonds Clubs Diamonds Hearts Clubs Clubs Hearts Diamonds Clubs Spades  Chapter 7  Ace Ace Queen Seven Six Ace Ten King Four Three Queen Six Nine Seven Seven Ten Nine Jack Ten Six Five Deuce King Jack Three Eight  of of of of of of of of of of of of of of of of of of of of of of of of of of  Spades Hearts Spades Hearts Hearts Clubs Diamonds Hearts Hearts Diamonds Clubs Clubs Diamonds Diamonds Spades Spades Spades Hearts Clubs Diamonds Diamonds Diamonds Clubs Clubs Spades Clubs  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 239  Chapter 7  7.17 (Simulation: The Tortoise and the Hare) In this problem, you will recreate one of the truly great moments in history, namely the classic race of the tortoise and the hare. You will use random number generation to develop a simulation of this memorable event. Our contenders begin the race at "square 1" of 70 squares. Each square represents a possible position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground. There is a clock that ticks once per second. With each tick of the clock, your program should adjust the position of the animals according to the rules of Fig. 7.31.  Animal  Move type  Percentage of the time  Actual move  Tortoise  Fast plod Slip Slow plod  50% 20% 30%  3 squares to the right 6 squares to the left 1 square to the right  Hare  Sleep Big hop Big slip Small hop Small slip  20% 20% 10% 30% 20%  No move at all 9 squares to the right 12 squares to the left 1 square to the right 2 squares to the left  Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70). Start each animal at position 1 (i.e., the "starting gate"). If an animal slips left before square 1, move the animal back to square 1. Generate the percentages in the preceding table by producing a random integer, i, in the range 1 ≤ i ≤ 10. For the tortoise, perform a "fast plod" when 1 ≤ i ≤ 5, a "slip" when 6 ≤ i ≤ 7, or a "slow plod" when 8 ≤ i ≤ 10. Use a similar technique to move the hare. Begin the race by printing BANG !!!!! AND THEY'RE OFF !!!!!  Then, for each tick of the clock (i.e., each repetition of a loop), print a 70 position line showing the letter T in the position of the tortoise and the letter H in the position of the hare. Occasionally, the contenders will land on the same square. In this case, the tortoise bites the hare and your program should print OUCH!!! beginning at that position. All print positions other than the T, the H, or the OUCH!!! (in case of a tie) should be blank. After each line is printed, test if either animal has reached or passed square 70. If so, then print the winner and terminate the simulation. If the tortoise wins, print TORTOISE WINS!!! YAY!!! If the hare wins, print Hare wins. Yuch. If both animals win on the same tick of the clock, you may want to favor the turtle (the "underdog"), or you may want to print It's a tie. If neither animal wins, perform the loop again to simulate the next tick of the clock. When you are ready to run your program, assemble a group of fans to watch the race. You'll be amazed at how involved your audience gets! ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  /* Exercise 7.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* function prototypes */ void moveTortoise( int *turtlePtr ); void moveHare( int *rabbitPtr ); void printCurrentPositions( int *snapperPtr, int *bunnyPtr ); int main() { int tortoise = 1; /* tortoise current position */ int hare = 1; /* hare current position */ int timer = 0; /* time elapsed during race */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  240 Pointers: Solutions  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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  srand( time( NULL ) ); printf( "ON YOUR MARK, GET SET\n" ); printf( "BANG !!!!\n" ); printf( "AND THEY'RE OFF !!!!\n" ); /* loop through the events */ while ( tortoise != 70 && hare != 70 ) { moveTortoise( &tortoise ); moveHare( &hare ); printCurrentPositions( &tortoise, &hare ); ++timer; } /* end while */ /* determine the winner and print message */ if ( tortoise >= hare ) { printf( "\nTORTOISE WINS!!! YAY!!!\n" ); } /* end if */ else { printf( "Hare wins. Yuch.\n" ); } /* end else */ printf( "TIME ELAPSED = %d seconds", timer ); return 0; /* indicate successful termination */ } /* end main */ /* progress for the tortoise */ void moveTortoise( int *turtlePtr ) { int x; /* random number */ x = rand() % 10 + 1; /* generate random number from 1-10 */ /* determine progress */ if ( x >= 1 && x <= 5 ) { /* fast plod */ *turtlePtr += 3; } /* end if */ else if ( x == 6 || x == 7 ) { /* slip */ *turtlePtr -= 6; } /* end else if */ else { /* slow plod */ ++( *turtlePtr ); } /* end else */ /* check boundaries */ if ( *turtlePtr < 1 ) { *turtlePtr = 1; } /* end if */ if ( *turtlePtr > 70 ) { *turtlePtr = 70; } /* end if */ } /* end function moveTortoise */ /* progress for the hare */ void moveHare( int *rabbitPtr ) { int y; /* random number */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 241  Chapter 7  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128  y = rand() % 10 + 1; /* generate random number from 1-10 */ /* determine progress */ if ( y == 3 || y == 4 ) { /* big hop */ *rabbitPtr += 9; } /* end if */ else if ( y == 5 ) { /* big slip */ *rabbitPtr -= 12; } /* end else if */ else if ( y >= 6 && y <= 8 ) { /* small hop */ ++( *rabbitPtr ); } /* end else if */ else if ( y == 10 ) { /* small slip */ *rabbitPtr -= 2; } /* end else if */ /* check boundaries */ if ( *rabbitPtr < 1 ) { *rabbitPtr = 1; } /* end if */ if ( *rabbitPtr > 70 ) { *rabbitPtr = 70; } /* end if */ } /* end function moveHare */ /* display new position */ void printCurrentPositions( int *snapperPtr, int *bunnyPtr ) { int count; /* counter */ /* loop through race */ for ( count = 1; count <= 70; count++ ) /* print current leader */ if ( count == *snapperPtr && count == *bunnyPtr ) { printf( "OUCH!!!" ); } /* end if */ else if ( count == *bunnyPtr ) { printf( "H" ); } /* end else if */ else if ( count == *snapperPtr ) { printf( "T" ); } /* end else if */ else { printf( " " ); } /* end else */ printf( "\n" ); } /* end function printCurrentPositions */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  242 Pointers: Solutions  Chapter 7  ON YOUR MARK, GET SET BANG !!!! AND THEY'RE OFF !!!! OUCH!!! H T H T T H T H T H T H T H T H T H T H T H T H T H T H T H T H H T H T H T H T H T H T H T H T H T H T H T H T TH OUCH!!! H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T ... H  T TH T  H T  H H H H  T T T T  H T  H T  H  Hare wins. Yuch. TIME ELAPSED = 88 seconds  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 243  Chapter 7  SPECIAL SECTION: BUILDING YOUR OWN COMPUTER In the next several problems, we take a temporary diversion away from the world of high-level language programming. We "peel open" a computer and look at its internal structure. We introduce machine language programming and write several machine language programs. To make this an especially valuable experience, we then build a computer (through the technique of software-based simulation) on which you can execute your machine language programs! 7.18 (Machine Language Programming) Let us create a computer we will call the Simpletron. As its name implies, it is a simple machine, but as we will soon see, a powerful one as well. The Simpletron runs programs written in the only language it directly understands—that is, Simpletron Machine Language, or SML for short. The Simpletron contains an accumulator—a "special register" in which information is put before the Simpletron uses that information in calculations or examines it in various ways. All information in the Simpletron is handled in terms of words. A word is a signed four-digit decimal number such as +3364, -1293, +0007, -0001, etc. The Simpletron is equipped with a 100-word memory, and these words are referenced by their location numbers 00, 01, …, 99. Before running an SML program, we must load or place the program into memory. The first instruction (or statement) of every SML program is always placed in location 00. Each instruction written in SML occupies one word of the Simpletron's memory (and hence instructions are signed four-digit decimal numbers). We assume that the sign of an SML instruction is always plus, but the sign of a data word may be either plus or minus. Each location in the Simpletron's memory may contain either an instruction, a data value used by a program or an unused (and hence undefined) area of memory. The first two digits of each SML instruction are the operation code, which specifies the operation to be performed. SML operation codes are summarized in Fig. Fig. 7.32.  Operation code  Meaning  Input/output operations: #define READ 10 #define WRITE 11  Read a word from the terminal into a specific location in memory. Write a word from a specific location in memory to the terminal.  Load/store operations: #define LOAD 20  Load a word from a specific location in memory into the accumulator.  #define STORE 21  Store a word from the accumulator into a specific location in memory.  Arithmetic operations: #define ADD 30  Add a word from a specific location in memory to the word in the accumulator (leave result in accumulator).  #define SUBTRACT 31  Subtract a word from a specific location in memory from the word in the accumulator (leave result in accumulator). Divide a word from a specific location in memory into the word in the accumulator (leave result in accumulator). Multiply a word from a specific location in memory by the word in the accumulator (leave result in accumulator).  #define DIVIDE 32 #define MULTIPLY 33  Transfer of control operations: #define BRANCH 40  Branch to a specific location in memory. #define BRANCHNEG 41 Branch to a specific location in memory if the accumulator is negative. #define BRANCHZERO 42 Branch to a specific location in memory if the accumulator is zero. #define HALT 43 Halt—i.e., the program has completed its task. Fig. 7.32 Simpletron Machine Language (SML) operation codes. The last two digits of an SML instruction are the operand, which is the address of the memory location containing the word to which the operation applies. Now let us consider several simple SML programs.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  244 Pointers: Solutions  Chapter 7  Example 1 Location  Number  Instruction  00  +1007  (Read A)  01  +1008  (Read B)  02  +2007  (Load A)  03  +3008  (Add B)  04  +2109  (Store C)  05  +1109  (Write C)  06  +4300  (Halt)  07  +0000  (Variable A)  08  +0000  (Variable B)  09  +0000  (Result C)  The preceding SML program reads two numbers from the keyboard, and computes and prints their sum. The instruction +1007 reads the first number from the keyboard and places it into location 07 (which has been initialized to zero). Then +1008 reads the next number into location 08. The load instruction, +2007, puts the first number into the accumulator, and the add instruction, +3008, adds the second number to the number in the accumulator. All SML arithmetic instructions leave their results in the accumulator. The store instruction, +2109, places the result back into memory location 09 from which the write instruction, +1109, takes the number and prints it (as a signed four-digit decimal number). The halt instruction, +4300, terminates execution.  Example 2 Location  Number  Instruction  00  +1009  (Read A)  01  +1010  (Read B)  02  +2009  (Load A)  03  +3110  (Subtract B)  04  +4107  (Branch negative to 07)  05  +1109  (Write A)  06  +4300  (Halt)  07  +1110  (Write B)  08  +4300  (Halt)  09  +0000  (Variable A)  10  +0000  (Variable B)  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 245  Chapter 7  The preceding SML program reads two numbers from the keyboard, and determines and prints the larger value. Note the use of the instruction +4107 as a conditional transfer of control, much the same as C's if statement. Now write SML programs to accomplish each of the following tasks. a) Use a sentinel-controlled loop to read 10 positive integers and compute and print their sum. ANS: 00 01 02 03 04 05 06 07 08 09  +1009 +2009 +4106 +3008 +2108 +4000 +1108 +4300 +0000 +0000  (Read Value) (Load Value) (Branch negative to 06) (Add Sum) (Store Sum) (Branch 00) (Write Sum) (Halt) (Variable Sum) (Variable Value)  b) Use a counter-controlled loop to read seven numbers, some positive and some negative, and compute and print their average. ANS: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21  +2018 +3121 +4211 +2018 +3019 +2118 +1017 +2016 +3017 +2116 +4000 +2016 +3218 +2120 +1120 +4300 +0000 +0000 +0000 +0001 +0000 +0007  (Load Counter) (Subtract Termination) (Branch zero to 11) (Load Counter) (Add Increment) (Store Counter) (Read Value) (Load Sum) (Add Value) (Store Sum) (Branch 00) (Load Sum) (Divide Counter) (Store Result) (Write Result) (Halt) (Variable Sum) (Variable Value) (Variable Counter) (Variable Increment) (Variable Result) (Variable Termination)  c) Read a series of numbers and determine and print the largest number. The first number read indicates how many numbers should be processed. ANS: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21  +1017 +2018 +3117 +4215 +2018 +3021 +2118 +1019 +2020 +3119 +4112 +4001 +2019 +2120 +4001 +1120 +4300 +0000 +0000 +0000 +0000 +0001  (Read Endvalue) (Load Counter) (Subtract Endvalue) (Branch zero to 15) (Load Counter) (Add Increment) (Store Counter) (Read Value) (Load Largest) (Subtract Value) (Branch negative to 12) (Branch 01) (Load Value) (Store Largest) (Branch 01) (Write Largest) (Halt) (Variable Endvalue) (Variable Counter) (Variable Value) (Variable Largest) (Variable Increment)  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  246 Pointers: Solutions  Chapter 7  7.19 (A Computer Simulator) It may at first seem outrageous, but in this problem you are going to build your own computer. No, you will not be soldering components together. Rather, you will use the powerful technique of software-based simulation to create a software model of the Simpletron. You will not be disappointed. Your Simpletron simulator will turn the computer you are using into a Simpletron, and you will actually be able to run, test and debug the SML programs you wrote in Exercise 7.18. When you run your Simpletron simulator, it should begin by printing: *** *** *** *** *** *** ***  Welcome to Simpletron! *** Please enter your program one instruction (or data word) at a time. I will type the location number and a question mark (?). You then type the word for that location. Type the sentinel -99999 to stop entering your program. ***  *** *** *** *** ***  Simulate the memory of the Simpletron with a single-subscripted array memory that has 100 elements. Now assume that the simulator is running, and let us examine the dialog as we enter the program of Example 2 of Exercise 7.18: 00 ? +1009 01 ? +1010 02 ? +2009 03 ? +3110 04 ? +4107 05 ? +1109 06 ? +4300 07 ? +1110 08 ? +4300 09 ? +0000 10 ? +0000 11 ? -99999 *** Program loading completed *** *** Program execution begins ***  The SML program has now been placed (or loaded) into the array memory. Now the Simpletron executes your SML program. Execution begins with the instruction in location 00 and, like C, continues sequentially, unless directed to some other part of the program by a transfer of control. Use the variable accumulator to represent the accumulator register. Use the variable instructionCounter to keep track of the location in memory that contains the instruction being performed. Use the variable operationCode to indicate the operation currently being performed—i.e., the left two digits of the instruction word. Use the variable operand to indicate the memory location on which the current instruction operates. Thus, operand is the rightmost two digits of the instruction currently being performed. Do not execute instructions directly from memory. Rather, transfer the next instruction to be performed from memory to a variable called instructionRegister. Then "pick off" the left two digits and place them in the variable operationCode, and "pick off" the right two digits and place them in operand. When Simpletron begins execution, the special registers are initialized as follows: accumulator instructionCounter instructionRegister operationCode operand  +0000 00 +0000 00 00  Now let us "walk through" the execution of the first SML instruction, +1009 in memory location 00. This is called an instruction execution cycle. The instructionCounter tells us the location of the next instruction to be performed. We fetch the contents of that location from memory by using the C statement instructionRegister = memory[ instructionCounter ];  The operation code and the operand are extracted from the instruction register by the statements operationCode = instructionRegister / 100; operand = instructionRegister % 100;  Now the Simpletron must determine that the operation code is actually a read (versus a write, a load, etc.). A switch differentiates among the twelve operations of SML. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 247  Chapter 7  In the switch statement, the behavior of various SML instructions is simulated as follows (we leave the others to the reader): read: scanf( "%d", &memory[ operand ] ); load: accumulator = memory[ operand ]; add: accumulator += memory[ operand ]; Various branch instructions: We'll discuss these shortly. halt: This instruction prints the message *** Simpletron execution terminated ***  then prints the name and contents of each register as well as the complete contents of memory. Such a printout is often called a computer dump. To help you program your dump function, a sample dump format is shown in Fig. Fig. 7.33. Note that a dump after executing a Simpletron program would show the actual values of instructions and data values at the moment execution terminated.  REGISTERS: accumulator instructionCounter instructionRegister operationCode operand  +0000 00 +0000 00 00  MEMORY: 0 10 20 30 40 50 60 70 80 90  0 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  1 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  2 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  3 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  4 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  5 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  6 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  7 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  8 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  9 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  Fig. 7.33 Sample dump of Simpletron's memory. Let us proceed with the execution of our program's first instruction, namely the +1009 in location 00. As we have indicated, the switch statement simulates this by performing the C statement scanf( "%d", &memory[ operand ] );  A question mark (?) should be displayed on the screen before the scanf is executed to prompt the user for input. The Simpletron waits for the user to type a value and then press the Return key. The value is then read into location 09. At this point, simulation of the first instruction is completed. All that remains is to prepare the Simpletron to execute the next instruction. Since the instruction just performed was not a transfer of control, we need merely increment the instruction counter register as follows: ++instructionCounter;  This completes the simulated execution of the first instruction. The entire process (i.e., the instruction execution cycle) begins anew with the fetch of the next instruction to be executed. Now let us consider how the branching instructions—the transfers of control—are simulated. All we need to do is adjust the value in the instruction counter appropriately. Therefore, the unconditional branch instruction (40) is simulated within the switch as instructionCounter = operand;  The conditional "branch if accumulator is zero" instruction is simulated as  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  248 Pointers: Solutions  Chapter 7  if ( accumulator == 0 ) instructionCounter = operand;  At this point, you should implement your Simpletron simulator and run the SML programs you wrote in Exercise 7.18. You may embellish SML with additional features and provide for these in your simulator. Your simulator should check for various types of errors. During the program loading phase, for example, each number the user types into the Simpletron's memory must be in the range -9999 to +9999. Your simulator should use a while loop to test that each number entered is in this range, and, if not, keep prompting the user to reenter the number until the user enters a correct number. During the execution phase, your simulator should check for various serious errors, such as attempts to divide by zero, attempts to execute invalid operation codes and accumulator overflows (i.e., arithmetic operations resulting in values larger than +9999 or smaller than -9999). Such serious errors are called fatal errors. When a fatal error is detected, your simulator should print an error message such as: *** Attempt to divide by zero *** *** Simpletron execution abnormally terminated ***  and should print a full computer dump in the format we have discussed previously. This will help the user locate the error in the program. 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  /* Exercise 7.19 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* define commands */ #define SIZE 100 #define SENTINEL -99999 #define TRUE 1 #define FALSE 0 #define READ 10 #define WRITE 11 #define LOAD 20 #define STORE 21 #define ADD 30 #define SUBTRACT 31 #define DIVIDE 32 #define MULTIPLY 33 #define BRANCH 40 #define BRANCHNEG 41 #define BRANCHZERO 42 #define HALT 43 /* function prototypes */ void load( int *loadMemory ); void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, int *opCodePtr, int *opPtr ); void dump( int *memory, int accumulator, int instructionCounter, int instructionRegister, int operationCode, int operand ); int validWord( int word ); int main() { int memory[ SIZE ]; /* define memory array */ int ac = 0; /* accumulator */ int ic = 0; /* instruction counter */ int opCode = 0; /* operation code */ int op = 0; /* operand */ int ir = 0; /* instruction register */ int i; /* counter */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 249  Chapter 7  41 42 43 44 45 46 47 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 92 93 94 95 96 97 98 99 100 101  /* clear memory */ for ( i = 0; i < SIZE; i++ ) { memory[ i ] = 0; } /* end for */ load( memory ); execute( memory, &ac, &ic, &ir, &opCode, &op ); dump( memory, ac, ic, ir, opCode, op ); return 0; /* indicate successful termination */ } /* end main */ /* function loads instructions */ void load( int *loadMemory ) { long int instruction; /* current instruction */ int i = 0; /* indexing variable */ printf( "%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n\n", "*** Welcome to Simpletron ***", "*** Please enter your program one instruction ***", "*** ( or data word ) at a time. I will type the ***", "*** location number and a question mark ( ? ). ***", "*** You then type the word for that location. ***", "*** Type the sentinel -99999 to stop entering ***", "*** your program. ***" ); printf( "00 ? " ); scanf( "%ld", &instruction ); /* read instruction */ /* while sentinel is not read from user */ while ( instruction != SENTINEL ) { /* test instruction for validity */ if ( !validWord( instruction ) ) { printf( "Number out of range. Please enter again.\n" ); } /* end if */ else { /* load instruction */ loadMemory[ i++ ] = instruction; } /* end else */ printf( "%02d ? ", i ); scanf( "%ld", &instruction ); } /* end while */ } /* end function load */ /* carry out the commands */ void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, int *opCodePtr, int *opPtr ) { int fatal = FALSE; /* fatal error flag */ int temp; /* temporary holding space */ printf( "\n************START SIMPLETRON EXECUTION************\n\n" ); /* separate operation code and operand */ *irPtr = memory[ *icPtr ]; *opCodePtr = *irPtr / 100; *opPtr = *irPtr % 100;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  250 Pointers: Solutions  102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162  /* loop while command is not HALT or fatal */ while ( *opCodePtr != HALT && !fatal ) { /* determine appropriate action */ switch ( *opCodePtr ) { /* read data into location in memory */ case READ: printf( "Enter an integer: " ); scanf( "%d", &temp ); /* check for validity */ while ( !validWord( temp ) ) { printf( "Number out of range. Please enter again: " ); scanf( "%d", &temp ); } /* end while */ memory[ *opPtr ] = temp; /* write to memory */ ++( *icPtr ); break; /* exit switch */ /* write data from memory to screen */ case WRITE: printf( "Contents of %02d: %d\n", *opPtr, memory[ *opPtr ] ); ++( *icPtr ); break; /* exit switch */ /* load data from memory into accumulator */ case LOAD: *acPtr = memory[ *opPtr ]; ++( *icPtr ); break; /* exit switch */ /* store data from accumulator into memory */ case STORE: memory[ *opPtr ] = *acPtr; ++( *icPtr ); break; /* exit switch */ /* add data from memory to data in accumulator */ case ADD: temp = *acPtr + memory[ *opPtr ]; /* check validity */ if ( !validWord( temp ) ) { printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr = temp; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* subtract data in memory from data in accumulator */ case SUBTRACT: temp = *acPtr - memory[ *opPtr ];  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 251  Chapter 7  163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223  /* check validity */ if ( !validWord( temp ) ) { printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr = temp; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* divide data in memory into data in accumulator */ case DIVIDE: /* check for divide by zero error */ if ( memory[ *opPtr ] == 0 ) { printf( "*** FATAL ERROR: Attempt to divide by zero ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr /= memory[ *opPtr ]; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* multiple data in memory by data in accumulator */ case MULTIPLY: temp = *acPtr * memory[ *opPtr ]; /* check validity */ if ( !validWord( temp ) ) { printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr = temp; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* branch to specific location in memory */ case BRANCH: *icPtr = *opPtr; break; /* exit switch */ /* branch to location in memory if accumulator is negative */ case BRANCHNEG: /* if accumulator is negative */ if ( *acPtr < 0 ) { *icPtr = *opPtr; } /* end if */ else { ++( *icPtr ); } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  252 Pointers: Solutions  224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284  Chapter 7  break; /* exit switch */ /* branch to location in memory if accumulator is zero */ case BRANCHZERO: /* if accumulator is zero */ if ( *acPtr == 0 ) { *icPtr = *opPtr; } /* end if */ else { ++( *icPtr ); } /* end else */ break; /* exit switch */ default: printf( "*** FATAL ERROR: Invalid opcode detected ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; break; /* exit switch */ } /* end switch */ /* separate next operation code and operand */ *irPtr = memory[ *icPtr ]; *opCodePtr = *irPtr / 100; *opPtr = *irPtr % 100; } /* end while */ printf( "\n*************END SIMPLETRON EXECUTION*************\n" ); } /* end function execute */ /* print out name and content of each register and memory */ void dump( int *memory, int accumulator, int instructionCounter, int instructionRegister, int operationCode, int operand ) { int i; /* counter */ printf( "\n%s\n%-23s%+05d\n%-23s%5.2d\n%-23s%+05d\n%-23s%5.2d\n%-23s%5.2d", "REGISTERS:", "accumulator", accumulator, "instructioncounter", instructionCounter, "instructionregister", instructionRegister, "operationcode", operationCode, "operand", operand ); printf( "\n\nMEMORY:\n  " );  /* print column headers */ for ( i = 0; i <= 9; i++ ) { printf( "%5d ", i ); } /* end for */ /* print row headers and memory contents */ for ( i = 0; i < SIZE; i++ ) { /* print in increments of 10 */ if ( i % 10 == 0 ) { printf( "\n%2d ", i ); } /* end if */ printf( "%+05d ", memory[ i ] ); } /* end for */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 253  Chapter 7  285 286 287 288 289 290 291 292 293 294 295  printf( "\n" ); } /* end function dump */ /* function tests validity of word */ int validWord( int word ) { return word >= -9999 && word <= 9999; } /* end function validWord */  ***  Welcome to Simpletron  *** *** *** *** *** *** 00 01 02 03 04 05 06 07 08 09 10  ***  Please enter your program one instruction *** ( or data word ) at a time. I will type the *** location number and a question mark ( ? ). *** You then type the word for that location. *** Type the sentinel -99999 to stop entering *** your program. *** ? ? ? ? ? ? ? ? ? ? ?  1007 1008 2007 3008 2109 1109 4300 0000 0000 0000 -99999  ************START SIMPLETRON EXECUTION************ Enter an integer: 23 Enter an integer: 17 Contents of 09: 40 *************END SIMPLETRON EXECUTION************* REGISTERS: accumulator instructioncounter instructionregister operationcode operand  +0040 06 +4300 43 00  MEMORY: 0 10 20 30 40 50 60 70 80 90  0 +1007 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  1 +1008 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  2 +2007 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  3 +3008 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  4 +2109 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  5 +1109 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  6 +4300 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  7 +0023 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  8 +0017 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  9 +0040 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  254 Pointers: Solutions  Chapter 7  7.20 Modify the card shuffling and dealing program of Fig. 7.24 so the shuffling and dealing operations are performed by the same function (shuffleAndDeal). The function should contain one nested looping structure that is similar to function shuffle in Fig. 7.24. 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 7.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* function prototype */ void shuffleAndDeal( int workdeck[][ 13 ], char *workface[], char *worksuit[] ); int main() { /* define card suit array and card face array */ char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"}; char *face[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; int deck[ 4 ][ 13 ] = { 0 }; /* array of cards */ srand( time( NULL ) ); shuffleAndDeal( deck, face, suit ); return 0; /* indicate successful termination */ } /* end main */ /* integrate shuffling and dealing operation */ void shuffleAndDeal( int workdeck[][ 13 ], char *workface[], char *worksuit[] ) { int card; /* card loop counter */ int row; /* current suit */ int column; /* current face */ /* loop through the deck of cards, shuffle and print */ for ( card = 1; card <= 52; card++ ) { /* choose random card until not equal to zero */ do { row = rand() % 4; column = rand() % 13; } while( workdeck[ row ][ column ] != 0 ); /* end do...while */ workdeck[ row ][ column ] = card; /* deal card */ printf( "%5s of %-8s", workface[ column ], worksuit[ row ] ); card % 2 == 0 ? printf( "\n" ) : printf( "\t" ); } /* end for */ } /* end function shuffleAndDeal */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 255  Chapter 7  Seven Six Three Jack Queen Four Six Three Seven Ten Queen Five Deuce Ace Five Deuce Nine King Seven Six Nine Three Four Ten Four Six  of of of of of of of of of of of of of of of of of of of of of of of of of of  Spades Spades Clubs Diamonds Clubs Hearts Clubs Hearts Clubs Hearts Hearts Clubs Spades Clubs Spades Hearts Hearts Clubs Diamonds Hearts Spades Spades Diamonds Spades Clubs Diamonds  King King Three Jack Eight Deuce Eight Five Ace Five Eight Deuce Jack Nine Nine King Queen Four Ace Ten Queen Jack Ace Ten Eight Seven  of of of of of of of of of of of of of of of of of of of of of of of of of of  Diamonds Hearts Diamonds Spades Hearts Clubs Spades Hearts Hearts Diamonds Clubs Diamonds Hearts Diamonds Clubs Spades Spades Spades Diamonds Diamonds Diamonds Clubs Spades Clubs Diamonds Hearts  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  256 Pointers: Solutions  7.21 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  What does this program do? /* ex07_21.c */ /* What does this program do? */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              void mystery1( char *s1, const char *s2 ); /* prototype */ int main() { char string1[ 80 ]; /* create char array */ char string2[ 80 ]; /* create char array */ printf( "Enter two strings: " ); scanf( "%s%s" , string1, string2 ); mystery1( string1, string2 ); printf("%s", string1 ); return 0; /* indicates successful termination */ } /* end main */ /* What does this function do? */ void mystery1( char *s1, const char *s2 ) { while ( *s1 != '\0' ) { s1++; } /* end while */ for ( ; *s1 = *s2; s1++, s2++ ) { ; /* empty statement */ } /* end for */ } /* end function mystery1 */  ANS: Concatenates strings.  Enter two strings: string1 string2 string1string2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 257  Chapter 7  7.22 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  What does this program do? /* ex07_22.c */ /* what does this program do? */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int mystery2( const char *s ); /* prototype */ int main() { char string[ 80 ]; /* create char array */ printf( "Enter a string: "); scanf( "%s", string ); printf( "%d\n", mystery2( string ) ); return 0; /* indicates successful termination */ } /* end main */ /* What does this function do? */ int mystery2( const char *s ) { int x; /* counter */ /* loop through string */ for ( x = 0; *s != '\0'; s++ ) { x++; } /* end for */ return x; } /* end function mystery2 */  ANS: Determines the length of a string.  Enter a string: string1 7  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  258 Pointers: Solutions  7.23  Chapter 7  Find the error in each of the following program segments. If the error can be corrected, explain how. a) int *number; printf( "%d\n", *number );  ANS: number has not been assigned to point to a location in memory. b) float *realPtr; long *integerPtr; integerPtr = realPtr;  ANS: A pointer cannot be assigned to a different type, other than void *. c) int * x, y; x = y;  ANS: There are two possible solutions. 1) The indirection operator (*) is not distributive and would be required for y, which would result in a valid pointer assignment. 2) y as it is defined is a valid integer variable, and would require the address operator (&) in the pointer assignment statement. d) char s[] = "this is a character array"; int count; for ( ; *s != '\0'; s++) printf( "%c ", *s ); ANS: s should be defined as char *, a constant pointer cannot be moved. e) short *numPtr, result; void *genericPtr = numPtr; result = *genericPtr + 7; ANS: A void * pointer cannot be dereferenced. f) float x = 19.34; float xPtr = &x; printf( "%f\n", xPtr ); ANS: xPtr is not defined as a pointer so it should be dereferenced as well. g) char *s; printf( "%s\n", s ); ANS: s has not been assigned a value, it does not point to anything.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 259  Chapter 7  7.24 (Quicksort) In the examples and exercises of Chapter 6, we discussed the sorting techniques bubble sort, bucket sort and selection sort. We now present the recursive sorting technique called Quicksort. The basic algorithm for a single-subscripted array of values is as follows: a) Partitioning Step: Take the first element of the unsorted array and determine its final location in the sorted array (i.e., all values to the left of the element in the array are less than the element, and all values to the right of the element in the array are greater than the element). We now have one element in its proper location and two unsorted subarrays. b) Recursive Step: Perform Step 1 on each unsorted subarray. Each time Step 1 is performed on a subarray, another element is placed in its final location of the sorted array, and two unsorted subarrays are created. When a subarray consists of one element, it must be sorted; therefore, that element is in its final location. The basic algorithm seems simple enough, but how do we determine the final position of the first element of each subarray. As an example, consider the following set of values (the element in bold is the partitioning element—it will be placed in its final location in the sorted array): 37 2 6 4 89 8 10 12 68 45 a) Starting from the rightmost element of the array, compare each element with 37 until an element less than 37 is found. Then swap 37 and that element. The first element less than 37 is 12, so 37 and 12 are swapped. The new array is 12 2 6 4 89 8 10 37 68 45 Element 12 is in italic to indicate that it was just swapped with 37. b) Starting from the left of the array, but beginning with the element after 12, compare each element with 37 until an element greater than 37 is found. Then swap 37 and that element. The first element greater than 37 is 89, so 37 and 89 are swapped. The new array is 12 2 6 4 37 8 10 89 68 45 c) Starting from the right, but beginning with the element before 89, compare each element with 37 until an element less than 37 is found. Then swap 37 and that element. The first element less than 37 is 10, so 37 and 10 are swapped. The new array is 12 2 6 4 10 8 37 89 68 45 d) Starting from the left, but beginning with the element after 10, compare each element with 37 until an element greater than 37 is found. Then swap 37 and that element. There are no more elements greater than 37, so when we compare 37 with itself, we know that 37 has been placed in its final location of the sorted array. Once the partition has been applied to the array, there are two unsorted subarrays. The subarray with values less than 37 contains 12, 2, 6, 4, 10 and 8. The subarray with values greater than 37 contains 89, 68 and 45. The sort continues by partitioning both subarrays in the same manner as the original array. Write recursive function quicksort to sort a single-subscripted integer array. The function should receive as arguments an integer array, a starting subscript and an ending subscript. Function partition should be called by quicksort to perform the partitioning step. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  /* Exercise 7.24 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define MAX 10 /* function prototypes */ void quicksort( int *array, int first, int last ); int partition( int *array, int left, int right ); void swap( int *ptr1, int *ptr2 ); int main() { int loop; /* loop counter */ int arrayToBeSorted[ MAX ] = { 0 }; /* array to sort */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  260 Pointers: Solutions  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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  srand( time( NULL ) ); /* randomly generate content */ for ( loop = 0; loop < MAX; loop++ ) { arrayToBeSorted[ loop ] = rand() % 1000; } /* end for */ printf( "Initial array values are: \n" ); /* print out values of the array */ for ( loop = 0; loop < MAX; loop++ ) { printf( "%4d", arrayToBeSorted[ loop ] ); } /* end for */ printf( "\n\n" ); /* if there is only one element */ if ( MAX == 1 ) { printf( "Array is sorted: %d\n", arrayToBeSorted[ 0 ] ); } /* end if */ else { /* call quicksort */ quicksort( arrayToBeSorted, 0, MAX - 1 ); printf( "The sorted array values are:\n" ); /* display sorted array */ for ( loop = 0; loop < MAX; loop++ ) { printf( "%4d", arrayToBeSorted[ loop ] ); } /* end for */ printf( "\n" ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* recursive function to sort array */ void quicksort( int array[], int first, int last ) { int currentLocation; /* current location in array */ /* if array is sorted, return */ if ( first >= last ) { return; } /* end if */ currentLocation = partition( array, first, last ); /* place an element */ quicksort( array, first, currentLocation - 1 ); /* sort left side */ quicksort( array, currentLocation + 1, last ); /* sort right side */ } /* end function quicksort */ /* partition the array into multiple sections */ int partition( int array[], int left, int right ) { int position = left; /* final location of first element */ /* infinite loop */ while ( 1 ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 261  Chapter 7  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124  /* loop through the portion of the array */ while ( array[ position ] <= array[ right ] && position != right ) { --right; } /* end while */ /* if correct position is found */ if ( position == right ) { return position ; } /* end if */ /* swap positions */ if ( array[ position ] > array[ right ] ) { swap( &array[ position ], &array[ right ] ); position = right; } /* end if */ /* loop through the portion of the array */ while ( array[ left ] <= array[ position ] && left != position ) { ++left; } /* end while */ /* if correct position is found */ if ( position == left ) { return position; } /* end if */ /* swap positions */ if ( array[ left ] > array[ position ] ) { swap( &array[ position ], &array[ left ] ); position = left; } /* end if */ } /* end while */ } /* end function partition */ /* swap locations */ void swap( int *ptr1, int *ptr2 ) { int temp; /* temporary holder */ temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; } /* end function swap */  Initial array values are: 276 980 550 654 811 764 571 469  12 161  The sorted array values are: 12 161 276 469 550 571 654 764 811 980  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  262 Pointers: Solutions  7.25  Chapter 7  (Maze Traversal) The following grid is a double-subscripted array representation of a maze. # # . # # # # # # # # #  # . . # . # . # . # . #  # . # # . # . . . # . #  # . . . . # # # . # . #  # # # # . . . . . # . #  # . . . # # # # . # . #  # . # . # . . . . . . #  # . # . # # # # . # # #  # . # . . . . . . # . #  # . # # # # # # # # . #  # . . . . . . . . . . #  # # # # . # # # # # # #  The # symbols represent the walls of the maze, and the periods (.) represent squares in the possible paths through the maze. There is a simple algorithm for walking through a maze that guarantees finding the exit (assuming there is an exit). If there is not an exit, you will arrive at the starting location again. Place your right hand on the wall to your right and begin walking forward. Never remove your hand from the wall. If the maze turns to the right, you follow the wall to the right. As long as you do not remove your hand from the wall, eventually you will arrive at the exit of the maze. There may be a shorter path than the one you have taken, but you are guaranteed to get out of the maze. Write recursive function mazeTraverse to walk through the maze. The function should receive as arguments a 12-by-12 character array representing the maze and the starting location of the maze. As mazeTraverse attempts to locate the exit from the maze, it should place the character X in each square in the path. The function should display the maze after each move so the user can watch as the maze is solved. 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  /* Exercise 7.25 Solution */ /* This solution assumes that there is only one */ /* entrance and one exit for a given maze, and */ /* these are the only two zeroes on the borders.*/ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #define #define #define #define  DOWN RIGHT UP LEFT  0 1 2 3  /* /* /* /*  move move move move  down right up left  */ */ */ */  #define X_START 2 /* starting X and Y coordinate for maze */ #define Y_START 0 /* function prototypes */ void mazeTraversal( char maze[ 12 ][ 12 ], int xCoord, int yCoord, int direction ); void printMaze( const char maze[][ 12 ] ); int validMove( const char maze[][ 12 ], int r, int c ); int coordsAreEdge( int x, int y ); int main() { /* maze grid */ char maze[ 12 ][ 12 ] = { { '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'}, { '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '1'}, { '0', '0', '1', '0', '1', '0', '1', '1', '1', '1', '0', '1'}, { '1', '1', '1', '0', '1', '0', '0', '0', '0', '1', '0', '1'},  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 263  Chapter 7  32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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  { { { { { { { {  '1', '1', '1', '1', '1', '1', '1', '1',  '0', '1', '0', '1', '0', '1', '0', '1',  '0', '1', '0', '0', '0', '1', '0', '1',  '0', '1', '1', '1', '0', '1', '0', '1',  '0', '0', '0', '0', '0', '1', '0', '1',  '1', '1', '1', '1', '0', '1', '0', '1',  '1', '0', '0', '0', '0', '0', '0', '1',  '1', '1', '1', '1', '0', '1', '1', '1',  '0', '0', '0', '0', '0', '1', '0', '1',  '1', '1', '1', '1', '1', '1', '0', '1',  '0', '0', '0', '0', '0', '0', '0', '1',  '0'}, '1'}, '1'}, '1'}, '1'}, '1'}, '1'}, '1' } };  mazeTraversal( maze, X_START, Y_START, RIGHT ); return 0; /* indicate successful termination */ } /* end main */ /* Assume that there is exactly 1 entrance and exactly 1 exit to the maze. */ void mazeTraversal( char maze[ 12 ][ 12 ], int xCoord, int yCoord, int direction ) { static int flag = 0; /* starting position flag */ maze[ xCoord ][ yCoord ] = 'X'; /* mark current point */ printMaze( maze ); /* if maze completed */ if ( coordsAreEdge( xCoord, yCoord ) && xCoord != X_START && yCoord != Y_START ) { printf( "\nMaze successfully exited!\n\n" ); return; } /* end if */ else if ( xCoord == X_START && yCoord == Y_START && flag == 1 ) { printf( "\nArrived back at the starting location.\n\n" ); return; } /* end else if */ else { /* make next move */ int move; /* next move */ int count; /* counter */ flag = 1; /* loop 4 times and find first valid move */ for ( move = direction, count = 0; count < 4; ++count, ++move, move %= 4 ) { /* choose valid move */ switch( move ) { case DOWN: /* move down */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, xCoord + 1, yCoord ) ) { mazeTraversal( maze, xCoord + 1, yCoord, LEFT ); return; } /* end if */ break; /* exit switch */ case RIGHT: /* move right */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  264 Pointers: Solutions  92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151  Chapter 7  /* if move is valid, call mazeTraversal */ if ( validMove( maze, xCoord, yCoord + 1 ) ) { mazeTraversal( maze, xCoord, yCoord + 1, DOWN ); return; } /* end if */ break; /* exit switch */ case UP: /* move up */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, xCoord - 1, yCoord ) ) { mazeTraversal( maze, xCoord - 1, yCoord, RIGHT ); return; } /* end if */ break; /* exit switch */ case LEFT: /* move left */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, xCoord, yCoord - 1 ) ) { /* move left mazeTraversal( maze, xCoord, yCoord - 1, UP ); return; } /* end if */  */  break; /* exit switch */ } /* end switch */ } /* end for */ } /* end else */ } /* end function mazeTraversal */ /* validate move */ int validMove( const char maze[][ 12 ], int r, int c ) { return ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != '1' ); } /* end function validMove */ /* function to check coordinates */ int coordsAreEdge( int x, int y ) { /* if coordinate is not valid if ( ( x == 0 || x == 11 ) && return 1; } /* end if */ else if ( ( y == 0 || y == 11 return 1; } /* end else if */ else { /* coordinate is valid return 0; } /* end else */  */ ( y >= 0 && y <= 11 ) ) {  ) && ( x >= 0 && x <= 11 ) ) {  */  } /* end function coordsAreEdge */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 265  Chapter 7  152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170  /* print the current state of the maze */ void printMaze( const char maze[][ 12 ] ) { int x; /* row counter */ int y; /* column counter */ /* iterate through the maze */ for ( x = 0; x < 12; x++ ) { for ( y = 0; y < 12; y++ ) { printf( "%c ", maze[ x ][ y ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\nHit return to see next move" ); getchar(); } /* end function printMaze */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  266 Pointers: Solutions  Chapter 7  Hit 1 1 1 X X X 1 1 1 X 1 1 1 X 1 1 1 X 1 1 1 X 1 1  return to 1 1 1 1 1 X X 1 X X 1 X 1 X 1 1 X 1 X X X X X 1 1 1 1 X 1 0 X 1 X 1 0 X 1 X 1 0 X X X X X 1 1 1 1 X X X X X X 1 1 1 1 1  see 1 1 X X 1 1 X X 1 X 1 X 1 X 1 X X X 1 1 1 0 1 1  next move 1 1 1 X X 1 1 0 1 1 0 1 1 0 0 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1  Hit 1 1 1 X X X 1 1 1 X 1 1 1 X 1 1 1 X 1 1 1 X 1 1  return to 1 1 1 1 1 X X 1 X X 1 X 1 X 1 1 X 1 X X X X X 1 1 1 1 X 1 0 X 1 X 1 0 X 1 X 1 0 X X X X X 1 1 1 1 X X X X X X 1 1 1 1 1  see 1 1 X X 1 1 X X 1 X 1 X 1 X 1 X X X 1 1 1 0 1 1  next move 1 1 1 X X 1 1 X 1 1 0 1 1 0 0 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1  return to 1 1 1 1 1 X X 1 X X 1 X 1 X 1 1 X 1 X X X X X 1 1 1 1 X 1 0 X 1 X 1 0 X 1 X 1 0 X X X X X 1 1 1 1 X X X X X X 1 1 1 1 1  see 1 1 X X 1 1 X X 1 X 1 X 1 X 1 X X X 1 1 1 X 1 1  next move 1 1 1 X X 1 1 X 1 1 X 1 1 X X 1 X 1 1 X 1 1 X 1 1 X 1 1 X 1 X X 1 1 1 1  ... Hit 1 1 1 X X X 1 1 1 X 1 1 1 X 1 1 1 X 1 1 1 X 1 1  Hit return to see next move Maze successfully exited!  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 267  Chapter 7  7.26 (Generating Mazes Randomly) Write a function mazeGenerator that takes as an argument a double-subscripted 12-by-12 character array and randomly produces a maze. The function should also provide the starting and ending locations of the maze. Try your function mazeTraverse from Exercise 7.25 using several randomly generated mazes. 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 53 54 55 56  /* Exercise 7.26 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define #define #define #define #define  DOWN 0 /* move down */ RIGHT 1 /* move right */ UP 2 /* move up */ LEFT 3 /* move left */ POSSIBLE_ZEROS 100 /* maximum possible zeroes */  /* function prototypes */ void mazeTraversal( char maze[ 12 ][ 12 ], const int xCoord, const int yCoord, int row, int col, int direction ); void mazeGenerator( char maze[][ 12 ], int *xPtr, int *yPtr ); void printMaze( const char maze[][ 12 ] ); int validMove( const char maze[][ 12 ], int r, int c ); int coordsAreEdge( int x, int y ); int main() { char maze[ 12 ][ 12 ]; /* maze grid */ int loop; /* row counter */ int loop2; /* column counter */ int xStart; /* starting x coordinate */ int yStart; /* starting y coordinate */ int x; /* current x coordinate */ int y; /* current y coordinate */ /* initialize maze grid to 1's */ for ( loop = 0; loop < 12; loop++ ) { for ( loop2 = 0; loop2 < 12; loop2++ ) { maze[ loop ][ loop2 ] = '1'; } /* end for */ } /* end for */ /* generate the maze */ mazeGenerator( maze, &xStart, &yStart ); x = xStart; /* starting row */ y = yStart; /* starting col */ mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); return 0; /* indicate successful termination */ } /* end main */ /* Assume that there is exactly 1 entrance and exactly 1 exit to the maze. */ void mazeTraversal( char maze[ 12 ][ 12 ], const int xCoord, const int yCoord, int row, int col, int direction ) { static int flag = 0; /* starting position flag */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  268 Pointers: Solutions  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 108 109 110 111 112 113 114 115 116 117  Chapter 7  maze[ row ][ col ] = 'X'; /* insert X at current location */ printMaze( maze ); /* if maze completed */ if ( coordsAreEdge( row, col ) && row != xCoord && col != yCoord ) { printf( "\nMaze successfully exited!\n\n" ); return; } /* end if */ else if ( row == xCoord && col == yCoord && flag == 1 ) { printf( "\nArrived back at the starting location.\n\n" ); return; } /* end else if */ else { /* make next move */ int move; /* next move */ int count; /* counter */ flag = 1; /* loop 4 times and find first valid move */ for ( move = direction, count = 0; count < 4; ++count, ++move, move %= 4 ) { /* choose valid move */ switch( move ) { case DOWN: /* move down */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row + 1, col ) ) { mazeTraversal( maze, xCoord, yCoord, row + 1, col, LEFT ); return; } /* end if */ break; /* exit switch */ case RIGHT: /* move right */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row, col + 1 ) ) { mazeTraversal( maze, xCoord, yCoord, row, col + 1, DOWN ); return; } /* end if */ break; /* exit switch */ case UP: /* move up */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row - 1, col ) ) { mazeTraversal( maze, xCoord, yCoord, row - 1, col, RIGHT ); return; } /* end if */ break; /* exit switch */ case LEFT: /* move left */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 269  Chapter 7  118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178  /* if move is valid, call mazeTraversal */ if ( validMove( maze, row, col - 1 ) ) { mazeTraversal( maze, xCoord, yCoord, row, col - 1, UP ); return; } /* end if */ break; /* exit switch */ } /* end switch */ } /* end for */ } /* end else */ } /* end function mazeTraversal */ /* validate move */ int validMove( const char maze[][ 12 ], int r, int c ) { return ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != '1' ); } /* end function validMove */ /* check boundaries of coordinates */ int coordsAreEdge( int x, int y ) { /* if coordinates not if ( ( x == 0 || x == return 1; } /* end if */ else if ( ( y == 0 || return 1; } /* end else if */ else { /* coordinates return 0; } /* end else */  valid */ 11 ) && ( y >= 0 && y <= 11 ) ) {  y == 11 ) && ( x >= 0 && x <= 11 ) ) {  valid */  } /* end function coordsAreEdge */ /* print the maze */ void printMaze( const char maze[][ 12 ] ) { int x; /* row counter */ int y; /* column counter */ /* loop through maze grid */ for ( x = 0; x < 12; x++ ) { for ( y = 0; y < 12; y++ ) { printf( "%c ", maze[ x ][ y ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\nHit return to see next move" ); getchar(); } /* end function printMaze */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  270 Pointers: Solutions  179 /* random maze generator */ 180 void mazeGenerator( char maze[][ 12 ], int *xPtr, int *yPtr ) 181 { 182 int a; /* random number */ 183 int x; /* random number */ 184 int y; /* random number */ 185 int entry; /* random entry */ 186 int exit; /* random exit */ 187 int loop; /* loop counter */ 188 189 srand( time( NULL ) ); 190 191 /* generate random entry and exit positions */ 192 do { 193 entry = rand() % 4; 194 exit = rand() % 4; 195 } while ( entry == exit ); /* end do...while */ 196 197 /* Determine entry position while avoiding corners */ 198 if ( entry == 0 ) { 199 *xPtr = 1 + rand() % 10; 200 *yPtr = 0; 201 maze[ *xPtr ][ 0 ] = '0'; 202 } /* end if */ 203 else if ( entry == 1 ) { 204 *xPtr = 0; 205 *yPtr = 1 + rand() % 10; 206 maze[ 0 ][ *yPtr ] = '0'; 207 } /* end else if */ 208 else if ( entry == 2 ) { 209 *xPtr = 1 + rand() % 10; 210 *yPtr = 11; 211 maze[ *xPtr ][ 11 ] = '0'; 212 } /* end else if */ 213 else { 214 *xPtr = 11; 215 *yPtr = 1 + rand() % 10; 216 maze[ 11 ][ *yPtr ] = '0'; 217 } /* end else */ 218 219 /* Determine exit location */ 220 if ( exit == 0 ) { 221 a = 1 + rand() % 10; 222 maze[ a ][ 0 ] = '0'; 223 } /* end if */ 224 else if ( exit == 1 ) { 225 a = 1 + rand() % 10; 226 maze[ 0 ][ a ] = '0'; 227 } /* end else if */ 228 else if ( exit == 2 ) { 229 a = 1 + rand() % 10; 230 maze[ a ][ 11 ] = '0'; 231 } /* end else if */ 232 else { 233 a = 1 + rand() % 10; 234 maze[ 11 ][ a ] = '0'; 235 } /* end else */ 236 237 /* randomly add zeroes to maze grid */ 238 for ( loop = 1; loop < POSSIBLE_ZEROS; loop++ ) { 239 x = 1 + rand() % 10;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 271  Chapter 7  240 y = 1 + rand() % 10; 241 maze[ x ][ y ] = '0'; 242 } /* end for */ 243 244 } /* end function mazeGenerator */ Hit 1 1 1 0 1 1 X X 1 X 1 X 1 1 1 1 1 X 1 1 1 1 1 1  return to 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1 1 0 0 1 X X X 1 X X 1 X X X 1 X 1 X X X X X X X 1 X 0 0 X 1 X 0 1 X 1 X X X X X 1 1 1 1 1  see 1 1 1 X 1 1 X X 1 X 0 1 1 X 1 X X X X X 1 1 1 1  next move 1 1 1 X X 1 1 X 1 X X 1 X 1 1 X 1 1 X 1 1 1 0 1 X 1 1 1 0 1 0 0 1 1 1 1  Hit 1 1 1 0 1 1 X X 1 X 1 X 1 1 1 1 1 X 1 1 1 1 1 1  return to 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1 1 0 0 1 X X X 1 X X 1 X X X 1 X 1 X X X X X X X 1 X 0 0 X 1 X 0 1 X 1 X X X X X 1 1 1 1 1  see 1 1 1 X 1 1 X X 1 X 0 1 1 X 1 X X X X X 1 1 1 1  next move 1 1 1 X X 1 1 X 1 X X 1 X 1 1 X 1 1 X 1 1 1 0 1 X 1 1 1 0 1 0 0 1 1 1 1  return to 1 1 X 1 1 1 1 X 1 0 1 0 X X 1 1 X X 1 X X X 1 X X 1 X X X 1 X 1 X X X X X X X 1 X 0 0 X 1 X 0 1 X 1 X X X X X 1 1 1 1 1  see 1 1 1 X 1 1 X X 1 X 0 1 1 X 1 X X X X X 1 1 1 1  next move 1 1 1 X X 1 1 X 1 X X 1 X 1 1 X 1 1 X 1 1 1 0 1 X 1 1 1 0 1 0 0 1 1 1 1  ... Hit 1 1 1 0 1 1 X X 1 X 1 X 1 1 1 1 1 X 1 1 1 1 1 1  Hit return to see next move Maze successfully exited!  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  272 Pointers: Solutions  Chapter 7  7.27 (Mazes of Any Size) Generalize functions mazeTraverse and mazeGenerator of Exercise 7.25 and Exercise 7.26 to process mazes of any width and height. 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 53 54 55 56 57  /* Exercise 7.27 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define #define #define #define #define #define  ROW 10 COL 10 DOWN 0 RIGHT 1 UP 2 LEFT 3  /* /* /* /* /* /*  height */ width */ move down */ move right */ move up */ move left */  /* function prototypes */ void mazeTraversal( char maze[ ROW ][ COL ], const int xCoord, const int yCoord, int row, int col, int direction ); void mazeGenerator( char maze[][ COL ], int *xPtr, int *yPtr ); void printMaze( const char maze[][ COL ] ); int validMove( const char maze[][ COL ], int r, int c ); int coordsAreEdge( int x, int y ); int main() { char maze[ ROW ][ COL ]; /* maze grid */ int loop; /* row counter */ int loop2; /* column counter */ int xStart; /* starting x coordinate */ int yStart; /* starting y coordinate */ int x; /* current x coordinate */ int y; /* current y coordinate */ /* initialize maze grid to 1's */ for ( loop = 0; loop < ROW; loop++ ) { for ( loop2 = 0; loop2 < COL; loop2++ ) { maze[ loop ][ loop2 ] = '1'; } /* end for */ } /* end for */ /* generate the maze */ mazeGenerator( maze, &xStart, &yStart ); x = xStart; /* starting row */ y = yStart; /* starting col */ mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); return 0; /* indicate successful termination */ } /* end main */ /* Assume that there is exactly 1 entrance and exactly 1 exit to the maze. */ void mazeTraversal( char maze[ ROW ][ COL ], const int xCoord, const int yCoord, int row, int col, int direction ) { static int flag = 0; /* starting position flag */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 273  Chapter 7  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 108 109 110 111 112 113 114 115 116 117 118  maze[ row ][ col ] = 'X'; /* insert X at current location */ printMaze( maze ); /* if maze completed */ if ( coordsAreEdge( row, col ) && row != xCoord && col != yCoord ) { printf( "\nMaze successfully exited!\n\n" ); return; } /* end if */ else if ( row == xCoord && col == yCoord && flag == 1 ) { printf( "\nArrived back at the starting location.\n\n" ); return; } /* end else if */ else { /* make next move */ int move; /* next move */ int count; /* counter */ flag = 1; /* loop 4 times and find first valid move */ for ( move = direction, count = 0; count < 4; ++count, ++move, move %= 4 ) { /* choose valid move */ switch( move ) { case DOWN: /* move down */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row + 1, col ) ) { mazeTraversal( maze, xCoord, yCoord, row + 1, col, LEFT ); return; } /* end if */ break; /* exit switch */ case RIGHT: /* move right */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row, col + 1 ) ) { mazeTraversal( maze, xCoord, yCoord, row, col + 1, DOWN ); return; } /* end if */ break; /* exit switch */ case UP: /* move up */ /* if move is valid, call mazeTraversal */ if ( validMove( maze, row - 1, col ) ) { mazeTraversal( maze, xCoord, yCoord, row - 1, col, RIGHT ); return; } /* end if */ break; /* exit switch */ case LEFT: /* move left */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  274 Pointers: Solutions  119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179  Chapter 7  /* if move is valid, call mazeTraversal */ if ( validMove( maze, row, col - 1 ) ) { mazeTraversal( maze, xCoord, yCoord, row, col - 1, UP ); return; } /* end if */ break; /* exit switch */ } /* end switch */ } /* end for */ } /* end else */ } /* end function mazeTraversal */ /* validate move */ int validMove( const char maze[][ COL ], int r, int c ) { return ( r >= 0 && r <= ROW - 1 && c >= 0 && c <= COL - 1 && maze[ r ][ c ] != '1' ); /* a valid move */ } /* end function validMove */ /* check boundaries of coordinates */ int coordsAreEdge( int x, int y ) { /* if coordinates not if ( ( x == 0 || x == return 1; } /* end if */ else if ( ( y == 0 || x <= ROW - 1 ) ) { return 1; } /* end else if */ else { /* coordinates return 0; } /* end else */  valid */ ROW - 1 ) && ( y >= 0 && y <= COL - 1 ) ) {  y == COL - 1 ) && ( x >= 0 &&  valid */  } /* end function coordsAreEdge */ /* print the maze */ void printMaze( const char maze[][ COL ] ) { int x; /* row counter */ int y; /* column counter */ /* loop through maze grid */ for ( x = 0; x < ROW; x++ ) { for ( y = 0; y < COL; y++ ) { printf( "%c ", maze[ x ][ y ] ); } /* end for */ printf( "\n" ); } /* end for */ printf( "\nHit return to see next move" ); getchar(); } /* end function printMaze */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 275  Chapter 7  180 181 /* random maze generator */ 182 void mazeGenerator( char maze[][ COL ], int *xPtr, int *yPtr ) 183 { 184 int a; /* random number */ 185 int x; /* random number */ 186 int y; /* random number */ 187 int entry; /* random entry */ 188 int exit; /* random exit */ 189 int loop; /* loop counter */ 190 191 srand( time( NULL ) ); 192 193 /* generate random entry and exit positions */ 194 do { 195 entry = rand() % 4; 196 exit = rand() % 4; 197 } while ( entry == exit ); /* end do...while */ 198 199 /* Determine entry position while avoiding corners */ 200 if ( entry == 0 ) { 201 *xPtr = 1 + rand() % ( ROW - 2 ); 202 *yPtr = 0; 203 maze[ *xPtr ][ *yPtr ] = '0'; 204 } /* end if */ 205 else if ( entry == 1 ) { 206 *xPtr = 0; 207 *yPtr = 1 + rand() % ( COL - 2 ); 208 maze[ *xPtr ][ *yPtr ] = '0'; 209 } /* end else if */ 210 else if ( entry == 2 ) { 211 *xPtr = 1 + rand() % ( ROW - 2 ); 212 *yPtr = COL - 1; 213 maze[ *xPtr ][ *yPtr ] = '0'; 214 } /* end else if */ 215 else { 216 *xPtr = ROW - 1; 217 *yPtr = 1 + rand() % ( COL - 2 ); 218 maze[ *xPtr ][ *yPtr ] = '0'; 219 } /* end else */ 220 221 /* Determine exit location */ 222 if ( exit == 0 ) { 223 a = 1 + rand() % ( ROW - 2 ); 224 maze[ a ][ 0 ] = '0'; 225 } /* end if */ 226 else if ( exit == 1 ) { 227 a = 1 + rand() % ( COL - 2 ); 228 maze[ 0 ][ a ] = '0'; 229 } /* end else if */ 230 else if ( exit == 2 ) { 231 a = 1 + rand() % ( ROW - 2 ); 232 maze[ a ][ COL - 1 ] = '0'; 233 } /* end else if */ 234 else { 235 a = 1 + rand() % ( COL - 2 ); 236 maze[ ROW - 1 ][ a ] = '0'; 237 } /* end else */ 238 239 /* randomly add zeroes to maze grid */ 240 for ( loop = 1; loop < ( ROW - 2 ) * ( COL - 2 ); loop++ ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  276 Pointers: Solutions  Chapter 7  241 x = 1 + rand() % ( ROW - 2 ); 242 y = 1 + rand() % ( COL - 2 ); 243 maze[ x ][ y ] = '0'; 244 } /* end for */ 245 246 } /* end function mazeGenerator */ 1 1 0 1 1 1 1 1 1 1  1 0 0 0 1 1 0 0 0 1  Hit 1 1 1 0 0 0 1 0 1 1 1 1 1 0 1 0 1 0 1 1  X 0 0 0 1 1 0 0 0 1  1 1 1 0 0 0 0 0 0 1  1 1 1 0 0 1 1 1 0 1  1 0 1 0 0 0 0 1 1 1  1 1 1 1 1 1 0 0 1 1  1 0 1 0 0 1 1 0 0 1  1 0 0 1 0 0 0 0 0 1  1 1 1 1 1 1 1 1 1 1  return to X 1 1 1 1 X 1 1 0 1 0 1 1 1 1 0 0 0 0 1 1 0 0 0 1 1 0 1 0 1 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 1 1 1 1 1  see 1 1 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 1 1  next move 1 1 1 1 1 1 1 1 1 1  return to X 1 1 1 1 X 1 1 0 1 0 1 1 1 1 0 0 0 0 1 1 0 0 0 1 1 0 1 0 1 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 1 1 1 1 1  see 1 1 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 1 1  next move 1 1 1 1 1 1 1 1 1 1  ... Hit 1 1 1 X X X 1 0 1 1 1 1 1 0 1 0 1 0 1 1  Hit return to see next move Maze successfully exited!  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Pointers: Solutions 277  Chapter 7  7.28 (Arrays of Pointers to Functions) Rewrite the program of Fig. 6.22 to use a menu driven interface. The program should offer the user four options as follows:  Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program  One restriction on using arrays of pointers to functions is that all the pointers must have the same type. The pointers must be to functions of the same return type that receive arguments of the same type. For this reason, the functions in Fig. 6.22 must be modified so that they each return the same type and take the same parameters. Modify functions minimum and maximum to print the minimum or maximum value and return nothing. For option 3, modify function average of Fig. 6.22 to output the average for each student (not a specific student). Function average should return nothing and take the same parameters as printArray, minimum and maximum. Store the pointers to the four functions in array processGrades and use the choice made by the user as the subscript into the array for calling each function. 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  /* Exercise 7.28 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define STUDENTS 3 #define EXAMS 4 /* function prototypes */ void minimum( int grades[][ EXAMS ], void maximum( int grades[][ EXAMS ], void average( int grades[][ EXAMS ], void printArray( int grades[][ EXAMS void printMenu( void );  int pupils, int tests ); int pupils, int tests ); int pupils, int tests ); ], int pupils, int tests );  int main() { /* pointer to a function that takes as parameters a two-dimensional array and two integer values */ void ( *processGrades[ 4 ] )( int [][ EXAMS ], int, int ) = { printArray, minimum, maximum, average}; int choice = 0; /* menu choice */ /* array of student grades */ int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; /* loop while user does not choose option 4 */ while ( choice != 4 ) { /* display menu and read user's choice */ do { printMenu(); scanf( "%d", &choice ); } while ( choice < 0 || choice > 4 ); /* end do...while */ /* pass choice into the array */ if ( choice != 4 ) { ( *processGrades[ choice ] )( studentGrades, STUDENTS, EXAMS ); } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  278 Pointers: Solutions  41 42 43 44 45 46 47 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 92 93 94 95 96 97 98 99 100  else { printf( "Program Ended.\n" ); } /* end else */ } /* end while */ return 0; /* indicate successful termination */ } /* end main */ /* search for the minimum value */ void minimum( int grades[][ EXAMS ], int pupils, int tests ) { int i; /* loop counter */ int j; /* loop counter */ int lowGrade = 100; /* set lowGrade to highest possible score */ /* loop through rows */ for ( i = 0; i <= pupils - 1; i++ ) { /* loop through columns */ for ( j = 0; j <= tests - 1; j++ ) { /* if current grade is lower than lowGrade */ if ( grades[ i ][ j ] < lowGrade ) { lowGrade = grades[ i ][ j ]; } /* end if */ } /* end for */ } /* end for */ printf( "\n\tThe lowest grade is %d\n", lowGrade ); } /* end function minimum */ /* search for maximum value */ void maximum( int grades[][ EXAMS ], int pupils, int tests ) { int i; /* loop counter */ int j; /* loop counter */ int highGrade = 0; /* set highGrade to lowest possible score */ /* loop through rows */ for ( i = 0; i <= pupils - 1; i++ ) { /* loop through columns */ for ( j = 0; j <= tests - 1; j++ ) { /* if current grade is higher than highGrade */ if ( grades[ i ][ j ] > highGrade ) { highGrade = grades[ i ][ j ]; } /* end if */ } /* end for */ } /* end for */ printf( "\n\tThe highest grade is %d\n", highGrade ); } /* end function maximum */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 279  Chapter 7  101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158  /* calculate average */ void average( int grades[][ EXAMS ], int pupils, int tests ) { int i; /* loop counter */ int j; /* loop counter */ int total; /* sum of all grades */ printf( "\n" ); /* loop through rows */ for ( i = 0; i <= pupils - 1; i++ ) { total = 0; /* loop through columns */ for ( j = 0; j <= tests - 1; j++ ) { total += grades[ i ][ j ]; } /* end for */ printf( "\tThe average for student %d is %.1f\n", i + 1, ( double ) total / tests ); } /* end for */ } /* end function average */ /* print the contents of the array */ void printArray( int grades[][ EXAMS ], int pupils, int tests ) { int i; /* loop counter */ int j; /* loop counter */ printf( "\n\t  [ 0 ]  [ 1 ]  [ 2 ]  [ 3 ]" );  /* loop through rows */ for ( i = 0; i <= pupils - 1; i++ ) { printf( "\n\tstudentGrades[ %d ] ", i ); /* loop through columns */ for ( j = 0; j <= tests - 1; j++ ) { printf( "%-7d", grades[ i ][ j ] ); } /* end for */ } /* end for */ printf( "\n" ); } /* end function printArray */ /* display the menu */ void printMenu( void ) { printf( "\n\tEnter a choice:\n" "\t 0 Print the array of grades\n" "\t 1 Find the minimum grade\n" "\t 2 Find the maximum grade\n" "\t 3 Print the average on all" " tests for each student\n" "\t 4 End program\n" "\t? " ); } /* end function printMenu */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  280 Pointers: Solutions  Chapter 7  Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program ? 0 [ 0 ] studentGrades[ 0 ] 77 studentGrades[ 1 ] 96 studentGrades[ 2 ] 70  [ 1 ] 68 87 90  [ 2 ] 86 89 86  [ 3 ] 73 78 81  Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program ? 1 The lowest grade is 68 Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program ? 2 The highest grade is 96 Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program ? 3 The average for student 1 is 76.0 The average for student 2 is 87.5 The average for student 3 is 81.8 Enter a choice: 0 Print the array of grades 1 Find the minimum grade 2 Find the maximum grade 3 Print the average on all tests for each student 4 End program ? 4 Program Ended.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 7  Pointers: Solutions 281  7.29 (Modifications to the Simpletron Simulator) In Exercise 7.19, you wrote a software simulation of a computer that executes programs written in Simpletron Machine Language (SML). In this exercise, we propose several modifications and enhancements to the Simpletron Simulator. In Exercises 12.26 and 12.27, we propose building a compiler that converts programs written in a highlevel programming language (a variation of BASIC) to Simpletron Machine Language. Some of the following modifications and enhancements may be required to execute the programs produced by the compiler. a) Extend the Simpletron Simulator's memory to contain 1000 memory locations to enable the Simpletron to handle larger programs. b) Allow the simulator to perform remainder calculations. This requires an additional Simpletron Machine Language instruction. c) Allow the simulator to perform exponentiation calculations. This requires an additional Simpletron Machine Language instruction. d) Modify the simulator to use hexadecimal values rather than integer values to represent Simpletron Machine Language instructions. e) Modify the simulator to allow output of a newline. This requires an additional Simpletron Machine Language instruction. f) Modify the simulator to process floating-point values in addition to integer values. g) Modify the simulator to handle string input. [Hint: Each Simpletron word can be divided into two groups, each holding a two-digit integer. Each two-digit integer represents the ASCII decimal equivalent of a character. Add a machine language instruction that will input a string and store the string beginning at a specific Simpletron memory location. The first half of the word at that location will be a count of the number of characters in the string (i.e., the length of the string). Each succeeding half word contains one ASCII character expressed as two decimal digits. The machine language instruction converts each character into its ASCII equivalent and assigns it to a half word.] h) Modify the simulator to handle output of strings stored in the format of part (g). [Hint: Add a machine language instruction that prints a string beginning at a specified Simpletron memory location. The first half of the word at that location is the length of the string in characters. Each succeeding half word contains one ASCII character expressed as two decimal digits. The machine language instruction checks the length and prints the string by translating each twodigit number into its equivalent character.]  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  282 Pointers: Solutions  7.30 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  Chapter 7  What does this program do? /* ex07_30.c */ /* What does this program do? */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int mystery3( const char *s1, const char *s2 ); /* prototype */ int main() { char string1[ 80 ]; /* create char array */ char string2[ 80 ]; /* create char array */ printf( "Enter two strings: " ); scanf( "%s%s", string1 , string2 ); printf( "The result is %d\n", mystery3( string1, string2 ) ); return 0; /* indicates successful termination */ } /* end main */ int mystery3( const char *s1, const char *s2 ) { for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) { if ( *s1 != *s2 ) { return 0; } /* end if */ } /* end for */ return 1; } /* end function mystery3 */  ANS: The Program compares two strings, element by element, for equality.  Enter two strings: The result is 0  string1 string2  Enter two strings: The result is 1  string2 string2  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  8 C Characters and Strings: Solutions  SOLUTIONS 8.5 Write a program that inputs a character from the keyboard and tests the character with each of the functions in the character handling library. The program should print the value returned by each function. 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  /* Exercise 8.5 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int c; /* character input by user */ printf( "Enter a character: " ); c = getchar(); /* test printf( printf( printf( printf( printf( printf( printf( printf( printf( printf( printf( printf( printf(  each function of the character handling library */ "isdigit( \'%c\' ) = %d\n", c, isdigit( c ) ); "isalpha( \'%c\' ) = %d\n", c, isalpha( c ) ); "isalnum( \'%c\' ) = %d\n", c, isalnum( c ) ); "isxdigit( \'%c\' ) = %d\n", c, isxdigit( c ) ); "islower( \'%c\' ) = %d\n", c, islower( c ) ); "isupper( \'%c\' ) = %d\n", c, isupper( c ) ); "tolower( \'%c\' ) = %d\n", c, tolower( c ) ); "toupper( \'%c\' ) = %d\n", c, toupper( c ) ); "isspace( \'%c\' ) = %d\n", c, isspace( c ) ); "iscntrl( \'%c\' ) = %d\n", c, iscntrl( c ) ); "ispunct( \'%c\' ) = %d\n", c, ispunct( c ) ); "isprint( \'%c\' ) = %d\n", c, isprint( c ) ); "isgraph( \'%c\' ) = %d\n", c, isgraph( c ) );  return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  284 C Characters and Strings: Solutions  Chapter 8  Enter a character: h isdigit( 'h' ) = 0 isalpha( 'h' ) = 2 isalnum( 'h' ) = 2 isxdigit( 'h' ) = 0 islower( 'h' ) = 2 isupper( 'h' ) = 0 tolower( 'h' ) = 104 toupper( 'h' ) = 72 isspace( 'h' ) = 0 iscntrl( 'h' ) = 0 ispunct( 'h' ) = 0 isprint( 'h' ) = 2 isgraph( 'h' ) = 2  8.6 Write a program that inputs a line of text with function gets into char array s[ 100 ]. Output the line in uppercase letters and in lowercase letters. 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  /* Exercise 8.6 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { char s[ 100 ]; /* define character array of size 100 */ int i; /* loop counter */ /* use gets to get text from user */ printf( "Enter a line of text:\n" ); gets( s ); printf( "\nThe line in uppercase is:\n" ); /* convert each character to uppercase and output */ for ( i = 0; s[ i ] != '\0'; i++ ) { printf( "%c", toupper( s[ i ] ) ); } /* end for */ printf( "\n\nThe line in lowercase is:\n" ); /* convert each character to lowercase and output */ for ( i = 0; s[ i ] != '\0'; i++ ) { printf( "%c", tolower( s[ i ] ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter a line of text: A line with UPPER- and lowercase LeTters The line in uppercase is: A LINE WITH UPPER- AND LOWERCASE LETTERS The line in lowercase is: a line with upper- and lowercase letters  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 285  Chapter 8  8.7 Write a program that inputs four strings that represent integers, converts the strings to integers, sums the values and prints the total of the four values. 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  /* Exercise 8.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char stringValue[ 6 ]; /* integer string input by user */ int sum = 0; /* result of four integers */ int i; /* loop counter */ /* loop 4 times */ for ( i = 1; i <= 4; i++ ) { printf( "Enter an integer string: " ); scanf( "%s", stringValue ); /* atoi converts stringValue to integer */ sum += atoi( stringValue ); } /* end for */ printf( "\nThe total of the values is %d\n", sum ); return 0; /* indicate successful termination */ } /* end main */  Enter Enter Enter Enter  an an an an  integer integer integer integer  string: string: string: string:  43 77 120 9999  The total of the values is 10239  8.8 Write a program that inputs four strings that represent floating-point values, converts the strings to double values, sums the values and prints the total of the four values. 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  /* Exercise 8.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { char stringValue[ 15 ]; /* string input by user */ double sum = 0.0; /* sum of all four values */ int i; /* loop counter */ /* loop 4 times */ for ( i = 1; i <= 4; i++ ) { printf( "Enter a doubleing point string: " ); gets( stringValue ); /* atof converts stringValue to a floating-point value */ sum += atof( stringValue ); } /* end for */ printf( "\nThe total of the values is %f\n", sum ); return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  286 C Characters and Strings: Solutions  Enter Enter Enter Enter  a a a a  doubleing doubleing doubleing doubleing  point point point point  string: string: string: string:  Chapter 8  1.2 2.3 3.4 4.5  The total of the values is 11.400000  8.9 Write a program that uses function strcmp to compare two strings input by the user. The program should state whether the first string is less than, equal to or greater than the second string. 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  /* Exercise 8.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char string1[ 20 ]; /* first string input by user */ char string2[ 20 ]; /* second string input by user */ int result; /* result of comparing two strings */ printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); /* read two strings */ result = strcmp( string1, string2 ); /* display appropriate message for result */ if ( result > 0 ) { printf( "\"%s\" is greater than \"%s\"\n", string1, string2 ); } /* end if */ else if ( result == 0 ) { printf( "\"%s\" is equal to \"%s\"\n", string1, string2 ); } /* end else if */ else { printf( "\"%s\" is less than \"%s\"\n", string1, string2 ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  Enter two strings: Greg Dave "Greg" is greater than "Dave"  Enter two strings: Bill Bill "Bill" is equal to "Bill"  Enter two strings: Pete Tim "Pete" is less than "Tim"  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 287  Chapter 8  8.10 Write a program that uses function strncmp to compare two strings input by the user. The program should input the number of characters to be compared. The program should state whether the first string is less than, equal to or greater than the second string. 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  /* Exercise 8.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { char string1[ 20 ]; char string2[ 20 ]; int result; int compareCount;  /* /* /* /*  first string input by user */ second string input by user */ result of using strncmp */ how many characters to be compared */  /* get two strings from user */ printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); /* get number of characters to compare */ printf( "How many characters should be compared: " ); scanf( "%d", &compareCount ); result = strncmp( string1, string2, compareCount ); /* display appropriate message for result */ if ( result > 0 ) { printf( "\"%s\" is greater than \"%s\" up to %d characters\n", string1, string2, compareCount ); } /* end if */ else if ( result == 0 ) { printf( "\"%s\" is equal to \"%s\" up to %d characters\n", string1, string2, compareCount ); } /* end else if */ else { printf( "\"%s\" is less than \"%s\" up to %d characters\n", string1, string2, compareCount ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  Enter two strings: ABCDEFG ABCDEFH How many characters should be compared: 6 "ABCDEFG" is less than "ABCDEFH" up to 6 characters  Enter two strings: ABCDEFG ABCDEFH How many characters should be compared: 7 "ABCDEFG" is less than "ABCDEFH" up to 7 characters  Enter two strings: ABCEFG ABCDFG How many characters should be compared: 4 "ABCEFG" is greater than "ABCDFG" up to 4 characters  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  288 C Characters and Strings: Solutions  Chapter 8  8.11 Write a program that uses random number generation to create sentences. The program should use four arrays of pointers to char called article, noun, verb and preposition. The program should create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, it should be concatenated to the previous words in an array large enough to hold the entire sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 such sentences. The arrays should be filled as follows: The article array should contain the articles "the", "a", "one", "some" and "any"; the noun array should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array should contain the prepositions "to", "from", "over", "under" and "on". After the preceding program is written and working, modify the program to produce a short story consisting of several of these sentences. (How about the possibility of a random term paper writer?) 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  /* Exercise 8.11 Solution */ #include #include #include #include #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { /* initialize 4 arrays of char pointers */ char *article[] = { "the", "a", "one", "some", "any" }; char *noun[] = { "boy", "girl", "dog", "town", "car" }; char *verb[] = { "drove", "jumped", "ran", "walked", "skipped" }; char *preposition[] = { "to", "from", "over", "under", "on" }; char sentence[ 100 ] = ""; /* completed sentence */ int i; /* loop counter */ /* create 20 sentences */ for ( i = 1; i <= 20; i++ ) { /* randomly choose pieces of sentence */ strcat( sentence, article[ rand() % 5 ] ); strcat( sentence, " " ); strcat( sentence, noun[ rand() % 5 ] ); strcat( sentence, " " ); strcat( sentence, verb[ rand() % 5 ] ); strcat( sentence, " " ); strcat( sentence, preposition[ rand() % 5 ] ); strcat( sentence, " " ); strcat( sentence, article[ rand() % 5 ] ); strcat( sentence, " " ); strcat( sentence, noun[ rand() % 5 ] ); /* capitalize first letter and print sentence */ putchar( toupper( sentence[ 0 ] ) ); printf( "%s.\n", &sentence[ 1 ] ); sentence[ 0 ] = '\0'; } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 289  Chapter 8  A dog skipped to any car. Some town ran on the boy. A dog jumped from the dog. One girl jumped on one town. One dog jumped from some boy. One girl jumped under any dog. One car drove on some girl. One town walked on a girl. Some town ran on one dog. One car walked from any town. A boy drove over some girl. The dog skipped under a boy. The car drove to a girl. Some town skipped under any car. A boy jumped from a town. Any car jumped under one town. Some dog skipped from some boy. Any town skipped to one girl. Some girl jumped to any dog. The car ran under one dog.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  290 C Characters and Strings: Solutions  Chapter 8  8.12 (Limericks) A limerick is a humorous five-line verse in which the first and second lines rhyme with the fifth, and the third line rhymes with the fourth. Using techniques similar to those developed in Exercise 8.11, write a program that produces random limericks. Polishing this program to produce good limericks is a challenging problem, but the result will be worth the effort! 8.13 Write a program that encodes English language phrases into pig Latin. Pig Latin is a form of coded language often used for amusement. Many variations exist in the methods used to form pig Latin phrases. For simplicity, use the following algorithm: To form a pig Latin phrase from an English language phrase, tokenize the phrase into words with function strtok. To translate each English word into a pig Latin word, place the first letter of the English word at the end of the English word, and add the letters "ay." Thus the word "jump" becomes "umpjay," the word "the" becomes "hetay" and the word "computer" becomes "omputercay." Blanks between words remain as blanks. Assume the following: The English phrase consists of words separated by blanks, there are no punctuation marks, and all words have two or more letters. Function printLatinWord should display each word. [Hint: Each time a token is found in a call to strtok, pass the token pointer to function printLatinWord, and print the pig Latin word.] 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  /* Exercise 8.13 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  void printLatinWord( char *word ); /* function prototype */ int main() { char sentence[ 80 ]; /* sentence input by user */ char *tokenPtr; /* pointer to current token */ printf( "Enter a sentence:\n" ); gets( sentence ); printf( "\nThe sentence in Pig Latin is:\n" ); /* call function strtok to alter the sentence */ tokenPtr = strtok( sentence, " .,;" ); /* if tokenPtr does not equal NULL */ while ( tokenPtr ) { /* pass the token to printLatinWord and get next token */ printLatinWord( tokenPtr ); tokenPtr = strtok( NULL, " .,;" ); /* if tokenPtr not NULL, print space */ if ( tokenPtr ) { printf( " " ); } /* end if */ } /* end while */ printf( "." ); return 0; /* indicates successful termination */ } /* end main */ /* print out the English word in pig Latin form */ void printLatinWord( char *word ) { unsigned int i; /* loop counter */ /* loop through the word */ for ( i = 1; i < strlen( word ); i++ ) { printf( "%c", word[ i ] ); } /* end for */ printf( "%c%s", word[ 0 ], "ay" ); } /* end function printLatinWord */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 291  Chapter 8  Enter a sentence: characters and strings The sentence in Pig Latin is: haracterscay ndaay tringssay.  8.14  Write a program that inputs a telephone number as a string in the form (555) 555-5555. The program should use function strtok to extract the area code as a token, the first three digits of the phone number as a token and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string. The program should convert the area-code string to int and convert the phone number string to long. Both the area code and the phone number should be printed. 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  /* Exercise 8.14 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char p[ 20 ]; /* complete phone number */ char phoneNumber[ 10 ] = { '\0' }; /* long integer phone number */ char *tokenPtr; /* store temporary token */ int areaCode; /* store area code */ long phone; /* store phone number */ printf( "Enter a phone number in the form ( 555 )" " 555-5555:\n" ); gets( p ); /* convert area code token to an integer */ areaCode = atoi( strtok( p, "()" ) ); /* take next token and copy to phoneNumber */ tokenPtr = strtok( NULL, " -" ); strcpy( phoneNumber, tokenPtr ); /* take last token and concatenate to phoneNumber */ tokenPtr = strtok( NULL, "" ); strcat( phoneNumber, tokenPtr ); /* convert phoneNumber to long integer */ phone = atol( phoneNumber ); printf( "\nThe integer area code is %d\n", areaCode ); printf( "The long integer phone number is %ld\n", phone ); return 0; /* indicate successful termination */ } /* end main */  Enter a phone number in the form ( 555 ) 555-5555: (800) 555-1212 The integer area code is 800 The long integer phone number is 5551212  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  292 C Characters and Strings: Solutions  8.15  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  Chapter 8  Write a program that inputs a line of text, tokenizes the line with function strtok and outputs the tokens in reverse order.. ANS: /* Exercise 8.15 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      void reverseTokens( char *sentence ); /* function prototype */ int main() { char text[ 80 ]; /* line of text from user */ printf( "Enter a line of text:\n" ); gets( text ); reverseTokens( text ); /* call to function reverseTokens */ return 0; /* indicate successful termination */ } /* end main */ /* function to reverse the individual tokens */ void reverseTokens( char *sentence ) { char *pointers[ 50 ]; /* array to store entire sentence */ char *temp; /* pointer to each token */ int count = 0; /* token counter */ int i; /* loop counter */ /* function strtok takes first word of sentence */ temp = strtok( sentence, " " ); /* while temp does not equal NULL */ while ( temp ) { /* add the word into the array and get next token */ pointers[ count++ ] = temp; temp = strtok( NULL, " " ); } /* end while */ printf( "The tokens in reverse order are:\n" ); /* loop through the array backwards */ for ( i = count - 1; i >= 0; i-- ) { printf( "%s ", pointers[ i ] ); } /* end for */ } /* end function reverseTokens */  Enter a line of text: testing 1 2 3 The tokens in reverse order are: 3 2 1 testing  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 293  Chapter 8  8.16 Write a program that inputs a line of text and a search string from the keyboard. Using function strstr, locate the first occurrence of the search string in the line of text, and assign the location to variable searchPtr of type char *. If the search string is found, print the remainder of the line of text beginning with the search string. Then, use strstr again to locate the next occurrence of the search string in the line of text. If a second occurrence is found, print the remainder of the line of text beginning with the second occurrence. [Hint: The second call to strstr should contain searchPtr + 1 as its first argument.] 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  /* Exercise 8.16 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char text[ 80 ]; /* line of text */ char search[ 15 ]; /* search string */ char *searchPtr; /* poiner to search string */ /* get line of text from user */ printf( "Enter a line of text:\n" ); gets( text ); /* get search string from user */ printf( "Enter a search string: " ); scanf( "%s", search ); /* search for search string in text */ searchPtr = strstr( text, search ); /* if searchPtr is not NULL */ if ( searchPtr ) { printf( "\n%s\n%s\"%s\":\n%s\n", "The remainder of the line beginning with", "the first occurrence of ", search, searchPtr ); /* search for a second occurrence */ searchPtr = strstr( searchPtr + 1, search ); /* if searchPtr is not NULL */ if ( searchPtr ) { printf( "\n%s\n%s\"%s\":\n%s\n", "The remainder of the line beginning with", "the second occurrence of ", search, searchPtr ); } /* end if */ else { printf( "The search string appeared only once.\n" ); } /* end else */ } /* end if */ else { printf( "\"%s\" not found.\n", search ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  294 C Characters and Strings: Solutions  Chapter 8  Enter a line of text: To be or not to be; that is the question. Enter a search string: be The remainder of the line beginning with the first occurrence of "be": be or not to be; that is the question. The remainder of the line beginning with the second occurrence of "be": be; that is the question.  8.17  Write a program based on the program of Exercise 8.16 that inputs several lines of text and a search string, and uses function  strstr to determine the total occurrences of the string in the lines of text. Print the result.  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  /* Exercise 8.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { char text[ 3 ][ 80 ]; /* array to hold text entered by user */ char search[ 20 ]; /* search string */ char *searchPtr; /* pointer to search string */ int count = 0; /* total occurrences of search string */ int i; /* loop counter */ int j; /* loop counter */ printf( "Enter three lines of text:\n" ); /* read in 3 lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* make all characters lowercase */ for ( i = 0; i <= 2; i++ ) { /* loop through each character */ for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { text[ i ][ j ] = tolower( text[ i ][ j ] ); } /* end for */ } /* end for */ printf( "\nEnter a search string: " ); /* get search string */ scanf( "%s", search ); /* loop through all three strings */ for ( i = 0; i <= 2; i++ ) { /* set pointer to first character of string */ searchPtr = &text[ i ][ 0 ]; /* loop while strstr does not return NULL */ while ( searchPtr = strstr( searchPtr, search ) ) { ++count; searchPtr++; } /* end while */ } /* end for */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 295  Chapter 8  49 50 51 52 53 54  printf( "\nThe total occurrences of \"%s\" in the text is %d\n", search, count ); return 0; /* indicate successful termination */ } /* end main */  Enter three lines of text: This program inputs three lines of text and counts the number of occurrences of the search string in the three lines of text. Enter a search string: th The total occurrences of "th" in the text is 6  8.18 Write a program that inputs several lines of text and a search character, and uses function strchr to determine the total occurrences of the character in the lines of text. 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  /* Exercise 8.18 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { char text[ 3 ][ 80 ]; /* array to hold text entered by user */ char search; /* search character */ char *searchPtr; /* pointer to search character */ int count = 0; /* total search characters found */ int i; /* loop counter */ int j; /* loop counter */ printf( "Enter three lines of text:\n" ); /* read 3 lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* convert all letters to lowercase */ for ( i = 0; i <= 2; i++ ) { /* loop through each character */ for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { text[ i ][ j ] = tolower( text[ i ][ j ] ); } /* end for */ } /* end for */ /* get search character */ printf( "\nEnter a search character: " ); scanf( "%c", &search ); /* loop through 3 lines of text */ for ( i = 0; i <= 2; i++ ) { /* set pointer to first character in line */ searchPtr = &text[ i ][ 0 ]; /* loop while strchr does not return NULL */ while ( searchPtr = strchr( searchPtr, search ) ) { ++count; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  296 C Characters and Strings: Solutions  45 46 47 48 49 50 51 52 53 54 55  searchPtr++; } /* end while */ } /* end for */ printf( "\nThe total occurrences of '%c' in the text is %d\n", search, count ); return 0; /* indicate successful termination */ } /* end main */  Enter three lines of text: This program inputs three lines of text and counts the number of occurrences of the specified search character in the text Enter a search character: e The total occurrences of 'e' in the text is 15  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 8  C Characters and Strings: Solutions 297  Chapter 8  8.19 Write a program based on the program of Exercise 8.18 that inputs several lines of text and uses function strchr to determine the total occurrences of each letter of the alphabet in the lines of text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array and print the values in tabular format after the totals have been determined. 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 53 54 55 56 57 58 59  /* Exercise 8.19 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { char text[ 3 ][ 80 ]; /* 3 lines of text */ char *searchPtr; /* pointer to search character */ char characters[ 26 ] = { 0 }; /* totals for each letter */ int count = 0; /* total for current letter */ int i; /* loop counter */ int j; /* loop counter */ printf( "Enter three lines of text:\n" ); /* read three lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* convert letters to lowercase */ for ( i = 0; i <= 2; i++ ) { /* loop through each character of line */ for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { text[ i ][ j ] = tolower( text[ i ][ j ] ); } /* end for */ } /* end for */ /* loop through alphabet */ for ( i = 0; i <= 25; i++ ) { /* loop through 3 lines of text */ for ( j = 0, count = 0; j <= 2; j++ ) { searchPtr = &text[ j ][ 0 ]; /* while strchr does not return NULL */ while ( searchPtr = strchr( searchPtr, 'a' + i ) ) { ++count; searchPtr++; } /* end while */ } /* end for */ characters[ i ] = count; } /* end for */ printf( "\nThe total occurrences of each character:\n" ); /* display totals for each character */ for ( i = 0; i <= 25; i++ ) { printf( "%c:%3d\n", 'a' + i, characters[ i ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  298 C Characters and Strings: Solutions  Enter three lines of text: This program inputs three lines of text and determines the number of occurrences of each character in the three lines. The total occurrences of each character: a: 5 b: 1 c: 6 d: 2 e: 17 f: 3 g: 1 h: 7 i: 6 j: 0 k: 0 l: 2 m: 3 n: 8 o: 5 p: 2 q: 0 r: 10 s: 6 t: 10 u: 3 v: 0 w: 0 x: 1 y: 0 z: 0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 8  C Characters and Strings: Solutions 299  Chapter 8  8.20 Write a program that inputs several lines of text and uses strtok to count the total number of words. Assume that the words are separated either by spaces or newline characters. 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  /* Exercise 8.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { char text[ 4 ][ 80 ]; /* text entered by user */ char *tokenPtr; /* pointer to current token */ int i; /* loop counter */ int counter = 0; /* token counter */ printf( "Enter 4 lines of text: \n" ); /* read 4 lines of text */ for ( i = 0; i <= 3; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* loop through 4 lines of text */ for ( i = 0; i <= 3; i++ ) { /* get first token */ tokenPtr = strtok( &text[ i ][ 0 ], " \n" ); /* while tokenPtr does not equal NULL */ while ( tokenPtr ) { ++counter; tokenPtr = strtok( NULL, " \n" ); /* get next token */ } /* end while */ } /* end for */ printf( "\nThe total number of words is %d\n", counter ); return 0; /* indicate successful termination */ } /* end main */  Enter 4 lines of text: This line of text has seven words This line has five words There are two words on the next line I am The total number of words is 22  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  300 C Characters and Strings: Solutions  Chapter 8  8.21 Use the string comparison functions discussed in Section 8.6 and the techniques for sorting arrays developed in Chapter 6 to write a program that alphabetizes a list of strings. Use the names of 10 or 15 towns in your area as data for your program. 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 53  /* Exercise 8.21 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  void bubbleSort( char a[][ 50 ] ); /* function prototype */ int main() { char array[ 10 ][ 50 ]; /* 10 lines of text from user */ int i; /* counter */ /* read in 10 lines of text */ for ( i = 0; i <= 9; i++ ) { printf( "Enter a string: " ); scanf( "%s", &array[ i ][ 0 ] ); } /* end for */ bubbleSort( array ); /* sort the array of strings */ printf( "\nThe strings in sorted order are:\n" ); /* display text in sorted order */ for ( i = 0; i <= 9; i++ ) { printf( "%s\n", &array[ i ][ 0 ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ /* sort the array */ void bubbleSort( char a[][ 50 ] ) { int i; /* loop counter */ int j; /* loop counter */ char temp[ 50 ]; /* temporary array */ /* make 9 passes */ for ( i = 0; i <= 8; i++ ) { for ( j = 0; j <= 8; j++ ) { /* swap strings if necessary */ if ( strcmp( &a[ j ][ 0 ], &a[ j + 1 ][ 0 ] ) > 0 ) { strcpy( temp, &a[ j ][ 0 ] ); strcpy( &a[ j ][ 0 ], &a[ j + 1 ][ 0 ] ); strcpy( &a[ j + 1 ][ 0 ], temp ); } /* end if */ } /* end for */ } /* end for */ } /* end function bubbleSort */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 301  Chapter 8  Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter  a a a a a a a a a a  string: string: string: string: string: string: string: string: string: string:  Westborough Wellesley Natick Waltham Framingham Marlborough Boston Ashland Hopkington Shrewsbury  The strings in sorted order are: Ashland Boston Framingham Hopkington Marlborough Natick Shrewsbury Waltham Wellesley Westborough  8.22 The chart in Appendix D shows the numeric code representations for the characters in the ASCII character set. Study this chart and then state whether each of the following is true or false. a) The letter "A" comes before the letter "B." ANS: True. b) The digit "9" comes before the digit "0." ANS: False. c) The commonly used symbols for addition, subtraction, multiplication and division all come before any of the digits. ANS: True. d) The digits come before the letters. ANS: True. e) If a sort program sorts strings into ascending sequence, then the program will place the symbol for a right parenthesis before the symbol for a left parenthesis. ANS: False.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  302 C Characters and Strings: Solutions  8.23  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  Write a program that reads a series of strings and prints only those strings beginning with the letter "b." ANS: /* Exercise 8.23 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { int i; /* loop counter */ char array[ 5 ][ 20 ]; /* 5 strings from user */ /* read 5 strings from user */ for ( i = 0; i <= 4; i++ ) { printf( "Enter a string: " ); scanf( "%s", &array[ i ][ 0 ] ); } /* end for */ printf( "\nThe strings starting with 'b' are:\n" ); /* loop through strings */ for ( i = 0; i <= 4; i++ ) { /* print if first character is 'b' */ if ( array[ i ][ 0 ] == 'b' ) { printf( "%s\n", &array[ i ][ 0 ] ); } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter Enter Enter Enter Enter  a a a a a  string: string: string: string: string:  the big bad boy sings  The strings starting with 'b' are: big bad boy  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 8  C Characters and Strings: Solutions 303  Chapter 8  8.24  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  Write a program that reads a series of strings and prints only those strings that end with the letters "ed." ANS: /* Exercise 8.24 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int i; /* loop counter */ int length; /* length of current string */ char array[ 5 ][ 20 ]; /* 5 strings from user */ /* read in 5 strings from user */ for ( i = 0; i <= 4; i++ ) { printf( "Enter a string: " ); scanf( "%s", &array[ i ][ 0 ] ); } /* end for */ printf( "\nThe strings ending with \"ED\" are:\n" ); /* loop through 5 strings */ for ( i = 0; i <= 4; i++ ) { /* find length of current string */ length = strlen( &array[ i ][ 0 ] ); /* print string if it ends with "ED" */ if ( strcmp( &array[ i ][ length - 2 ], "ED" ) == 0 ) { printf( "%s\n", &array[ i ][ 0 ] ); } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter Enter Enter Enter Enter  a a a a a  string: string: string: string: string:  WALKED SKIPPED JUMPED FLEW DROVE  The strings ending with "ED" are: WALKED SKIPPED JUMPED  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  304 C Characters and Strings: Solutions  Chapter 8  8.25 Write a program that inputs an ASCII code and prints the corresponding character. Modify this program so that it generates all possible three-digit codes in the range 000 to 255 and attempts to print the corresponding characters. What happens when this program is run? 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  /* Exercise 8.25 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { int c; /* ASCII character */ printf( "Enter an ASCII character code ( EOF to end ): " ); /* while user does not enter EOF */ while ( scanf( "%d", &c ) != EOF ) { /* check if character code is valid */ if ( c >= 0 && c <= 255 ) { printf( "The corresponding character is '%c'\n", c ); } /* end if */ else { printf( "Invalid character code\n" ); } /* end else */ printf( "\nEnter an ASCII character code ( EOF to end ): " ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */  Enter an ASCII character code ( EOF to end ): 90 The corresponding character is 'Z' Enter an ASCII character code ( EOF to end ): 116 The corresponding character is 't' Enter an ASCII character code ( EOF to end ): 130 The corresponding character is 'é' Enter an ASCII character code ( EOF to end ): 45 The corresponding character is '-' Enter an ASCII character code ( EOF to end ): 40 The corresponding character is '(' Enter an ASCII character code ( EOF to end ): ^Z  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 305  Chapter 8  8.26 Using the ASCII character chart in Appendix D as a guide, write your own versions of the character handling functions in Fig. 8.1. 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 53 54 55 56 57 58 59 60 61 62  /* Exercise 8.26 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* function prototypes */ int isDigit( int c ); int isAlpha( int c ); int isAlNum( int c ); int isLower( int c ); int isUpper( int c ); int toLower( int c ); int isSpace( int c ); int isPunct( int c ); int isPrint( int c ); int isGraph( int c ); int toLower( int c ); int toUpper( int c ); int main() { int v; /* function result */ char array[ 2 ] = { '\0' }; /* character from user */ /* read a character from the user */ printf( "Enter a character: " ); scanf( "%c", &array[ 0 ] ); /* test isDigit function */ v = isDigit( ( int ) array[ 0 ] ); printf( "According to isDigit" ); v == 0 ? printf( " %c is not a digit\n", array[ 0 ] ): printf( " %c is a digit\n", array[ 0 ] ); /* test isAlpha function */ v = isAlpha( ( int ) array[ 0 ] ); printf( "According to isAlpha" ); v == 0 ? printf( " %c is not a letter\n", array[ 0 ] ): printf( " %c is a letter\n", array[ 0 ] ); /* test isAlNum function */ v = isAlNum( ( int ) array[ 0 ] ); printf( "According to isAlNum" ); v == 0 ? printf( " %c is not a letter or digit\n", array[ 0 ] ): printf( " %c is a letter or digit\n", array[ 0 ] ); /* test isLower function */ v = isLower( ( int ) array[ 0 ] ); printf( "According to isLower" ); v == 0 ? printf( " %c is not a lowercase letter\n", array[ 0 ] ): printf( " %c is a lowercase letter\n", array[ 0 ] ); /* test isUpper function */ v = isUpper( ( int ) array[ 0 ] ); printf( "According to isUpper" ); v == 0 ? printf( " %c is not an uppercase letter\n", array[ 0 ] ): printf( " %c is an uppercase letter\n", array[ 0 ] ); /* test isSpace function */ v = isSpace( ( int ) array[ 0 ] ); printf( "According to isSpace" ); v == 0 ? printf( " %c is not a white-space character\n", array[ 0 ] ): printf( " character is a white-space character\n" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  306 C Characters and Strings: Solutions  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130  /* test isPunct function */ v = isPunct( ( int ) array[ 0 ] ); printf( "According to isPunct" ); v == 0 ? printf( " %c is not a punctuation character\n", array[ 0 ] ): printf( " %c is a punctuation character\n", array[ 0 ] ); /* test isPrint function */ v = isPrint( ( int ) array[ 0 ] ); printf( "According to isPrint" ); v == 0 ? printf( " %c is not a printing character\n", array[ 0 ] ): printf( " %c is a printing character\n", array[ 0 ] ); /* test isGraph function */ v = isGraph( ( int ) array[ 0 ] ); printf( "According to isGraph" ); v == 0 ? printf( " %c is not a printing character\n", array[ 0 ] ): printf( " %c is a printing character other than space\n", array[ 0 ] ); /* test toLower function */ v = toLower( ( int ) array[ 0 ] ); printf( "According to toLower" ); v == 0 ? printf( " %c is unchanged\n", array[ 0 ] ): printf( " %c has been converted to lowercase\n", v ); /* test toUpper function */ v = toUpper( ( int ) array[ 0 ] ); printf( "According to toUpper" ); v == 0 ? printf( " %c is unchanged\n", array[ 0 ] ): printf( " %c has been converted to uppercase\n", v ); return 0; /* indicate successful termination */ } /* end main */ /* determines whether argument is a digit */ int isDigit( int c ) { return ( c >= 48 && c <= 57 ) ? 1 : 0; } /* end function isDigit */ /* determines whether argument is a letter */ int isAlpha( int c ) { return ( ( c >= 65 && c <= 90 ) || ( c >= 97 && c <= 122 ) ) ? 1 : 0; } /* end function isAlpha */ /* determines whether argument is a letter or digit */ int isAlNum( int c ) { return ( isDigit( c ) == 1 || isAlpha( c ) == 1 ) ? 1 : 0; } /* end function isAlNum */ /* determines whether argument is a lowercase letter */ int isLower( int c ) { return ( c >= 97 && c <= 122 ) ? 1 : 0; } /* end function isLower */ /* determines whether argument is an uppercase letter */ int isUpper( int c ) { return ( c >= 65 && c <= 90 ) ? 1 : 0; } /* end function isUpper */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 8  C Characters and Strings: Solutions 307  Chapter 8  131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176  /* determines whether argument is a whitespace character */ int isSpace( int c ) { return ( ( c == 32 ) || ( c >= 9 && c <= 13 ) ) ? 1 : 0; } /* end function isSpace */ /* determines whether argument is a printing character other than a space, a digit or a letter */ int isPunct( int c ) { return ( isAlNum( c ) == 0 && isSpace( c ) == 0 ) ? 1 : 0; } /* end function isPunct */ /* determines whether argument is a printing character including the space character */ int isPrint( int c ) { return ( c >= 32 && c <= 126 ) ? 1 : 0; } /* end function isPrint */ /* determines whether argument is a printing character other than the space character */ int isGraph( int c ) { return ( c >= 33 && c <= 126 ) ? 1 : 0; } /* end function isGraph */ /* converts and uppercase letter to lowercase */ int toLower( int c ) { return ( isUpper( c ) == 1 ) ? c + 32 : c; } /* end function toLower */ /* converts a lowercase letter to uppercase */ int toUpper( int c ) { return ( isLower( c ) == 1 ) ? c - 32 : c; } /* end function toUpper */  Enter a character: m According to isDigit According to isAlpha According to isAlNum According to isLower According to isUpper According to isSpace According to isPunct According to isPrint According to isGraph According to toLower According to toUpper  m m m m m m m m m m M  is not a digit is a letter is a letter or digit is a lowercase letter is not an uppercase letter is not a white-space character is not a punctuation character is a printing character is a printing character other than space has been converted to lowercase has been converted to uppercase  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  308 C Characters and Strings: Solutions  Enter a character: * According to isDigit According to isAlpha According to isAlNum According to isLower According to isUpper According to isSpace According to isPunct According to isPrint According to isGraph According to toLower According to toUpper  8.27  * * * * * * * * * * *  Chapter 8  is not a digit is not a letter is not a letter or digit is not a lowercase letter is not an uppercase letter is not a white-space character is a punctuation character is a printing character is a printing character other than space has been converted to lowercase has been converted to uppercase  Write your own versions of the functions in Fig. 8.5 for converting strings to numbers.  8.28 Write two versions of each of the string copy and string concatenation functions in Fig. 8.17. The first version should use array subscripting, and the second version should use pointers and pointer arithmetic. 8.29  Write your own versions of the functions getchar, gets, putchar and puts described in Fig. 8.12.  8.30 Write two versions of each string comparison function in Fig. 8.20. The first version should use array subscripting, and the second version should use pointers and pointer arithmetic. 8.31  Write your own versions of the functions in Fig. 8.22 for searching strings.  8.32  Write your own versions of the functions in Fig. 8.30 for manipulating blocks of memory.  8.33 Write two versions of function strlen in Fig. 8.36. The first version should use array subscripting, and the second version should use pointers and pointer arithmetic.  SPECIAL SECTION: ADVANCED STRING MANIPULATION EXERCISES The preceding exercises are keyed to the text and designed to test the reader's understanding of fundamental string manipulation concepts. This section includes a collection of intermediate and advanced problems. The reader should find these problems challenging yet enjoyable. The problems vary considerably in difficulty. Some require an hour or two of program writing and implementation. Others are useful for lab assignments that might require two or three weeks of study and implementation. Some are challenging term projects. 8.34 (Text Analysis) The availability of computers with string manipulation capabilities has resulted in some rather interesting approaches to analyzing the writings of great authors. Much attention has been focused on whether William Shakespeare ever lived. Some scholars believe that there is substantial evidence indicating that Christopher Marlowe actually penned the masterpieces attributed to Shakespeare. Researchers have used computers to find similarities in the writings of these two authors. This exercise examines three methods for analyzing texts with a computer. a) Write a program that reads several lines of text and prints a table indicating the number of occurrences of each letter of the alphabet in the text. For example, the phrase To be, or not to be: that is the question:  contains one "a," two "b's," no "c's," etc. ANS: 1 2 3 4 5 6 7 8 9 10 11 12  /* Exercise 8.34 Part A Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char letters[ 26 ] = { 0 }; /* letters of the alphabet */ char text[ 3 ][ 80 ]; /* three lines of text */ int i; /* loop counter */ int j; /* loop counter */ printf( "Enter three lines of text:\n" ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 309  Chapter 8  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  /* read 3 lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* loop through 3 strings */ for ( i = 0; i <= 2; i++ ) { /* loop through each character */ for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { /* if letter, update corresponding array element */ if ( isalpha( text[ i ][ j ] ) ) { ++letters[ tolower( text[ i ][ j ] ) - 'a' ]; } /* end if */ } /* end for */ } /* end for */ printf( "\nTotal letter counts:\n" ); /* print letter totals */ for ( i = 0; i <= 25; i++ ) { printf( "%c:%3d\n", 'a' + i, letters[ i ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter three lines of text: This program counts the occurrences of each letter of the alphabet in the input text. Then, it prints a summary of the occurrences. Total letter counts: a: 6 b: 1 c: 8 d: 0 e: 14 f: 3 g: 1 h: 8 i: 5 j: 0 k: 0 l: 2 m: 3 n: 7 o: 7 p: 4 q: 0 r: 9 s: 6 t: 15 u: 5 v: 0 w: 0 x: 1 y: 1 z: 0  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  310 C Characters and Strings: Solutions  Chapter 8  b) Write a program that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, three-letter words, etc., appearing in the text. For example, the phrase Whether 'tis nobler in the mind to suffer  contains Word length  Occurrences  1  0  2  2  3  1  4  2 (including 'tis)  5  0  6  2  7  1 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  /* Exercise 8.34 Part B solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { char text[ 3 ][ 80 ]; /* char *temp; /* int lengths[ 20 ] = { 0 }; /* int i; /*  3 strings from user */ token pointer */ array of length counts */ loop counter */  printf( "Enter three lines of text:\n" ); /* read 3 lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* loop through each string */ for ( i = 0; i <= 2; i++ ) { /* get first token */ temp = strtok( &text[ i ][ 0 ], ". \n" ); /* while temp does not equal NULL */ while ( temp ) { /* increment corresponding array element */ ++lengths[ strlen( temp ) ]; temp = strtok( NULL, ". \n" ); } /* end while */ } /* end for */ putchar( '\n' ); /* display results in array */ for ( i = 1; i <= 19; i++ ) { /* if length is not zero */ if ( lengths[ i ] ) { printf( "%d word%s of length %d\n", lengths[ i ], lengths[ i ] == 1 ? "" : "s", i ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 311  Chapter 8  44 45 46 47 48 49 50  } /* end if */ } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter three lines of text: This program determines the length of each word in the input text. The input text here has words of several different lengths. 3 4 6 3 1 3 1 1  words of length 2 words of length 3 words of length 4 words of length 5 word of length 6 words of length 7 word of length 9 word of length 10  c) Write a program that reads several lines of text and prints a table indicating the number of occurrences of each different word in the text. The first version of your program should include the words in the table in the same order in which they appear in the text. A more interesting (and useful) printout should then be attempted in which the words are sorted alphabetically. For example, the lines To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer  contain the words "to" three times, the word "be" two times, the word "or" once, etc. 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  /* Exercise 8.34 Part C solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char text[ 3 ][ 80 ]; /* 3 string from user */ char *temp; /* token pointer */ char words[ 100 ][ 20 ] = { "" }; /* array of words */ int i; /* loop counter */ int j; /* loop counter */ int count[ 100 ] = { 0 }; /* array of word counts */ printf( "Enter three lines of text:\n" ); /* read three lines of text */ for ( i = 0; i <= 2; i++ ) { gets( &text[ i ][ 0 ] ); } /* end for */ /* loop through 3 strings */ for ( i = 0; i <= 2; i++ ) { /* get first token */ temp = strtok( &text[ i ][ 0 ], ". \n" ); /* while temp does not equal NULL */ while ( temp ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  312 C Characters and Strings: Solutions  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 55 56 57 58  Chapter 8  /* loop through words for match */ for ( j = 0; words[ j ][ 0 ] && strcmp( temp, &words[ j ][ 0 ] ) != 0; j++ ) { ; /* empty body */ } /* end for */ ++count[ j ]; /* increment count */ /* if temp could not be found in words array */ if ( !words[ j ][ 0 ] ) { strcpy( &words[ j ][ 0 ], temp ); } /* end if */ temp = strtok( NULL, ". \n" ); } /* end while */ } /* end for */ putchar( '\n' ); /* loop through words array */ for ( j = 0; words[ j ][ 0 ] != '\0' && j <= 99; j++ ) { printf( "\"%s\" appeared %d time%s\n", &words[ j ][ 0 ], count[ j ], count[ j ] == 1 ? "" : "s" ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter three lines of text: This program counts the number of occurrences of each word in the input text. "This" appeared 1 time "program" appeared 1 time "counts" appeared 1 time "the" appeared 2 times "number" appeared 1 time "of" appeared 2 times "occurrences" appeared 1 time "each" appeared 1 time "word" appeared 1 time "in" appeared 1 time "input" appeared 1 time "text" appeared 1 time  8.35 (Word Processing) The detailed treatment of string manipulation in this text is greatly attributable to the exciting growth in word processing in recent years. One important function in word processing systems is type-justification—the alignment of words to both the left and right margins of a page. This generates a professional-looking document that gives the appearance of being set in type, rather than prepared on a typewriter. Type-justification can be accomplished on computer systems by inserting one or more blank characters between each of the words in a line so that the rightmost word aligns with the right margin. Write a program that reads several lines of text and prints this text in type-justified format. Assume that the text is to be printed on 8 1/2-inch-wide paper and that one-inch margins are to be allowed on both the left and right sides of the printed page. Assume that the computer prints 10 characters to the horizontal inch. Therefore, your program should print 6 1/2 inches of text or 65 characters per line.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 313  Chapter 8  8.36 (Printing Dates in Various Formats) Dates are commonly printed in several different formats in business correspondence. Two of the more common formats are 07/21/2003 and July 21, 2003  Write a program that reads a date in the first format and prints that date in the second format. 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  /* Exercise 8.36 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { /* array of month names */ char *months[ 13 ] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; int m; /* integer month */ int d; /* integer day */ int y; /* integer year */ /* read a date from user */ printf( "Enter a date in the form mm/dd/yyyy: " ); scanf( "%d/%d/%d", &m, &d, &y ); /* output date in new format */ printf( "The date is: %s %d, %d\n", months[ m ], d, y ); return 0; /* indicate successful termination */ } /* end main */  Enter a date in the form mm/dd/yyyy: 06/18/2003 The date is: June 18, 2003  8.37 (Check Protection) Computers are frequently used in check-writing systems, such as payroll and accounts payable applications. Many strange stories circulate regarding weekly paychecks being printed (by mistake) for amounts in excess of $1 million. Weird amounts are printed by computerized check-writing systems because of human error and/or machine failure. Systems designers, of course, make every effort to build controls into their systems to prevent erroneous checks from being issued. Another serious problem is the intentional alteration of a check amount by someone who intends to cash a check fraudulently. To prevent a dollar amount from being altered, most computerized check-writing systems employ a technique called check protection. Checks designed for imprinting by computer contain a fixed number of spaces in which the computer may print an amount. Suppose a paycheck contains nine blank spaces in which the computer is supposed to print the amount of a weekly paycheck. If the amount is large, then all nine of those spaces will be filled, for example: 11,230.60 --------123456789  (check amount) (position numbers)  99.87 --------123456789  contains three blank spaces. If a check is printed with blank spaces, it is easier for someone to alter the amount of the check. To prevent a check from being altered, many check-writing systems insert leading asterisks to protect the amount as follows: ****99.87 --------123456789 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  314 C Characters and Strings: Solutions  Chapter 8  Write a program that inputs a dollar amount to be printed on a check and then prints the amount in check-protected format with leading asterisks if necessary. Assume that nine spaces are available for printing an amount. 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  /* Exercise 8.37 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { double amount; double base = 100000.0; int i; int j;  /* /* /* /*  check amount */ base to check number of digits */ loop counter */ loop counter */  /* get check amount */ printf( "Enter check amount: " ); scanf( "%lf", &amount ); printf( "The protected amount is $" ); /* loop until amount is less than base */ for ( i = 0; amount < base; i++ ) { base /= 10; } /* end for */ /* print i leading asterisks */ for ( j = 1; j <= i; j++ ) { printf( "*" ); } /* end for */ printf( "%*.2f\n", 9 - i, amount ); return 0; /* indicate successful termination */ } /* end main */  Enter check amount: 234.83 The protected amount is $***234.83  Enter check amount: 14892.98 The protected amount is $*14892.98  Enter check amount: 1.54 The protected amount is $*****1.54  8.38 (Writing the Word Equivalent of a Check Amount) Continuing the discussion of the previous example, we reiterate the importance of designing check-writing systems to prevent alteration of check amounts. One common security method requires that the check amount be both written in numbers and "spelled out" in words. Even if someone is able to alter the numerical amount of the check, it is extremely difficult to change the amount in words. Many computerized check-writing systems do not print the amount of the check in words. Perhaps the main reason for this omission is the fact that most high-level languages used in commercial applications do not contain adequate string manipulation features. Another reason is that the logic for writing word equivalents of check amounts is somewhat involved. Write a program that inputs a numeric check amount and writes the word equivalent of the amount. For example, the amount 112.43 should be written as ONE HUNDRED TWELVE and 43/100  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 315  Chapter 8  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 53 54 55 56 57 58  /* Exercise 8.38 solution */ /* NOTE THAT THIS PROGRAM ONLY HANDLES VALUES UP TO $99.99 */ /* The program is easily modified to process larger values */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { /* word equivalents of single digits */ char *digits[ 10 ] = { "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"}; /* word equivalents of 10-19 */ char *teens[ 10 ] = { "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"}; /* word equivalents of tens digits */ char *tens[ 10 ] = { "", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"}; int int int int  dollars; cents; digit1; digit2;  /* /* /* /*  check dollar amount */ check cents amount */ ones digit */ tens digit */  /* get check amount */ printf( "Enter the check amount ( 0.00 to 99.99 ): " ); scanf( "%d.%d", &dollars, ¢s ); printf( "\nThe check amount in words is:\n" ); /* print equivalent words */ if ( dollars < 10 ) { printf( "%s ", digits[ dollars ] ); } /* end if */ else if ( dollars < 20 ) { printf( "%s ", teens[ dollars - 10 ] ); } /* end else if */ else { digit1 = dollars / 10; /* ones digit */ digit2 = dollars % 10; /* tens digit */ /* if ones digit is zero */ if ( digit2 == 0 ) { printf( "%s ", tens[ digit1 ] ); } /* end if */ else { printf( "%s-%s ", tens[ digit1 ], digits[ digit2 ] ); } /* end else */ } /* end else */ printf( "and %d/100\n", cents ); return 0; /* indicate successful termination */ } /* end main */  Enter the check amount ( 0.00 to 99.99 ): 72.63 The check amount in words is: SEVENTY-TWO and 63/100  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  316 C Characters and Strings: Solutions  Chapter 8  Enter the check amount ( 0.00 to 99.99 ): 13.22 The check amount in words is: THIRTEEN and 22/100  Enter the check amount ( 0.00 to 99.99 ): 5.75 The check amount in words is: FIVE and 75/100  ANS: 8.39 (Morse Code) Perhaps the most famous of all coding schemes is Morse code, developed by Samuel Morse in 1832 for use with the telegraph system. Morse code assigns a series of dots and dashes to each letter of the alphabet, each digit, and a few special characters (such as period, comma, colon and semicolon). In sound-oriented systems, the dot represents a short sound and the dash represents a long sound. Other representations of dots and dashes are used with light-oriented systems and signal-flag systems. Separation between words is indicated by a space,—quite simply, the absence of a dot or dash. In a sound-oriented system, a space is indicated by a short period of time during which no sound is transmitted. The international version of Morse code appears in Fig. 8.39. Write a program that reads an English-language phrase and encodes the phrase into Morse code. Also write a program that reads a phrase in Morse code and converts the phrase into the English-language equivalent. Use one blank between each Morsecoded letter and three blanks between each Morse-coded word.  Character  Code  Character  Code  A  .-  T  -  B  -...  U  ..-  C  -.-.  V  ...-  D  -..  W  .--  E  .  X  -..-  F  ..-.  Y  -.--  G  --.  Z  --..  H  ....  I  ..  Digits  J  .---  1  .----  K  -.-  2  ..---  L  .-..  3  ...--  M  --  4  ....-  N  -.  5  .....  O  ---  6  -....  P  .--.  7  --...  Q  --.-  8  ---..  R  .-.  9  ----.  S  ...  0  -----  Fig. 8.1  The letters of the alphabet as expressed in international Morse code.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Characters and Strings: Solutions 317  Chapter 8  8.40 (A Metric Conversion Program) Write a program that will assist the user with metric conversions. Your program should allow the user to specify the names of the units as strings (i.e., centimeters, liters, grams, etc., for the metric system and inches, quarts, pounds, etc., for the English system) and should respond to simple questions such as "How many inches are in 2 meters?" "How many liters are in 10 quarts?"  Your program should recognize invalid conversions. For example, the question "How many feet in 5 kilograms?"  is not meaningful, because "feet" are units of length while "kilograms" are units of mass. 8.41 (Dunning Letters) Many businesses spend a great deal of time and money collecting overdue debts. Dunning is the process of making repeated and insistent demands upon a debtor in an attempt to collect a debt. Computers are often used to generate dunning letters automatically and in increasing degrees of severity as a debt ages. The theory is that as a debt becomes older, it becomes more difficult to collect, and therefore the dunning letters must become more threatening. Write a program that contains the texts of five dunning letters of increasing severity. Your program should accept as input the following: a) Debtor's name b) Debtor's address c) Debtor's account d) Amount owed e) Age of the amount owed (i.e., one month overdue, two months overdue, etc.). Use the age of the amount owed to select one of the five message texts, and then print the dunning letter inserting the other user-supplied information where appropriate.  A CHALLENGING STRING MANIPULATION PROJECT 8.42 (A Crossword-Puzzle Generator) Most people have worked a crossword puzzle at one time or another, but few have ever attempted to generate one. Generating a crossword puzzle is a difficult problem. It is suggested here as a string manipulation project requiring substantial sophistication and effort. There are many issues the programmer must resolve to get even the simplest crossword-puzzle generator program working. For example, how does one represent the grid of a crossword puzzle inside the computer? Should one use a series of strings, or should double-subscripted arrays be used? The programmer needs a source of words (i.e., a computerized dictionary) that can be directly referenced by the program. In what form should these words be stored to facilitate the complex manipulations required by the program? The really ambitious reader will want to generate the "clues" portion of the puzzle in which the brief hints for each "across" word and each "down" word are printed for the puzzle worker. Merely printing a version of the blank puzzle itself is not a simple problem.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  318 C Characters and Strings: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 8  9 C Formatted Input/Output: Solutions  SOLUTIONS 9.4  Write a printf or scanf statement for each of the following: a) Print unsigned integer 40000 left justified in a 15-digit field with 8 digits. ANS: printf( "%-15.8u", ( unsigned ) 40000 ); b) Read a hexadecimal value into variable hex. ANS: scanf( "%x", hex ); c) Print 200 with and without a sign. ANS: printf( "%+d %d\n", 200, 200 ); d) Print 100 in hexadecimal form preceded by 0x. ANS: printf( %#x\n", 100 ); e) Read characters into array s until the letter p is encountered. ANS: scanf( "%[^p]", s ); f) Print 1.234 in a 9-digit field with preceding zeros. ANS: printf( "%09.3f\n", 1.234 ); g) Read a time of the form hh:mm:ss, storing the parts of the time in the integer variables hour, minute and second. Skip the colons (:) in the input stream. Use the assignment suppression character. ANS: scanf( "%d%*c%d%*c%d", &hour, &minute, &second ); h) Read a string of the form "characters" from the standard input. Store the string in character array s. Eliminate the quotation marks from the input stream. ANS: scanf( "\"%[^\"]", s ); i) Read a time of the form hh:mm:ss, storing the parts of the time in the integer variables hour, minute and second. Skip the colons (:) in the input stream. Do not use the assignment-suppression character. ANS: scanf( "%d:%d:%d:", &hour, &minute, &second );  9.5  Show what is printed by each of the following statements. If a statement is incorrect, indicate why. a) printf( "%-10d\n", 10000 ); ANS: 10000 b) printf( "%c\n", "This is a string" ); ANS: A string cannot be printed with the %c specifier. c) printf( "%*.*lf\n", 8, 3, 1024.987654 ); ANS: 1024.988 d) printf( "%#o\n%#X\n%#e\n", 17, 17, 1008.83689 ); ANS: 021 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  320 C Formatted Input/Output: Solutions  Chapter 9  0X11 1.008837e+03 e) printf( "% ld\n%+ld\n", 1000000, 1000000 );  ANS: 1000000 +1000000 f) printf( "%10.2E\n", 444.93738 ); ANS: 4.45E+02 preceded by two spaces g) printf( "%10.2g\n", 444.93738 ); ANS: 4.4e+02 preceded by three spaces h) printf( "%d\n", 10.987 );  ANS: A floating point value cannot be printed with the %d conversion specifier. 9.6  Find the error(s) in each of the following program segments. Explain how each error can be corrected. a) printf( "%s\n", 'Happy Birthday' ); ANS: printf( "%s\n", "Happy Birthday" ); b) printf( "%c\n", 'Hello' ); ANS: printf( "%s\n", "Hello" ); c) printf( "%c\n", "This is a string" ); ANS: printf( "%s\n", "This is a string" ); d) The following statement should print "Bon Voyage": printf( ""%s"", "Bon Voyage" );  ANS: printf( "\"%s\"", "Bon Voyage" ); e) char day[] = "Sunday"; printf( "%s\n", day[ 3 ] ); ANS: printf( "%s\n", day ); f) printf( 'Enter your name: ' ); ANS: printf( "Enter your name: " ); g) printf( %f, 123.456 ); ANS: printf( "%f", 123.456 ); h) The following statement should print the characters 'O' and 'K': printf( "%s%s\n", 'O', 'K' );  ANS: printf( "%c%c\n", 'O', 'K' ); i) char s[ 10 ]; scanf( "%c", s[ 7 ] ); ANS: scanf( "%c", &s[ 7 ] ); 9.7 Write a program that loads 10-element array number with random integers from 1 to 1000. For each value, print the value and a running total of the number of characters printed. Use the %n conversion specifier to determine the number of characters output for each value. Print the total number of characters output for all values up to and including the current value each time the current value is printed. The output should have the following format: Value 342 1000 963 6 etc.  Total characters 3 7 10 11  ANS: 1 2 3 4 5 6 7  /* Exercise 9.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 321  Chapter 9  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  int int int int  a[ 10 ] = { 0 }; i; count; totalCount = 0;  /* /* /* /*  random integers from 1 to 1000 */ loop counter */ number of characters in current value */ total characters in array */  srand( time( NULL ) ); /* fill the array with random numbers */ for ( i = 0; i <= 9; i++ ) { a[ i ] = 1 + rand() % 1000; } /* end for */ /* print table headers */ printf( "%s\t%s\n", "Value", "Total characters" ); /* loop through 10 elements */ for ( i = 0; i <= 9; i++ ) { printf( "%d%n", a[ i ], &count ); totalCount+= count; /* update totalCount */ printf( "\t%d\n", totalCount ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Value 842 18 220 658 275 647 657 623 242 471  Total characters 3 5 8 11 14 17 20 23 26 29  9.8 Write a program to test the difference between the %d and %i conversion specifiers when used in scanf statements. Use the statements scanf( "%i%d", &x, &y ); printf( "%d %d\n", x, y );  to input and print the values. Test the program with the following sets of input data: 10 -10 010 0x10  10 -10 010 0x10  ANS: 1 2 3 4 5 6 7 8 9  /* Exercise 9.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { int i; /* loop counter */ int x; /* first integer from user */ int y; /* second integer from user */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  322 C Formatted Input/Output: Solutions  10 11 12 13 14 15 16 17 18 19  Chapter 9  /* loop four times */ for ( i = 1; i <= 4; i++ ) { printf( "\nEnter two integers: " ); scanf( "%i%d", &x, &y ); printf( "%d %d\n", x, y ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter two integers: 10 10 10 10 Enter two integers: -10 -10 -10 -10 Enter two integers: 010 010 8 10 Enter two integers: 0x10 0x10 16 0  9.9 Write a program that prints pointer values using all the integer conversion specifiers and the %p conversion specifier. Which ones print strange values? Which ones cause errors? In which format does the %p conversion specifier display the address on your system? ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  /* Exercise 9.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int x; /* define x for testing */ printf( printf( printf( printf( printf( printf( printf(  "%o\n", &x ); "%lo\n", &x ); "%d\n", &x ); "%ld\n", &x ); "%x\n", &x ); "%lx\n", &x ); "%p\n", &x );  return 0; /* indicate successful termination */ } /* end main */  4577574 4577574 1245052 1245052 12ff7c 12ff7c 0012FF7C  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 323  Chapter 9  9.10 Write a program to test the results of printing the integer value 12345 and the floating-point value 1.2345 in various size fields. What happens when the values are printed in fields containing fewer digits than the values? ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  /* Exercise 9.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { /* print the integer 12345 */ printf( "%10d\n", 12345 ); printf( "%5d\n", 12345 ); printf( "%2d\n\n", 12345 ); /* print the floating-point value 1.2345 */ printf( "%10f\n", 1.2345 ); printf( "%6f\n", 1.2345 ); printf( "%2f\n", 1.2345 ); return 0; /* indicate successful termination */ } /* end main */ 12345  12345 12345 1.234500 1.234500 1.234500  9.11 Write a program that prints the value 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth and ten thousandth. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  /* Exercise 9.11 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { printf( printf( printf( printf( printf(  "%.0f\n", "%.1f\n", "%.2f\n", "%.3f\n", "%.4f\n",  100.453627 100.453627 100.453627 100.453627 100.453627  ); ); ); ); );  return 0; /* indicate successful termination */ } /* end main */  100 100.5 100.45 100.454 100.4536  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  324 C Formatted Input/Output: Solutions  Chapter 9  9.12 Write a program that inputs a string from the keyboard and determines the length of the string. Print the string using twice the length as the field width. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  /* Exercise 9.12 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { int count; /* length of string */ char string[ 20 ]; /* string entered by user */ /* read string from user and find length */ printf( "Enter a string:\n" ); scanf( "%s%n", string, &count ); printf( "%*s\n", 2 * count, string ); /* print the string */ return 0; /* indicate successful termination */ } /* end main */  Enter a string: hello hello  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 325  Chapter 9  9.13 Write a program that converts integer Fahrenheit temperatures from 0 to 212 degrees to floating-point Celsius temperatures with 3 digits of precision. Use the formula celsius = 5.0 / 9.0 * ( fahrenheit - 32 );  to perform the calculation. The output should be printed in two right-justified columns of 10 characters each, and the Celsius temperatures should be preceded by a sign for both positive and negative values. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  /* Exercise 9.13 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { int fahrenheit; /* holds fahrenheit temperature */ double celcius; /* holds celcius temperature */ printf( "%10s%12s\n", "Fahrenheit", "Celcius" ); /* convert fahrenheit to celsius and display temperatures showing the sign for celsius temperatures */ for ( fahrenheit = 0; fahrenheit <= 212; fahrenheit++ ) { celcius = 5.0 / 9.0 * ( fahrenheit - 32 ); printf( "%10d%+12.3f\n", fahrenheit, celcius ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Fahrenheit 0 1 2 3 4 5 6 7 . . . 204 205 206 207 208 209 210 211 212  Celcius -17.778 -17.222 -16.667 -16.111 -15.556 -15.000 -14.444 -13.889  +95.556 +96.111 +96.667 +97.222 +97.778 +98.333 +98.889 +99.444 +100.000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  326 C Formatted Input/Output: Solutions  Chapter 9  9.14 Write a program to test all the escape sequences in Figure 9.16. For the escape sequences that move the cursor, print a character before and after printing the escape sequence so it is clear where the cursor has moved. 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  /* Exercise 9.14 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { /* test printf( printf( printf( printf(  all escape sequences */ "The single quote : \'\n" "The double quote : \"\n" "The question mark: \?\n" "The backslash : \\\n"  ); ); ); );  printf( "The bell. \a\n\n" ); printf( "Move cursor back one position on current line. *\b*\n" ); printf( "Move cursor to start of next logical page. *\f*\n" ); printf( "Move cursor to the beginning of next line. *\n*\n" ); printf( "Move cursor to the beginning of current line. *\r*\n" ); printf( "Move cursor to the next horizontal tab position. *\t*\n" ); printf( "Move cursor to the next vertical tab position. *\v*\n" ); return 0; /* indicate successful termination */ } /* end main */  The The The The The Move Move Move * *ove Move Move  single quote : double quote : question mark: backslash : bell.  ' " ? \  cursor back one position on current line. * cursor to start of next logical page. *?* cursor to the beginning of next line. * cursor to the beginning of current line. * cursor to the next horizontal tab position. * cursor to the next vertical tab position. *?*  *  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 327  Chapter 9  9.15 Write a program that determines whether ? can be printed as part of a printf format control string as a literal character rather than using the \? escape sequence. ANS: 1 2 3 4 5 6 7 8 9 10  /* Exercise 9.15 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { printf( "Did the \? print at the end of the sentence?\n" ); return 0; /* indicate successful termination */ } /* end main */  Did the ? print at the end of the sentence?  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  328 C Formatted Input/Output: Solutions  Chapter 9  9.16 Write a program that inputs the value 437 using each of the scanf integer conversion specifiers. Print each input value using all the integer conversion specifiers. 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  /* Exercise 9.16 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { int array[ 5 ]; /* holds the value 437 five times */ int loop; /* loop counter */ /* array of table headers */ char *s[] = { "Read with %d:", "Read with %i:", "Read with %o:", "Read with %u:", "Read with %x:"}; /* prompt the user and read 5 values */ printf( "Enter the value 437 five times: " ); scanf( "%d%i%o%u%x", &array[ 0 ], &array[ 1 ], &array[ 2 ], &array[ 3 ], &array[ 4 ] ); /* loop through all 5 values */ for ( loop = 0; loop <= 4; loop++ ) { /* print each of the 5 values */ printf( "%s\n%d %i %o %u %x\n\n", s[ loop ], array[ loop ], array[ loop ], array[ loop ], array[ loop ], array[ loop ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  Enter the value 437 five times: 437 437 437 437 437 Read with %d: 437 437 665 437 1b5 Read with %i: 437 437 665 437 1b5 Read with %o: 287 287 437 287 11f Read with %u: 437 437 665 437 1b5 Read with %x: 1079 1079 2067 1079 437  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 329  Chapter 9  9.17 Write a program that uses each of the conversion specifiers e, f and g to input the value 1.2345. Print the values of each variable to prove that each conversion specifier can be used to input this same value. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  /* Exercise 9.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { float a[ 3 ]; /* holds the value 1.2345 three times */ /* array of table headers */ char *s[] = { "Read with %e:", "Read with %f:", "Read with %g:" }; /* prompt the user and read 3 values */ printf( "Enter the value 1.2345 three times: " ); scanf( "%e%f%g", &a[ 0 ], &a[ 1 ], &a[ 2 ] ); printf( "%s%e\n\n", s[ 0 ], a[ 0 ] ); printf( "%s%f\n\n", s[ 1 ], a[ 1 ] ); printf( "%s%g\n\n", s[ 2 ], a[ 2 ] ); return 0; /* indicate successful termination */ } /* end main */  Enter the value 1.2345 three times: 1.2345 1.2345 1.2345 Read with %e:1.234500e+000 Read with %f:1.234500 Read with %g:1.2345  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  330 C Formatted Input/Output: Solutions  Chapter 9  9.18 In some programming languages, strings are entered surrounded by either single or double quotation marks. Write a program that reads the three strings suzy, "suzy" and 'suzy'. Are the single and double quotes ignored by C or read as part of the string? ANS: 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  /* Exercise 9.18 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { char a[ 10 ]; /* first string */ char b[ 10 ]; /* second string */ char c[ 10 ]; /* third string */ /* prompt user and read three strings */ printf( "Enter the strings suzy, \"suzy\", and 'suzy':\n" ); scanf( "%s%s%s", a, b, c ); printf( "%s %s %s\n", a, b, c ); /* display strings */ return 0; /* indicate successful termination */ } /* end main */  Enter the strings suzy, "suzy", and 'suzy': suzy "suzy" 'suzy' suzy "suzy" 'suzy'  9.19 Write a program that determines whether ? can be printed as the character constant '?' rather than the character constant escape sequence '\?' using conversion specifier %c in the format control string of a printf statement. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13  /* Exercise 9.19 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { const char questionMark = '?'; /* define '?' as a char constant */ printf( "This %c can be printed without using the \\\?\n", questionMark ); return 0; /* indicate successful termination */ } /* end main */  This ? can be printed without using the \?  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C Formatted Input/Output: Solutions 331  Chapter 9  9.20 Write a program that uses the conversion specifier g to output the value 9876.12345. Print the value with precisions ranging from 1 to 9. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  /* Exercise 9.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { /* output the value printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision:  9876.12345 with precisions from 1 to 9 */ %d, value = %.1g\n", 1, 9876.12345 ); %d, value = %.2g\n", 2, 9876.12345 ); %d, value = %.3g\n", 3, 9876.12345 ); %d, value = %.4g\n", 4, 9876.12345 ); %d, value = %.5g\n", 5, 9876.12345 ); %d, value = %.6g\n", 6, 9876.12345 ); %d, value = %.7g\n", 7, 9876.12345 ); %d, value = %.8g\n", 8, 9876.12345 ); %d, value = %.9g\n", 9, 9876.12345 );  return 0; /* indicate successful termination */ } /* end main */  Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision:  1, 2, 3, 4, 5, 6, 7, 8, 9,  value value value value value value value value value  = = = = = = = = =  1e+004 9.9e+003 9.88e+003 9876 9876.1 9876.12 9876.123 9876.1234 9876.12345  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  332 C Formatted Input/Output: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 9  10 Structures, Unions, Bit Manipulations and Enumerations: Solutions Solutions 10.5  Provide the definition for each of the following structures and unions: a) Structure inventory containing character array partName[ 30 ], integer partNumber, floating point price, integer stock and integer reorder. ANS: struct inventory { char partName[ 30 ]; int partNumber; float price; int stock; int reorder; }; b) Union data containing char c, short s, long b, float f and double d.  ANS: union data { char c; short s; long l; float f; double d; };  c) A structure called address that contains character arrays streetAddress[ 25 ], city[ 20 ], state[ 3 ] and zipCode[ 6 ]. ANS: struct address { char streetAddress[ 25 ]; char city[ 20 ]; char state[ 3 ]; char zipCode[ 6 ]; }; d) Structure student that contains arrays firstName[ 15 ] and lastName[ 15 ] and variable homeAddress of type struct address from part (c).  ANS: struct student { char firstName[ 15 ]; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  334 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  char lastName[ 15 ]; struct address homeAddress; };  e) Structure test containing 16 bit fields with widths of 1 bit. The names of the bit fields are the letters a to p. ANS: struct test { unsigned a:1, b:1, c:1, d:1, e:1, f:1, g:1, h:1, i:1, j:1, k:1, l:1, m:1, n:1, o:1, p:1; };  10.6  Given the following structure and variable definitions, struct customer { char lastName[ 15 ]; char firstName[ 15 ]; int customerNumber; struct { char phoneNumber[ 11 ]; char address[ 50 ]; char city[ 15 ]; char state[ 3 ]; char zipCode[ 6 ]; } personal; } customerRecord, *customerPtr; customerPtr = &customerRecord;  write an expression that can be used to access the structure members in each of the following parts: a) Member lastName of structure customerRecord. ANS: customerRecord.lastName b) Member lastName of the structure pointed to by customerPtr. ANS: customerPtr->lastName c) Member firstName of structure customerRecord. ANS: customerRecord.firstName d) Member firstName of the structure pointed to by customerPtr. ANS: customerPtr->firstName e) Member customerNumber of structure customerRecord. ANS: customerRecord. customerNumber f) Member customerNumber of the structure pointed to by customerPtr. ANS: customerRecord-> customerNumber g) Member phoneNumber of member personal of structure customerRecord. ANS: customerRecord.personal.phoneNumber h) Member phoneNumber of member personal of the structure pointed to by customerPtr. ANS: customerRecord->personal.phoneNumber i) Member address of member personal of structure customerRecord. ANS: customerRecord.personal.address j) Member address of member personal of the structure pointed to by customerPtr. ANS: customerRecord->personal.address k) Member city of member personal of structure customerRecord. ANS: customerRecord.personal.city l) Member city of member personal of the structure pointed to by customerPtr. ANS: customerRecord->personal.city m) Member state of member personal of structure customerRecord. ANS: customerRecord.personal.state n) Member state of member personal of the structure pointed to by customerPtr. ANS: customerRecord->personal.state o) Member zipCode of member personal of customerRecord. ANS: customerRecord.personal.zipCode p) Member zipCode of member personal of the structure pointed to by customerPtr. ANS: customerRecord->personal.zipCode © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 335  Chapter 10  10.7 Modify the program of Fig. 10.16 to shuffle the cards using a high performance shuffle (as shown in Fig. 10.3). Print the resulting deck in two column format as in Fig. 10.4. Precede each card with its color. 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 53 54 55  /* Exercise 10.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* bitCard structure definition */ struct bitCard { unsigned face : 4; /* 4 bits; 0-15 */ unsigned suit : 2; /* 2 bits; 0-3 */ unsigned color : 1; /* 1 bit; 0-1 */ }; /* end structure bitCard */ /* new type name Card */ typedef struct bitCard Card; /* prototypes */ void fillDeck( Card *wDeck ); void shuffle( Card *wDeck ); void deal( Card *wDeck2 ); int main() { Card deck[ 52 ]; /* create array of Cards */ srand( time( NULL ) ); /* randomize */ fillDeck( deck ); shuffle( deck ); deal( deck ); return 0; /* indicate successful termination */ } /* end main */ /* create 52 cards */ void fillDeck( Card *wDeck ) { int i; /* loop counter */ /* loop 52 times and create cards */ for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; } /* end for */ } /* end function fillDeck */ /* shuffle cards */ void shuffle( Card *wDeck ) { int i; /* current card */ int j; /* random card to swap with current card */ Card temp; /* temporary Card */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  336 Structures, Unions, Bit Manipulations and Enumerations: Solutions  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  /* loop through deck */ for ( i = 0; i <= 51; i++ ) { j = rand() % 52; /* swap cards if not equal */ if ( i != j ) { temp = wDeck[ i ]; wDeck[ i ] = wDeck[ j ]; wDeck[ j ] = temp; } /* end if */ } /* end for */ } /* end function shuffle */ /* deal the cards */ void deal( Card *wDeck2 ) { /* arrays face, suit and color hold all possible string descriptions of the cards */ char *face[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; char *color[] = { "Red", "Black"}; int i; /* loop counter */ /* loop through deck and print string description of each card */ for ( i = 0; i <= 51; i++ ) { printf( "%5s: %5s of %-8s", color[ wDeck2[ i ].color ], face[ wDeck2[ i ].face ], suit[ wDeck2[ i ].suit ] ); putchar( ( i + 1 ) % 2 ? '\t' : '\n' ); } /* end for */ } /* end function deal */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 10  Structures, Unions, Bit Manipulations and Enumerations: Solutions 337  Chapter 10  Red: Red: Red: Black: Black: Red: Red: Black: Red: Black: Black: Black: Black: Red: Black: Black: Red: Red: Red: Black: Red: Red: Black: Black: Red: Black:  Eight Jack Three Ten Jack Deuce Queen Nine Seven Nine Jack Five Ace Ten Deuce Seven Six Jack Four Ten Nine Ace Four Seven Eight Eight  of of of of of of of of of of of of of of of of of of of of of of of of of of  Diamonds Hearts Diamonds Spades Spades Diamonds Diamonds Clubs Diamonds Spades Clubs Clubs Clubs Diamonds Clubs Clubs Hearts Diamonds Hearts Clubs Diamonds Hearts Spades Spades Hearts Clubs  Red: Red: Black: Black: Black: Red: Red: Black: Red: Red: Black: Black: Red: Red: Red: Red: Red: Black: Black: Black: Black: Black: Black: Red: Black: Red:  Queen Seven Eight Three Deuce Ten King Ace Three Five Six Queen Nine Ace Four King Deuce Three Four Six King Five Queen Five King Six  of of of of of of of of of of of of of of of of of of of of of of of of of of  Hearts Hearts Spades Clubs Spades Hearts Diamonds Spades Hearts Diamonds Spades Clubs Hearts Diamonds Diamonds Hearts Hearts Spades Clubs Clubs Spades Spades Spades Hearts Clubs Diamonds  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  338 Structures, Unions, Bit Manipulations and Enumerations: Solutions  10.8  Chapter 10  Create union integer with members char c, short s, int i and long b. Write a program that inputs value of type char, short, int and long and stores the values in union variables of type union integer. Each union variable should be printed as a char, a short, an int and a long. Do the values always print correctly? 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 53 54 55 56  /* Exercise 10.8 Solution */ /* NOTE: The program output is machine dependent */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* integer union definition */ union integer { char c; /* character input by user */ short s; /* short integer input by user */ int i; /* integer input by user */ long l; /* long integer input by user */ }; /* end union integer */ int main() { union integer a; /* define union a */ /* read a character from user into the union */ printf( "Enter a character: " ); scanf( "%c", &a.c ); /* print each value of union */ printf( "\'%c'\ printed as a character is %c\n", a.c, a.c ); printf( "\'%c'\ printed as a short integer is %hd\n", a.c, a.s ); printf( "\'%c'\ printed as an integer is %d\n", a.c, a.i ); printf( "\'%c'\ printed as a long integer is %ld\n", a.c, a.l ); /* read a short integer from user into the union */ printf( "\nEnter a short integer: " ); scanf( "%hd", &a.s ); /* print each value of union */ printf( "%hd printed as a character is %c\n", a.s, a.c ); printf( "%hd printed as a short integer is %hd\n", a.s, a.s ); printf( "%hd printed as an integer is %d\n", a.s, a.i ); printf( "%hd printed as a long integer is %ld\n", a.s, a.l ); /* read an integer from user into the union */ printf( "\nEnter an integer: " ); scanf( "%d", &a.i ); /* print each value printf( "%d printed printf( "%d printed printf( "%d printed printf( "%d printed  of as as as as  union */ a character is %c\n", a.i, a.c ); a short integer is %hd\n", a.i, a.s ); an integer is %d\n", a.i, a.i ); a long integer is %ld\n", a.i, a.l );  /* read a long integer from user into the union */ printf( "\nEnter a long integer: " ); scanf( "%ld", &a.l ); /* print each value of union */ printf( "%ld printed as a character is %c\n", a.l, a.c ); printf( "%ld printed as a short integer is %hd\n", a.l, a.s ); printf( "%ld printed as an integer is %d\n", a.l, a.i ); printf( "%ld printed as a long integer is %ld\n", a.l, a.l );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 339  Chapter 10  57 58 59  return 0; /* indicate successful termination */ } /* end main */  Enter a character: A 'A' printed as a character is A 'A' printed as a short integer is -13247 'A' printed as an integer is -858993599 'A' printed as a long integer is -858993599 Enter a short 97 printed as 97 printed as 97 printed as 97 printed as Enter 32700 32700 32700 32700  integer: 97 a character is a a short integer is 97 an integer is -859045791 a long integer is -859045791  an integer: 32700 printed as a character is + printed as a short integer is 32700 printed as an integer is 32700 printed as a long integer is 32700  Enter a long integer: 10000000 10000000 printed as a character is Ç 10000000 printed as a short integer is -27008 10000000 printed as an integer is 10000000 10000000 printed as a long integer is 10000000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  340 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  10.9 Create union floatingPoint with members float f, double d and long double x. Write a program that inputs value of type float, double and long double and stores the values in union variables of type union floatingPoint. Each union variable should be printed as a float, a double and a long double. Do the values always print correctly? 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  /* Exercise 10.9 Solution */ /* NOTE: The program output is machine dependent */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* floatingPoint union definition */ union floatingPoint { float f; /* floating-point value input by user */ double d; /* double value input by user */ long double l; /* long double value input by user */ }; /* end union floatingPoint */ int main() { union floatingPoint a; /* define union a */ /* read a floating-point value from user into the union */ printf( "Enter a float: " ); scanf( "%f", &a.f ); /* print each value printf( "%f printed printf( "%f printed printf( "%f printed  of as as as  union */ a float is %f\n", a.f, a.f ); a double is %f\n", a.f, a.d ); a long double is %Lf\n", a.f, a.l );  /* read a double value from user into the union */ printf( "\nEnter a double: " ); scanf( "%lf", &a.d ); /* print each value of union */ printf( "%lf printed as a float is %f\n", a.d, a.f ); printf( "%lf printed as a double is %f\n", a.d, a.d ); printf( "%lf printed as a long double is %Lf\n", a.d, a.l ); /* read a long double value from user into the union */ printf( "\nEnter a long double: " ); scanf( "%Lf", &a.l ); /* print each value of union */ printf( "%Lf printed as a float is %f\n", a.l, a.f ); printf( "%Lf printed as a double is %f\n", a.l, a.d ); printf( "%Lf printed as a long double is %Lf\n", a.l, a.l ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 10  Structures, Unions, Bit Manipulations and Enumerations: Solutions 341  Enter a float: 7.2 7.200000 printed as a float is 7.200000 7.200000 printed as a double is -92559604549802064000000000000000000000000000000 000000000000000.000000 7.200000 printed as a long double is -925596045498020640000000000000000000000000 00000000000000000000.000000 Enter a double: 3884.29382387423 3884.293824 printed as a float is 184710340379508400000000000000.000000 3884.293824 printed as a double is 3884.293824 3884.293824 printed as a long double is 3884.293824 Enter a long double: 833738.9384434797 833738.938443 printed as a float is -72537143835359183000.000000 833738.938443 printed as a double is 833738.938443 833738.938443 printed as a long double is 833738.938443  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  342 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  10.10 Write a program that right shifts an integer variable 4 bits. The program should print the integer in bits before and after the shift operation. Does your system place 0s or 1s in the vacated bits? 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  /* Exercise 10.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  void displayBits( unsigned value ); /* prototype */ int main() { unsigned val; /* value from user */ /* prompt user and read value */ printf( "Enter an integer: " ); scanf( "%u", &val ); /* display value before shifting */ printf( "%u before right shifting 4 bits is:\n", val ); displayBits( val ); /* display value after shifting */ printf( "%u after right shifting 4 bits is:\n", val ); displayBits( val >> 4 ); return 0; /* indicate successful termination */ } /* end main */ /* function displayBits prints each bit of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask = 1 << 15; /* bit mask */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= 16; c++ ) { value & displayMask ? putchar( '1' ) : putchar( '0' ); value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ } /* end for */ putchar( '\n' ); } /* end function displayBits */  Enter an integer: 1234 1234 before right shifting 4 bits is: 1234 = 00000100 11010010 1234 after right shifting 4 bits is: 77 = 00000000 01001101  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 343  Chapter 10  10.11 If your computer uses 2-byte integers, modify the program of Fig. 10.7 so that it works with 2-byte integers. 10.12 Left shifting an unsigned integer by 1 bit is equivalent to multiplying the value 2. Write function power2 that takes two integer arguments number and pow and calculates number * 2pow  Use the shift operator to calculate the result. Print the values as integers and as bits. 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 10.12 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* prototypes */ void displayBits( unsigned value ); unsigned power2( unsigned n, unsigned p ); int main() { unsigned number; /* value from user */ unsigned pow; /* number of bits to left shift */ unsigned result; /* result of shift */ /* prompt user and read two integers */ printf( "Enter two integers: " ); scanf( "%u%u", &number, &pow ); /* display bits of number */ printf( "number:\n" ); displayBits( number ); /* display bits of pow */ printf( "\npow:\n" ); displayBits( pow ); /* perform shift and display results */ result = power2( number, pow ); printf( "\n%u * 2^%u = %u\n", number, pow, result ); displayBits( result ); return 0; /* indicate successful termination */ } /* end main */ /* function power2 left shifts n by p */ unsigned power2( unsigned n, unsigned p ) { return n << p; } /* end function power2 */ /* display the bits of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask = 1 << 15; /* bit mask */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= 16; c++ ) { value & displayMask ? putchar( '1' ) : putchar( '0' ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  344 Structures, Unions, Bit Manipulations and Enumerations: Solutions  53 54 55 56 57 58 59 60 61 62  Chapter 10  value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ } /* end for */ putchar( '\n' ); } /* end function displayBits */  Enter two integers: 10 3 number: 10 = 00000000 00001010 pow: 3 = 00000000 00000011 10 * 2^3 = 80 80 = 00000000 01010000  10.13 The left-shift operator can be used to pack two character values into an unsigned integer variable. Write a program that inputs two characters from the keyboard and passes them to function packCharacters. To pack two characters into an unsigned integer variable, assign the first character to the unsigned variable, shift the unsigned variable left by 8 bit positions and combine the unsigned variable with the second character using the bitwise inclusive OR operator. The program should output the characters in their bit format before and after they are packed into the unsigned integer to prove that the characters are in fact packed correctly in the unsigned variable. 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  /* Exercise 10.13 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* prototypes */ unsigned packCharacters( char x, char y ); void displayBits( unsigned value ); int main() { char a; /* first character from user */ char b; /* second character from user */ unsigned result; /* result of packing both characters */ /* prompt user and read two characters */ printf( "Enter two characters: " ); scanf( "%c %c", &a, &b ); /* display first character as bits */ printf( "\'%c\' in bits as an unsigned integers is:\n", a ); displayBits( a ); /* display second character as bits */ printf( "\n\'%c\' in bits as an unsigned integers is:\n", b ); displayBits( b ); /* pack characters and display result */ result = packCharacters( a, b ); printf( "\n\'%c\' and \'%c\' packed in an unsigned integer:\n", a, b );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 345  Chapter 10  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 55 56 57 58 59 60 61 62 63 64 65 66 67  displayBits( result ); return 0; /* indicate successful termination */ } /* end main */ /* function packCharacters packs two characters into an unsigned int */ unsigned packCharacters( char x, char y ) { unsigned pack = x; /* initialize pack to x */ pack <<= 8; /* shift pack 8 bits to the left */ pack |= y; /* pack y using inclusive OR operator */ return pack; } /* end function packCharacters */ /* display the bits of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask = 1 << 15; /* bit mask */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= 16; c++ ) { value & displayMask ? putchar( '1' ) : putchar( '0' ); value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ } /* end for */ putchar( '\n' ); } /* end function displayBits */  Enter two characters: A B 'A' in bits as an unsigned integers is: 65 = 00000000 01000001 'B' in bits as an unsigned integers is: 66 = 00000000 01000010 'A' and 'B' packed in an unsigned integer: 16706 = 01000001 01000010  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  346 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  10.14 Using the right-shift operator, the bitwise AND operator and a mask, write function unpackCharacters that takes the unsigned integer from Exercise 10.13 and unpacks it into two characters. To unpack two characters from an unsigned integer, combine the unsigned integer with the mask 65280 (00000000 00000000 11111111 00000000) and right shift the result 8 bits. Assign the resulting value to a char variable. Then combine the unsigned integer with the mask 255 (00000000 00000000 00000000 11111111). Assign the result to another char variable. The program should print the unsigned integer in bits before it is unpacked, then print the characters in bits to confirm that they were unpacked correctly. 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 53  /* Exercise 10.14 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* prototypes */ void unpackCharacters( char *aPtr, char *bPtr, unsigned pack ); void displayBits( unsigned value ); int main() { char a; /* first character unpacked */ char b; /* second character unpacked */ unsigned packed = 16706; /* initialize packed value */ /* display bits of packed */ printf( "The packed character representation is:\n" ); displayBits( packed ); /* unpack packed and display results */ unpackCharacters( &a, &b, packed ); printf( "\nThe unpacked characters are \'%c\' and \'%c\'\n", a, b ); displayBits( a ); displayBits( b ); return 0; /* indicate successful termination */ } /* end main */ /* unpack two characters from pack void unpackCharacters( char *aPtr, { unsigned mask1 = 65280; /* mask unsigned mask2 = 255; /* mask  */ char *bPtr, unsigned pack ) for first character */ for second character */  *aPtr = ( pack & mask1 ) >> 8; /* separate first character */ *bPtr = ( pack & mask2 ); /* separate second character */ } /* end function unpackCharacters */ /* display the bits of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask = 1 << 15; /* bit mask */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= 16; c++ ) { value & displayMask ? putchar( '1' ) : putchar( '0' ); value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 347  Chapter 10  54 55 56 57 58  } /* end for */ putchar( '\n' ); } /* end function displayBits */  The packed character representation is: 16706 = 01000001 01000010 The unpacked characters are 'A' and 'B' 65 = 00000000 01000001 66 = 00000000 01000010  10.15 If your system uses 4-byte integers, rewrite the program of Exercise 10.13 to pack 4 characters. 10.16 If your system uses 4-byte integers, rewrite the function unpackCharacters of Exercise 10.14 to unpack 4 characters. Create the masks you need to unpack the 4 characters by left shifting the value 255 in the mask variable by 8 bits 0, 1, 2 or 3 times (depending on the byte you are unpacking).  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  348 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  10.17 Write a program that reverses the order of the bits in an unsigned integer value. The program should input the value from the user and call function reverseBits to print the bits in reverse order. Print the value in bits both before and after the bits are reversed to confirm that the bits are reversed properly. 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 53 54 55 56  /* Exercise 10.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* prototypes */ unsigned reverseBits( unsigned value ); void displayBits( unsigned value ); int main() { unsigned a; /* unsigned integer from user */ /* prompt user and read value */ printf( "Enter an unsigned integer: " ); scanf( "%u", &a ); /* display bits of a before reversed */ printf( "\nBefore bits are reversed:\n" ); displayBits( a ); /* reverse bits and display results */ a = reverseBits( a ); printf( "\nAfter bits are reversed:\n" ); displayBits( a ); return 0; /* indicate successful termination */ } /* end main */ /* reverseBits reverses the bits of value */ unsigned reverseBits( unsigned value ) { unsigned mask = 1; /* bit mask */ unsigned temp = 0; /* reversed bits */ int i; /* loop counter */ /* loop through bits of value */ for ( i = 0; i <= 15; i++ ) { temp <<= 1; /* right shift 1 bit */ temp |= ( value & mask ); /* separate bit and place in temp */ value >>= 1; /* left shift 1 bit */ } /* end for */ return temp; } /* end function reverseBits */ /* display the bits of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask = 1 << 15; /* bit mask */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= 16; c++ ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 349  Chapter 10  57 58 59 60 61 62 63 64 65 66 67  value & displayMask ? putchar( '1' ) : putchar( '0' ); value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ } /* end for */ putchar( '\n' ); } /* end function displayBits */  Enter an unsigned integer: 2127 Before bits are reversed: 2127 = 00001000 01001111 After bits are reversed: 61968 = 11110010 00010000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  350 Structures, Unions, Bit Manipulations and Enumerations: Solutions  Chapter 10  10.18 Modify function displayBits of Fig. 10.7 so it is portable between systems using 2-byte integers and systems using 4byte integers. [Hint: Use the sizeof operator to determine the size of an integer on a particular machine.] 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  /* Exercise 10.18 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      void displayBits( unsigned value ); /* prototype */ int main() { unsigned x; /* value from user */ /* prompt user and read value */ printf( "Enter an unsigned integer: " ); scanf( "%u", &x ); displayBits( x ); return 0; /* indicate successful termination */ } /* end main */ /* display the bits of value */ void displayBits( unsigned value ) { unsigned c; /* bit counter */ unsigned displayMask; /* bit mask */ /* if system uses 4-byte integers */ if ( sizeof( int ) == 4 ) { displayMask = 1 << 31; } /* end if */ else { /* assume default of 2-byte integers */ displayMask = 1 << 15; } /* end else */ printf( "%7u = ", value ); /* loop through bits */ for ( c = 1; c <= sizeof( int ) * 8; c++ ) { putchar( value & displayMask ? '1' : '0' ); value <<= 1; /* shift value 1 bit to the left */ if ( c % 8 == 0 ) { /* print a space */ putchar( ' ' ); } /* end if */ } /* end for */ putchar( '\n' ); } /* end function displayBits */  Enter an unsigned integer: 2345 2345 = 00000000 00000000 00001001 00101001  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Structures, Unions, Bit Manipulations and Enumerations: Solutions 351  Chapter 10  10.19 The following program uses function multiple to determine if the integer entered from the keyboard is a multiple of some integer X. Examine the function multiple, then determine the value of X. 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  /* ex10_19.c */ /* This program determines if a value is a multiple of X. */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int multiple( int num ); /* prototype */ int main() { int y; /* y will hold an integer entered by the user  */  printf( "Enter an integer between 1 and 32000: " ); scanf( "%d", &y ); /* if y is a multiple of X */ if ( multiple( y ) ) { printf( "%d is a multiple of X\n", y ); } /* end if */ else { printf( "%d is not a multiple of X\n", y ); } /* end else */ return 0; /* indicates successful termination */ } /* end main */ /* determine if num is a multiple of X */ int multiple( int num ) { int i; /* counter */ int mask = 1; /* initialize mask */ int mult = 1; /* initialize mult */ for ( i = 1; i <= 10; i++, mask <<= 1 ) { if ( ( num & mask ) != 0 ) { mult = 0; break; } /* end if */ } /* end for */ return mult; } /* end function multiple */  ANS:  Enter an integer between 1 and 32000: 1024 1024 is a multiple of X  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  352 Structures, Unions, Bit Manipulations and Enumerations: Solutions  10.20 What does the following program do? 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  /* ex10_20.c */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int mystery( unsigned bits ); /* prototype */ int main() { unsigned x; /* x will hold an integer entered by the user */ printf( "Enter an integer: " ); scanf( "%u", &x ); printf( "The result is %d\n", mystery( x ) ); return 0; /* indicates successful termination */ } /* end main */ /* What does this function do? int mystery( unsigned bits ) { unsigned i; /* unsigned mask = 1 << 31; /* unsigned total = 0; /*  */  counter */ initialize mask */ initialize total */  for ( i = 1; i <= 32; i++, bits <<= 1 ) { if ( ( bits & mask ) == mask ) { total++; } /* end if */ } /* end for */ return !( total % 2 ) ? 1 : 0; } /* end function mystery */  ANS:  Enter an integer: 5678 The result is 0  Enter an integer: 65 The result is 1  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 10  11 C File Processing: Solutions  SOLUTIONS 11.5  Fill in the blanks in each of the following: a) Computers store large amounts of data on secondary storage devices as . ANS: files. b) A(n) is composed of several fields. ANS: record. c) A field that may contain digits, letters and blanks is called a(n) field. ANS: alphanumeric. d) To facilitate the retrieval of specific records from a file, one field in each record is chosen as a(n) . ANS: key. e) The vast majority of information stored in computer systems is stored in files. ANS: sequential f) A group of related characters that conveys meaning is called a(n) . ANS: field. g) The file pointers for the three files that are opened automatically when program execution begins are named , and . ANS: stdin, stdout, stderr. h) Function writes a character to a specified file. ANS: fputc. i) Function writes a line to a specified file. ANS: fputs. j) Function is generally used to write data to a random-access file. ANS: fwrite. k) Function repositions the file position pointer to the beginning of the file. ANS: rewind.  11.6  State which of the following are true and which are false. If false, explain why. a) The impressive functions performed by computers essentially involve the manipulation of zeros and ones. ANS: True. b) People prefer to manipulate bits instead of characters and fields because bits are more compact. ANS: False. People prefer to manipulate characters and fields because they are less cumbersome and more understandable. c) People specify programs and data items as characters; computers then manipulate and process these characters as groups of zeros and ones. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  354 C File Processing: Solutions  Chapter 11  ANS: True. d) A person's zip code is an example of a numeric field. ANS: True. e) A person's street address is generally considered to be an alphabetic field in computer applications. ANS: False. A street address is generally considered to be alphanumeric. f) Data items processed by a computer form a data hierarchy in which data items become larger and more complex as we progress from fields to characters to bits etc. ANS: Data items process by a computer form a data hierarchy in which data items become larger and more complex as we progress from bits to characters to fields, etc. g) A record key identifies a record as belonging to a particular field. ANS: False. A record key identifies a record as belonging to a particular person or entity. h) Most organizations store all their information in a single file to facilitate computer processing. ANS: False. Most organizations have many files in which they store their information. i) Files are always referred to by name in C programs. ANS: False. A pointer to each file is used to refer to the file. j) When a program creates a file, the file is automatically retained by the computer for future reference. ANS: True. 11.7 Exercise 11.3 asked the reader to write a series of single statements. Actually, these statements form the core of an important type of file-processing program, namely, a file-matching program. In commercial data processing, it is common to have several files in each system. In an accounts receivable system, for example, there is generally a master file containing detailed information about each customer such as the customer's name, address, telephone number, outstanding balance, credit limit, discount terms, contract arrangements and possibly a condensed history of recent purchases and cash payments. As transactions occur (i.e., sales are made and cash payments arrive in the mail), they are entered into a file. At the end of each business period (i.e., a month for some companies, a week for others and a day in some cases) the file of transactions (called "trans.dat" in Exercise 11.3) is applied to the master file (called "oldmast.dat" in Exercise 11.3), thus updating each account's record of purchases and payments. After each of these updatings run, the master file is rewritten as a new file ("newmast.dat"), which is then used at the end of the next business period to begin the updating process again. File-matching programs must deal with certain problems that do not exist in single-file programs. For example, a match does not always occur. A customer on the master file might not have made any purchases or cash payments in the current business period, and therefore no record for this customer will appear on the transaction file. Similarly, a customer who did make some purchases or cash payments might have just moved to this community, and the company may not have had a chance to create a master record for this customer. Use the statements written in Exercise 11.3 as a basis for writing a complete file-matching accounts receivable program. Use the account number on each file as the record key for matching purposes. Assume that each file is a sequential file with records stored in increasing account number order. When a match occurs (i.e., records with the same account number appear on both the master file and the transaction file), add the dollar amount on the transaction file to the current balance on the master file and write the "newmast.dat" record. (Assume that purchases are indicated by positive amounts on the transaction file, and that payments are indicated by negative amounts.) When there is a master record for a particular account but no corresponding transaction record, merely write the master record to "newmast.dat". When there is a transaction record but no corresponding master record, print the message "Unmatched transaction record for account number …" (fill in the account number from the transaction record). ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  /* Exercise 11.7 Solution */ /* NOTE: This program was run using the */ /* data in Exercise 11.8 */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main() { int masterAccount; int transactionAccount; double masterBalance; double transactionBalance; char masterName[ 30 ]; FILE *ofPtr;  /* /* /* /* /* /*  account from old master file */ account from transactions file */ balance from old master file */ balance from transactions file */ name from master file */ old master file pointer */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 355  Chapter 11  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 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  FILE *tfPtr; FILE *nfPtr;  /* transactions file pointer */ /* new master file pointer */  /* terminate application if old master file cannot be opened */ if ( ( ofPtr = fopen( "oldmast.dat", "r" ) ) == NULL ) { printf( "Unable to open oldmast.dat\n" ); exit( 1 ); } /* end if */ /* terminate application if transactions file cannot be opened */ if ( ( tfPtr = fopen( "trans.dat", "r" ) ) == NULL ) { printf( "Unable to open trans.dat\n" ); exit( 1 ); } /* end if */ /* terminate application if new master file cannot be opened */ if ( ( nfPtr = fopen( "newmast.dat", "w" ) ) == NULL ) { printf( "Unable to open newmast.dat\n" ); exit( 1 ); } /* end if */ /* display account currently being processed */ printf( "Processing....\n" ); fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance ); /* while not the end of transactions file */ while ( !feof( tfPtr ) ) { /* read next record from old master file */ fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName, &masterBalance ); /* display accounts from master file until number of new account is reached */ while ( masterAccount < transactionAccount && !feof( ofPtr ) ) { fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName, masterBalance ); printf( "%d %s %.2f\n", masterAccount, masterName, masterBalance ); /* read next record from old master file */ fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName, &masterBalance ); } /* end while */ /* if matching account found, update balance and output account info */ if ( masterAccount == transactionAccount ) { masterBalance += transactionBalance; fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName, masterBalance ); printf( "%d %s %.2f\n", masterAccount, masterName, masterBalance ); } /* end if */ /* tell user if account from transactions file does not match account from master file */ else if ( masterAccount > transactionAccount ) { printf( "Unmatched transaction record for account %d\n", transactionAccount ); fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName, masterBalance ); printf( "%d %s %.2f\n", masterAccount, masterName, masterBalance ); } /* end else if */ else { printf( "Unmatched transaction record for account %d\n", transactionAccount ); } /* end else */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  356 C File Processing: Solutions  Chapter 11  84 85 /* get next account and balance from transactions file */ 86 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance ); 87 } /* end while */ 88 89 /* loop through file and display account number, name and balance */ 90 while ( !feof( ofPtr ) ) { 91 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName, 92 &masterBalance ); 93 fprintf( nfPtr, "%d %s %.2f", masterAccount, masterName, 94 masterBalance ); 95 printf( "%d %s %.2f", masterAccount, masterName, masterBalance ); 96 } /* end while */ 97 98 fclose( ofPtr ); /* close all file pointers */ 99 fclose( tfPtr ); 100 fclose( nfPtr ); 101 102 return 0; /* indicate successful termination */ 103 104 } /* end main */ Processing.... 100 Alan Jones 375.31 300 Mary Smith 89.30 Unmatched transaction record for account 400 500 Sam Sharp 0.00 700 Suzy Green -14.22 Unmatched transaction record for account 900  11.8 After writing the program of Exercise 11.7, write a simple program to create some test data for checking out the program of Exercise 11.7. Use the following sample account data: Master File: Account number  Name  Balance  100  Alan Jones  348.17  300  Mary Smith  500  Sam Sharp  0.00  700  Suzy Green  -14.22  Transaction File: Account number  Dollar amount  100  27.14  300  62.11  400  100.56  900  82.17  27.19  ANS: 1 2 3 4 5 6  /* Exercise 11.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { int account;  /* account number */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 357  Chapter 11  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  char name[ 30 ]; double balance; double amount; FILE *ofPtr; FILE *tfPtr;  /* /* /* /* /*  account name */ account balance */ transaction amount */ old master file pointer */ transaction file pointer */  /* open both files for writing */ ofPtr = fopen( "oldmast.dat", "w" ); tfPtr = fopen( "trans.dat", "w" ); /* prompt user for sample data */ printf( "Sample data for file oldmast.dat:\n" ); printf( "Enter account, name, and balance (EOF to end): " ); /* loop while EOF character not entered by user */ while ( scanf( "%d%[^0-9-]%lf", &account, name, &balance ) != EOF ) { /* write data to old master file */ fprintf( ofPtr, "%d %s %.2f\n", account, name, balance ); printf( "Enter account, name, and balance (EOF to end): " ); } /* end while */ fclose( ofPtr ); /* close file pointer */ /* prompt user for sample data */ printf( "\nSample data for file trans.dat:\n" ); printf( "Enter account and transaction amount (EOF to end): " ); /* loop while EOF character not entered by user */ while ( scanf( "%d%lf", &account, &amount ) != EOF ) { /* write data to transactions file */ fprintf( tfPtr, "%d %.2f\n", account, amount ); printf( "Enter account and transaction amount (EOF to end): " ); } /* end while */ fclose( tfPtr ); /* close file pointer */ return 0; /* indicate successful termination */ } /* end main */  Sample data for file Enter account, name, Enter account, name, Enter account, name, Enter account, name, Enter account, name,  oldmast.dat: and balance (EOF and balance (EOF and balance (EOF and balance (EOF and balance (EOF  Sample data for file trans.dat: Enter account and transaction amount Enter account and transaction amount Enter account and transaction amount Enter account and transaction amount Enter account and transaction amount  to to to to to  (EOF (EOF (EOF (EOF (EOF  end): end): end): end): end):  to to to to to  100 300 500 700 ^Z  end): end): end): end): end):  Alan Jones 348.17 Mary Smith 27.19 Sam Sharp 0.00 Suzy Green -14.22  100 300 400 900 ^Z  27.14 62.11 100.56 82.17  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  358 C File Processing: Solutions  Chapter 11  11.9 Run the program of Exercise 11.7 using the files of test data created in Exercise 11.8. Use the listing program of Section 11.7 to print the new master file. Check the results carefully. 11.10 It is possible (actually common) to have several transaction records with the same record key. This occurs because a particular customer might make several purchases and cash payments during a business period. Rewrite your accounts receivable filematching program of Exercise 11.7 to provide for the possibility of handling several transaction records with the same record key. Modify the test data of Exercise 11.8 to include the following additional transaction records: Account number  Dollar amount  300  83.89  700  80.78  700  1.53  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  /* Exercise 11.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { int masterAccount; int transactionAccount; double masterBalance; double transactionBalance; char masterName[ 30 ]; FILE *ofPtr; FILE *tfPtr; FILE *nfPtr;  /* /* /* /* /* /* /* /*  account from old master file */ account from transactions file */ balance from old master file */ balance from transactions file */ name from master file */ old master file pointer */ transactions file pointer */ new master file pointer */  /* terminate application if old master file cannot be opened */ if ( ( ofPtr = fopen( "oldmast.dat", "r" ) ) == NULL ) { printf( "Unable to open oldmast.dat\n" ); exit( 1 ); } /* end if */ /* terminate application if transactions file cannot be opened */ if ( ( tfPtr = fopen( "trans.dat", "r" ) ) == NULL ) { printf( "Unable to open trans.dat\n" ); exit( 1 ); } /* end if */ /* terminate application if new master file cannot be opened */ if ( ( nfPtr = fopen( "newmast.dat", "w" ) ) == NULL ) { printf( "Unable to open newmast.dat\n" ); exit( 1 ); } /* end if */ /* display account currently being processed */ printf( "Processing....\n" ); fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance ); /* while not the end of transactions file */ while ( !feof( tfPtr ) ) { /* read next record from old master file */ fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName, &masterBalance ); /* display accounts from master file until number of new account is reached */ while ( masterAccount < transactionAccount && !feof( ofPtr ) ) { fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName, masterBalance ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 11  C File Processing: Solutions 359  50 printf( "%d %s %.2f\n", masterAccount, masterName, 51 masterBalance ); 52 53 /* read next record from old master file */ 54 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, 55 masterName, &masterBalance ); 56 } /* end while */ 57 58 /* if matching account found, update balance and output 59 account info */ 60 if ( masterAccount == transactionAccount ) { 61 62 /* while more transactions exist for current account */ 63 while ( masterAccount == transactionAccount && 64 !feof( tfPtr ) ) { 65 66 /* update masterBalance and read next record */ 67 masterBalance += transactionBalance; 68 fscanf( tfPtr, "%d%lf", &transactionAccount, 69 &transactionBalance ); 70 } /* end while */ 71 72 fprintf( nfPtr, "%d %s %.2f\n", 73 masterAccount, masterName, masterBalance ); 74 printf( "%d %s %.2f\n", masterAccount, masterName, masterBalance ); 75 } /* end if */ 76 77 /* tell user if account from transactions file does 78 not match account from master file */ 79 else if ( masterAccount > transactionAccount ) { 80 printf( "Unmatched transaction record for account %d\n", 81 transactionAccount ); 82 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName, masterBalance ); 83 printf( "%d %s %.2f\n", masterAccount, masterName, masterBalance ); 84 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance ); 85 } /* end else if */ 86 else { 87 printf( "Unmatched transaction record for account %d\n", 88 transactionAccount ); 89 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance ); 90 } /* end else */ 91 92 } /* end while */ 93 94 /* loop through file and display account number, name and balance */ 95 while ( !feof( ofPtr ) ) { 96 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName, 97 &masterBalance ); 98 fprintf( nfPtr, "%d %s %.2f", masterAccount, masterName, 99 masterBalance ); 100 printf( "%d %s %.2f", masterAccount, masterName, masterBalance ); 101 } /* end while */ 102 103 fclose( ofPtr ); /* close all file pointers */ 104 fclose( tfPtr ); 105 fclose( nfPtr ); 106 107 return 0; /* indicate successful termination */ 108 109 } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  360 C File Processing: Solutions  Chapter 11  Processing.... 100 Alan Jones 375.31 300 Mary Smith 173.19 Unmatched transaction record for account 400 500 Sam Sharp 0.00 700 Suzy Green 68.09 Unmatched transaction record for account 900  11.11 Write statements that accomplish each of the following. Assume that the structure struct person { char lastName[ 15 ]; char firstName[ 15 ]; char age[ 4 ]; };  has been defined and that the file is already open for writing. a) Initialize the file "nameage.dat" so that there are 100 records with lastName = "unassigned", firstname = "" and age = "0". b) Input 10 last names, first names and ages, and write them to the file. c) Update a record; if there is no information in the record, tell the user "No info". d) Delete a record that has information by reinitializing that particular record. 11.12 You are the owner of a hardware store and need to keep an inventory that can tell you what tools you have, how many you have and the cost of each one. Write a program that initializes the file "hardware.dat" to 100 empty records, lets you input the data concerning each tool, enables you to list all your tools, lets you delete a record for a tool that you no longer have and lets you update any information in the file. The tool identification number should be the record number. Use the following information to start your file:  Record #  Tool name  Quantity  Cost  3  Electric sander  7  57.98  17  Hammer  76  11.99  24  Jig saw  21  11.00  39  Lawn mower  3  79.50  56  Power saw  18  99.99  68  Screwdriver  106  6.99  77  Sledge hammer  11  21.50  83  Wrench  34  7.50  11.13 Telephone Number Word Generator. Standard telephone keypads contain the digits 0 through 9. The numbers 2 through 9 each have three letters associated with them, as is indicated by the following table:  Digit  Letter  2  A B C  3  D E F  4  G H I  5  J K L  6  M N O  7  P R S  8  T U V  9  W X Y  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 361  Chapter 11  Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in the above table to develop the seven-letter word "NUMBERS." Businesses frequently attempt to get telephone numbers that are easy for their clients to remember. If a business can advertise a simple word for its customers to dial, then no doubt the business will receive a few more calls. Each seven-letter word corresponds to exactly one seven-digit telephone number. The restaurant wishing to increase its takehome business could surely do so with the number 825-3688 (i.e., "TAKEOUT"). Each seven-digit phone number corresponds to many separate seven-letter words. Unfortunately, most of these represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a barber shop would be pleased to know that the shop's telephone number, 424-7288, corresponds to "HAIRCUT." The owner of a liquor store would, no doubt, be delighted to find that the store's telephone number, 233-7226, corresponds to "BEERCAN." A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters "PETCARE." Write a C program that, given a seven-digit number, writes to a file every possible seven-letter word corresponding to that number. There are 2187 (3 to the seventh power) such words. Avoid phone numbers with the digits 0 and 1. 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  /* Exercise 11.13 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      void wordGenerator( int number[] ); /* prototype */ int main() { int loop; /* loop counter */ int phoneNumber[ 7 ] = { 0 }; /* holds phone number */ /* prompt user to enter phone number */ printf( "Enter a phone number one digit at a time" ); printf( " using the digits 2 thru 9:\n" ); /* loop 7 times for ( loop = 0; printf( "? " scanf( "%d",  to get number */ loop <= 6; loop++ ) { ); &phoneNumber[ loop ] );  /* test if number is between 0 and 9 */ while ( phoneNumber[ loop ] < 2 || phoneNumber[ loop ] > 9 ) { printf( "\nInvalid number entered. Please enter again: " ); scanf( "%d", &phoneNumber[ loop ] ); } /* end while */ } /* end for */ wordGenerator( phoneNumber ); /* form words from phone number */ return 0; /* indicate successful termination */ } /* end main */ /* function to form words based on phone number */ void wordGenerator( int number[] ) { int loop; /* loop counter */ int loop1; /* loop counter for first digit of phone number */ int loop2; /* loop counter for second digit of phone number */ int loop3; /* loop counter for third digit of phone number */ int loop4; /* loop counter for fourth digit of phone number */ int loop5; /* loop counter for fifth digit of phone number */ int loop6; /* loop counter for sixth digit of phone number */ int loop7; /* loop counter for seventh digit of phone number */ FILE *foutPtr; /* output file pointer */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  362 C File Processing: Solutions  47 /* letters corresponding to each number */ 48 char *phoneLetters[ 10 ] = { "", "", "ABC", "DEF", "GHI", "JKL", 49 "MNO", "PRS", "TUV", "WXY"}; 50 51 /* open output file */ 52 if ( ( foutPtr = fopen( "phone.out", "w" ) ) == NULL ) { 53 printf( "Output file was not opened.\n" ); 54 } /* end if */ 55 else { /* print all possible combinations */ 56 57 for ( loop1 = 0; loop1 <= 2; loop1++ ) { 58 59 for ( loop2 = 0; loop2 <= 2; loop2++ ) { 60 61 for ( loop3 = 0; loop3 <= 2; loop3++ ) { 62 63 for ( loop4 = 0; loop4 <= 2; loop4++ ) { 64 65 for ( loop5 = 0; loop5 <= 2; loop5++ ) { 66 67 for ( loop6 = 0; loop6 <= 2; loop6++ ) { 68 69 for ( loop7 = 0; loop7 <= 2; loop7++ ) { 70 fprintf( foutPtr, "%c%c%c%c%c%c%c\n", 71 phoneLetters[ number[ 0 ] ][ loop1 ], 72 phoneLetters[ number[ 1 ] ][ loop2 ], 73 phoneLetters[ number[ 2 ] ][ loop3 ], 74 phoneLetters[ number[ 3 ] ][ loop4 ], 75 phoneLetters[ number[ 4 ] ][ loop5 ], 76 phoneLetters[ number[ 5 ] ][ loop6 ], 77 phoneLetters[ number[ 6 ] ][ loop7 ] ); 78 } /* end for */ 79 80 } /* end for */ 81 82 } /* end for */ 83 84 } /* end for */ 85 86 } /* end for */ 87 88 } /* end for */ 89 90 } /* end for */ 91 92 /* output phone number */ 93 fprintf( foutPtr, "\nPhone number is " ); 94 95 /* loop through digits */ 96 for ( loop = 0; loop <= 6; loop++ ) { 97 98 /* insert hyphen */ 99 if ( loop == 3 ) { 100 fprintf( foutPtr, "-" ); 101 } /* end if */ 102 103 fprintf( foutPtr, "%d", number[ loop ] ); 104 } /* end for */ 105 106 } /* end else */ 107 108 fclose( foutPtr ); /* close file pointer */ 109 } /* end function wordGenerator  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 11  C File Processing: Solutions 363  Chapter 11  Enter a phone number one digit at a time using the digits 2 thru 9: ? 8 ? 4 ? 3 ? 2 ? 6 ? 7 ? 7  The contents of phone.out are: TGDAMPP TGDAMPR TGDAMPS TGDAMRP TGDAMRR TGDAMRS TGDAMSP TGDAMSR . . . VIFCORP VIFCORR VIFCORS VIFCOSP VIFCOSR VIFCOSS Phone number is 843-2677  11.14 If you have a computerized dictionary available, modify the program you wrote in Exercise 11.13 to look up the words in the dictionary. Some seven-letter combinations created by this program consist of two or more words (the phone number 843-2677 produces "THEBOSS").  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  364 C File Processing: Solutions  Chapter 11  11.15 Modify the example of Fig. 8.14 to use functions fgetc and fputs rather than getchar and puts. The program should give the user the option to read from the standard input and write to the standard output or to read from a specified file and write to a specified file. If the user chooses the second option, have the user enter the file names for the input and output files. 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 53 54 55 56 57 58 59 60 61 62  /* Exercise 11.15 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { char c; char sentence[ 80 ]; char input[ 20 ]; char output[ 20 ]; char choice[ 2 ]; int i = 0; FILE *infilePtr; FILE *outfilePtr;  /* /* /* /* /* /* /* /*  current character */ text from user or input file */ input file */ output file */ user's menu choice */ character counter */ input file pointer */ output file pointer */  /* display choices to user */ printf( "%s%s\n%s\n%s", "1 Read from standard input; ", "write to standard output", "2 Read from a file; write to file", "Enter choice: " ); scanf( "%s", choice ); /* while user does not enter a valid choice */ while ( choice[ 0 ] != '1' && choice[ 0 ] != '2' ) { printf( "Invalid choice. Choose again: " ); scanf( "%s", choice ); } /* end while */ /* if user chooses option 2 */ if ( choice[ 0 ] == '2' ) { printf( "Enter input file name: " ); /* get input file name */ scanf( "%s", input ); printf( "Enter output file name: " ); /* get output file name */ scanf( "%s", output ); /* exit program if unable to open input file */ if ( ( infilePtr = fopen( input, "r" ) ) == NULL ) { printf( "Unable to open %s\n", input ); exit( 1 ); } /* end if */ /* exit program if unable to open output file */ else if ( ( outfilePtr = fopen( output, "w" ) ) == NULL ) { printf( "Unable to open %s\n", output ); fclose( infilePtr ); exit( 1 ); } /* end if */ } /* end if */ else { /* if user chooses option 1 */ infilePtr = stdin; outfilePtr = stdout; } /* end else */ /* if user chooses option 1 */ if ( choice[ 0 ] == '1' ) { /* prompt user for text */ printf( "Enter a line of text:\n" ); scanf( " " ); /* Eliminate spaces and newlines at the start of the input stream */ } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 365  Chapter 11  63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82  /* read each character using fgetc */ while ( ( c = fgetc( infilePtr ) ) != '\n' && !feof( infilePtr ) ) { sentence[ i++ ] = c; } /* end while */ /* add terminating character and output text with fputs */ sentence[ i ] = '\0'; fprintf( outfilePtr, "\nThe line entered was:\n" ); fputs( sentence, outfilePtr ); /* close file pointers */ if ( choice[ 0 ] == '2' ) { fclose( infilePtr ); fclose( outfilePtr ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */  1 Read from standard input; write to standard output 2 Read from a file; write to file Enter choice: 1 Enter a line of text: This is a test. The line entered was: This is a test.  1 Read from standard input; write to standard output 2 Read from a file; write to a file Enter choice: 2 Enter input file name: test.dat Enter output file name: output.dat  Contents of test.dat  This is a test file for exercise 11.15.  Contents of output.dat  The line entered was: This is a test file for exercise 11.15.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  366 C File Processing: Solutions  Chapter 11  11.16 Write a program that uses the sizeof operator to determine the sizes in bytes of the various data types on your computer system. Write the results to the file "datasize.dat" so you may print the results later. The format for the results in the file should be as follows:  Data type char unsigned char short int unsigned short int int unsigned int long int unsigned long int float double long double  Size 1 1 2 2 4 4 4 4 4 8 16  [Note: The type sizes on your computer might be different from those listed above.] 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  /* Exercise 11.16 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { FILE *outPtr; /* output file pointer */ /* open datasize.dat for writing */ outPtr = fopen( "datasize.dat", "w" ); /* write size of various data types */ fprintf( outPtr, "%s%16s\n", "Data type", "Size" ); fprintf( outPtr, "%s%21d\n", "char", sizeof( char ) ); fprintf( outPtr, "%s%12d\n", "unsigned char", sizeof( unsigned char ) ); fprintf( outPtr, "%s%16d\n", "short int", sizeof( short int ) ); fprintf( outPtr, "%s%7d\n", "unsigned short int", sizeof( unsigned short int ) ); fprintf( outPtr, "%s%22d\n", "int", sizeof( int ) ); fprintf( outPtr, "%s%13d\n", "unsigned int", sizeof( unsigned int ) ); fprintf( outPtr, "%s%17d\n", "long int", sizeof( long int ) ); fprintf( outPtr, "%s%8d\n", "unsigned long int", sizeof( unsigned long int ) ); fprintf( outPtr, "%s%20d\n", "float", sizeof( float ) ); fprintf( outPtr, "%s%19d\n", "double", sizeof( double ) ); fprintf( outPtr, "%s%14d\n", "long double", sizeof( long double ) ); fclose( outPtr ); /* close file pointer */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 367  Chapter 11  Contents of datasize.dat  Data type char unsigned char short int unsigned short int int unsigned int long int unsigned long int float double long double  Size 1 1 2 2 4 4 4 4 4 8 8  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  368 C File Processing: Solutions  Chapter 11  11.17 In Exercise 7.19, you wrote a software simulation of a computer that used a special machine language called Simpletron Machine Language (SML). In the simulation, each time you wanted to run an SML program, you entered the program into the simulator from the keyboard. If you made a mistake while typing the SML program, the simulator was restarted and the SML code was reentered. It would be nice to be able to read the SML program from a file rather than type it each time. This would reduce time and mistakes in preparing to run SML programs. a) Modify the simulator you wrote in Exercise 7.19 to read SML programs from a file specified by the user at the keyboard. b) After the Simpletron executes, it outputs the contents of its registers and memory on the screen. It would be nice to capture the output in a file, so modify the simulator to write its output to a file in addition to displaying the output on the screen. 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 53 54 55  /* Exercise 11.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* define commands */ #define SIZE 100 #define TRUE 1 #define FALSE 0 #define READ 10 #define WRITE 11 #define LOAD 20 #define STORE 21 #define ADD 30 #define SUBTRACT 31 #define DIVIDE 32 #define MULTIPLY 33 #define BRANCH 40 #define BRANCHNEG 41 #define BRANCHZERO 42 #define HALT 43 /* function prototype */ void load( int *loadMemory ); void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, int *opCodePtr, int *opPtr ); void dump( int *memory, int accumulator, int instructionCounter, int instructionRegister, int operationCode, int operand ); int validWord( int word ); int main() { int memory[ SIZE ]; /* define memory array */ int ac = 0; /* accumulator */ int ic = 0; /* instruction counter */ int opCode = 0; /* operation code */ int op = 0; /* operand */ int ir = 0; /* instruction register */ int i; /* counter */ /* clear memory */ for ( i = 0; i < SIZE; i++ ) { memory[ i ] = 0; } /* end for */ load( memory ); execute( memory, &ac, &ic, &ir, &opCode, &op ); dump( memory, ac, ic, ir, opCode, op ); return 0; /* indicate successful termination */ } /* end main */ /* function loads instructions */ void load( int *loadMemory ) { © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C File Processing: Solutions 369  Chapter 11  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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123  int instruction; /* int i = 0; /* char fileName[ 36 ]; /* FILE *finPtr; /*  current instruction */ indexing variable */ input file name */ input file pointer */  /* prompt user for input file name */ printf( "Enter input file: " ); scanf( "%s", fileName ); /* open input file */ if ( ( finPtr = fopen( fileName, "r" ) ) == NULL ) { printf( "Data file was NOT opened.\n" ); } /* end if */ else { /* if file opened correctly */ fscanf( finPtr, "%d", &instruction ); /* while not end of file */ while ( !feof( finPtr ) ) { /* check if instruction is valid */ while ( !validWord( instruction ) ) { printf( "***DATA ERROR.\n" ); printf( "***check instructions in data file.\n" ); fscanf( finPtr, "%d", &instruction ); } /* end while */ /* load instruction and read next instruction */ loadMemory[ i++ ] = instruction; fscanf( finPtr, "%d", &instruction ); } /* end while */ } /* end else */ fclose( finPtr ); /* close file pointer */ } /* end function load */ /* carry out the commands */ void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, int *opCodePtr, int *opPtr ) { int fatal = FALSE; /* fatal error flag */ int temp; /* temporary holding space */ printf( "\n************START SIMPLETRON EXECUTION************\n\n" ); /* separate operation code and operand */ *irPtr = memory[ *icPtr ]; *opCodePtr = *irPtr / 100; *opPtr = *irPtr % 100; /* loop while command is not HALT or fatal */ while ( *opCodePtr != HALT && !fatal ) { /* determine appropriate action */ switch ( *opCodePtr ) { /* read data into location in memory */ case READ: printf( "Enter an integer: " ); scanf( "%d", &temp ); /* check for validity */ while ( !validWord( temp ) ) { printf( "Number out of range. Please enter again: " ); scanf( "%d", &temp ); } /* end while */ memory[ *opPtr ] = temp; /* write to memory */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  370 C File Processing: Solutions  124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191  ++( *icPtr ); break; /* exit switch */ /* write data from memory to screen */ case WRITE: printf( "Contents of %02d: %d\n", *opPtr, memory[ *opPtr ] ); ++( *icPtr ); break; /* exit switch */ /* load data from memory into accumulator */ case LOAD: *acPtr = memory[ *opPtr ]; ++( *icPtr ); break; /* exit switch */ /* store data from accumulator into memory */ case STORE: memory[ *opPtr ] = *acPtr; ++( *icPtr ); break; /* exit switch */ /* add data from memory to data in accumulator */ case ADD: temp = *acPtr + memory[ *opPtr ]; /* check validity */ if ( !validWord( temp ) ) { printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr = temp; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* subtract data in memory from data in accumulator */ case SUBTRACT: temp = *acPtr - memory[ *opPtr ]; /* check validity */ if ( !validWord( temp ) ) { printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr = temp; ++( *icPtr ); } /* end else */ break; /* exit switch */ /* divide data in memory into data in accumulator */ case DIVIDE: /* check for divide by zero error */ if ( memory[ *opPtr ] == 0 ) { printf( "*** FATAL ERROR: Attempt to divide by zero ***\n" ); printf( "*** Simpletron execution abnormally terminated ***\n" ); fatal = TRUE; } /* end if */ else { *acPtr /= memory[ *opPtr ]; ++( *icPtr ); } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 11  Chapter 11  C File Processing: Solutions 371  192 193 break; /* exit switch */ 194 195 /* multiple data in memory by data in accumulator */ 196 case MULTIPLY: 197 temp = *acPtr * memory[ *opPtr ]; 198 199 /* check validity */ 200 if ( !validWord( temp ) ) { 201 printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); 202 printf( "*** Simpletron execution abnormally terminated ***\n" ); 203 fatal = TRUE; 204 } /* end if */ 205 else { 206 *acPtr = temp; 207 ++( *icPtr ); 208 } /* end else */ 209 210 break; /* exit switch */ 211 212 /* branch to specific location in memory */ 213 case BRANCH: 214 *icPtr = *opPtr; 215 break; /* exit switch */ 216 217 /* branch to location in memory if accumulator is negative */ 218 case BRANCHNEG: 219 220 /* if accumulator is negative */ 221 if ( *acPtr < 0 ) { 222 *icPtr = *opPtr; 223 } /* end if */ 224 else { 225 ++( *icPtr ); 226 } /* end else */ 227 228 break; /* exit switch */ 229 230 /* branch to location in memory if accumulator is zero */ 231 case BRANCHZERO: 232 233 /* if accumulator is zero */ 234 if ( *acPtr == 0 ) { 235 *icPtr = *opPtr; 236 } /* end if */ 237 else { 238 ++( *icPtr ); 239 } /* end else */ 240 241 break; /* exit switch */ 242 243 default: 244 printf( "*** FATAL ERROR: Invalid opcode detected ***\n" ); 245 printf( "*** Simpletron execution abnormally terminated ***\n" ); 246 fatal = TRUE; 247 break; /* exit switch */ 248 } /* end switch */ 249 250 /* separate next operation code and operand */ 251 *irPtr = memory[ *icPtr ]; 252 *opCodePtr = *irPtr / 100; 253 *opPtr = *irPtr % 100; 254 } /* end while */ 255 256 printf( "\n*************END SIMPLETRON EXECUTION*************\n" ); 257 } /* end function execute */ 258  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  372 C File Processing: Solutions  259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322  /* print out name and content of each register and memory */ void dump( const int *memory, int accumulator, int instructionCounter, int instructionRegister, int operationCode, int operand ) { int i; /* counter */ char outputFile[ 36 ]; /* output file name */ FILE *foutPtr; /* output file pointer */ /* prompt user for output file name */ printf( "Enter output file name: " ); scanf( "%s", outputFile ); /* open output file for writing */ if ( ( foutPtr = fopen( outputFile, "w" ) ) == NULL ) { printf( "Output file was not opened.\n" ); } /* end if */ else { /* if file opened correctly, print headers to file */ fprintf( foutPtr, "\n%s\n%-23s%+05d\n%-23s%5.2d\n%-23s%+05d\n", "REGISTERS:", "accumulator", accumulator, "instructioncounter",instructionCounter, "instructionregister", instructionRegister ); fprintf( foutPtr, "%-23s%5.2d\n%-23s%5.2d", "operationcode", operationCode, "operand", operand ); fprintf( foutPtr, "\n\nMEMORY:\n " ); } /* end else */ /* print headers to screen */ printf( "\n%s\n%-23s%+05d\n%-23s%5.2d\n%-23s%+05d", "REGISTERS:", "accumulator", accumulator, "instructioncounter", instructionCounter, "instructionregister", instructionRegister); printf( "\n%-23s%5.2d\n%-23s%5.2d", "operationcode", operationCode, "operand", operand ); printf( "\n\nMEMORY:\n " ); /* print column headers */ for ( i = 0; i <= 9; i++ ) { printf( "%5d ", i ); fprintf( foutPtr, "%5d ", i ); } /* end for */ /* print row headers and memory contents */ for ( i = 0; i < SIZE; i++ ) { /* print in increments of 10 */ if ( i % 10 == 0 ) { printf( "\n%2d ", i ); fprintf( foutPtr, "\n%2d ", i ); } /* end for */ printf( "%+05d ", memory[ i ] ); fprintf( foutPtr, "%+05d ", memory[ i ] ); } /* end for */ printf( "\n" ); fprintf( foutPtr, "\n" ); fclose( foutPtr ); /* close file pointer */ } /* end function dump */ /* function tests validity of word */ int validWord( int word ) { return word >= -9999 && word <= 9999; } /* end function validWord */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 11  C File Processing: Solutions 373  Chapter 11  Enter input file: simple.in ************START SIMPLETRON EXECUTION************ Enter an integer: 5 Enter an integer: 2 Contents of 09: 7 *************END SIMPLETRON EXECUTION************* Enter output file name: simple.out REGISTERS: accumulator instructioncounter instructionregister operationcode operand  +0007 06 +4300 43 00  MEMORY: 0 10 20 30 40 50 60 70 80 90  0 +1007 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  1 +1008 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  2 +2007 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  3 +3008 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  4 +2109 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  5 +1109 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  6 +4300 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  7 +0005 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  8 +0002 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  9 +0007 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000  Contents of simple.in ( a simple addition program )  1007 1008 2007 3008 2109 1109 4300 0000 0000 0000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  374 C File Processing: Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 11  12 Data Structures: Solutions  SOLUTIONS 12.6 Write a program that concatenates two linked lists of characters. The program should include function concatenate that takes pointers to both lists as arguments and concatenates the second list to the first list. 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  /* Exercise 12.6 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* ListNode structure definition */ struct ListNode { char data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ }; /* end struct ListNode */ typedef struct ListNode ListNode; typedef ListNode *ListNodePtr; /* function prototypes */ void concatenate( ListNodePtr a, ListNodePtr b ); void insert( ListNodePtr *sPtr, char value ); void printList( ListNodePtr currentPtr ); int main() { ListNodePtr list1Ptr = NULL; /* pointer to first list */ ListNodePtr list2Ptr = NULL; /* pointer to second list */ char i; /* loop counter */ /* assign letters from A to C into first list */ for ( i = 'A'; i <= 'C'; i++ ) { insert( &list1Ptr, i ); } /* end for */ printf( "List 1 is: " );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  376 Data Structures: Solutions  31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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 92  printList( list1Ptr ); /* assign letters from D to F into second list */ for ( i = 'D'; i <= 'F'; i++ ) { insert( &list2Ptr, i ); } /* end for */ printf( "List 2 is: " ); printList( list2Ptr ); concatenate( list1Ptr, list2Ptr ); printf( "The concatenated list is: " ); printList( list1Ptr ); return 0; /* indicate successful termination */ } /* end main */ /* Concatenate two lists */ void concatenate( ListNodePtr a, ListNodePtr b ) { ListNodePtr currentPtr; /* temporary pointer */ currentPtr = a; /* set currentPtr to first linked list */ /* while currentPtr does not equal NULL */ while( currentPtr->nextPtr != NULL ) { currentPtr = currentPtr->nextPtr; } /* end while */ currentPtr->nextPtr = b; /* concatenate both lists */ } /* end function concatenate */ /* Insert a new value into the list in sorted order */ void insert( ListNodePtr *sPtr, char value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 377  Chapter 12  93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124  else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else { printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insert */ /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%c ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "*\n\n" ); } /* end else */ } /* end function printList */  List 1 is: A B C * List 2 is: D E F * The concatenated list is: A B C D E F *  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  378 Data Structures: Solutions  Chapter 12  12.7 Write a program that merges two ordered lists of integers into a single ordered list of integers. Function merge should receive pointers to the first node of each of the lists to be merged and should return a pointer to the first node of the merged list. 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 53 54 55 56 57  /* Exercise 12.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* ListNode structure definition */ struct ListNode { int data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ }; /* end struct ListNode */ typedef struct ListNode ListNode; typedef ListNode *ListNodePtr; /* function prototype */ void insert( ListNodePtr *sPtr, int value ); void printList( ListNodePtr currentPtr ); ListNodePtr merge( ListNodePtr a, ListNodePtr b ); int main() { ListNodePtr list1Ptr = NULL; /* pointer to first list */ ListNodePtr list2Ptr = NULL; /* pointer to second list */ ListNodePtr list3Ptr; /* pointer to merged list */ int i; /* loop counter */ /* build first list */ for ( i = 2; i <= 10; i += 2 ) { insert( &list1Ptr, i ); } /* end for */ printf( "List 1 is: " ); printList( list1Ptr ); /* build second list */ for ( i = 1; i <= 9; i += 2 ) { insert( &list2Ptr, i ); } /* end for */ printf( "List 2 is: " ); printList( list2Ptr ); /* merge both lists and print results */ list3Ptr = merge( list1Ptr, list2Ptr ); printf( "The merged list is: " ); printList( list3Ptr ); return 0; /* indicate successful termination */ } /* end main */ /* Merge two lists of integers ListNodePtr merge( ListNodePtr { ListNodePtr currentPtr1; /* ListNodePtr currentPtr2; /* ListNodePtr c = NULL; /*  */ a, ListNodePtr b ) pointer to first list */ pointer to second list */ pointer to merged list */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 379  Chapter 12  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 108 109 110 111 112 113 114 115 116 117 118 119  currentPtr1 = a; /* set currentPtr1 to first linked list */ currentPtr2 = b; /* set currentPtr2 to second linked list */ /* while currentPtr1 does not equal NULL */ while ( currentPtr1 != NULL ) { /* compare currentPtr1 and currentPtr2, insert lesser node */ if ( currentPtr2 == NULL || currentPtr1->data < currentPtr2->data ) { /* insert currentPtr1 node */ insert( &c, currentPtr1->data ); currentPtr1 = currentPtr1->nextPtr; } /* end if */ else { /* insert currentPtr2 node */ insert( &c, currentPtr2->data ); currentPtr2 = currentPtr2->nextPtr; } /* end else */ } /* end while */ /* insert any remaining nodes in currentPtr2 list */ while ( currentPtr2 != NULL ) { insert( &c, currentPtr2->data ); currentPtr2 = currentPtr2->nextPtr; } /* end while */ return c; /* return merged list */ } /* end function merge */ /* Insert a new value into the list in sorted order */ void insert( ListNodePtr *sPtr, int value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  380 Data Structures: Solutions  120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151  else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else { printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insert */ /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%d ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "*\n\n" ); } /* end else */ } /* end function printList */  List 1 is: 2 4 6 8 10 * List 2 is: 1 3 5 7 9 * The merged list is: 1 2 3 4 5 6 7 8 9 10 *  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 381  Chapter 12  12.8 Write a program that inserts 25 random integers from 0 to 100 in order in a linked list. The program should calculate the sum of the elements and the floating-point average of the elements. 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 53 54 55 56 57  /* Exercise 12.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* ListNode structure definition */ typedef struct ListNode { int data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ } ListNode; /* end struct ListNode */ typedef ListNode *ListNodePtr; /* function prototypes */ int sumList( ListNodePtr a ); double averageList( ListNodePtr a ); void insert( ListNodePtr *sPtr, int value ); void printList( ListNodePtr currentPtr ); int main() { ListNodePtr listPtr = NULL; /* list pointer */ int i; /* loop counter */ srand( time( NULL ) ); /* randomize */ /* build list with random numbers from 0 to 100 */ for ( i = 1; i <= 25; i++ ) { insert( &listPtr, rand() % 101 ); } /* end for */ printf( "The list is:\n" ); printList( listPtr ); /* calculate and display the sum and average of list values */ printf( "The sum is %d\n", sumList( listPtr ) ); printf( "The average is %f\n", averageList( listPtr ) ); return 0; /* indicate successful termination */ } /* end main */ /* Sum the integers in a list */ int sumList( ListNodePtr a ) { ListNodePtr currentPtr; /* temporary pointer to list a */ int total = 0; /* sum of node values */ currentPtr = a; /* set currentPtr to list a */ /* loop through list */ while ( currentPtr != NULL ) { /* add node value to total */ total += currentPtr->data; currentPtr = currentPtr->nextPtr; } /* end while */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  382 Data Structures: Solutions  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 108 109 110 111 112 113 114 115 116 117 118  return total; } /* end function sumList */ /* Average the integers in a list */ double averageList( ListNodePtr a ) { ListNodePtr currentPtr; /* temporary pointer to list a */ double total = 0.0; /* sum of node values */ int count = 0; /* number of nodes in list */ currentPtr = a; /* set currentPtr to list a */ /* loop through list */ while ( currentPtr != NULL ) { ++count; /* increment count */ total += currentPtr->data; /* update total */ currentPtr = currentPtr->nextPtr; } /* end while */ return total / count; /* return average */ } /* end function averageList */ /* Insert a new value into the list in sorted order */ void insert( ListNodePtr *sPtr, int value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 383  Chapter 12  119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143  printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insert */ /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%d ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "*\n\n" ); } /* end else */ } /* end function printList */  The list is: 6 12 14 20 27 31 31 34 37 38 56 59 63 66 72 73 73 76 77 79 88 94 95 96 97 * The sum is 1414 The average is 56.560000  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  384 Data Structures: Solutions  12.9  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 53 54 55 56 57  Write a program that creates a linked list of 10 characters, then creates a copy of the list in reverse order. ANS: /* Exercise 12.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* ListNode structure definition */ struct ListNode { char data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ }; /* end struct ListNode */ typedef struct ListNode ListNode; typedef ListNode *ListNodePtr; /* function prototypes */ ListNodePtr reverseList( ListNodePtr currentPtr ); void insert( ListNodePtr *sPtr, char value ); void printList( ListNodePtr currentPtr ); void push( ListNodePtr *topPtr, char info ); int main() { ListNodePtr listPtr = NULL; /* list pointer */ char i; /* loop counter */ /* build list with characters A to J */ for ( i = 'A'; i <= 'J'; i++ ) { insert( &listPtr, i ); } /* end for */ printf( "The list is:\n" ); printList( listPtr ); /* reverse the list and display result */ printf( "The list in reverse is:\n" ); printList( reverseList( listPtr ) ); return 0; /* indicate successful termination */ } /* end main */ /* Create a list in the reverse order of the list argument */ ListNodePtr reverseList( ListNodePtr currentPtr ) { ListNodePtr stack = NULL; /* pointer to reversed list */ /* loop through list currentPtr */ while ( currentPtr != NULL ) { /* push current element on to stack */ push( &stack, currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ return stack; /* return reversed list */ } /* end function reverseList */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 385  Chapter 12  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 108 109 110 111 112 113 114 115 116 117 118  /* Insert a new value into the list in sorted order */ void insert( ListNodePtr *sPtr, char value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else { printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insert */ /* Insert a node at the stack top */ void push( ListNodePtr *topPtr, char info ) { ListNodePtr newPtr; /* temporary node pointer */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if memory was allocated, insert node at top of list */ if ( newPtr ) { newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } /* end if */ else { printf( "%c not inserted. No memory available.\n", info ); } /* end else */ } /* end function push */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  386 Data Structures: Solutions  119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138  /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%c ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "*\n\n" ); } /* end else */ } /* end function printList */  The list is: A B C D E F G H I J * The list in reverse is: J I H G F E D C B A *  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 387  Chapter 12  12.10 Write a program that inputs a line of text and uses a stack to print the line reversed. 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 53 54 55 56 57 58  /* Exercise 12.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* stackNode structure definition */ struct stackNode { char data; /* node data */ struct stackNode *nextPtr; /* pointer to next node */ }; /* end struct stackNode */ typedef struct stackNode StackNode; typedef StackNode *StackNodePtr; /* function prototypes */ void push( StackNodePtr *topPtr, char info ); char pop( StackNodePtr *topPtr ); int isEmpty( StackNodePtr topPtr ); int main() { StackNodePtr stackPtr = NULL; /* points to the stack top */ char c; /* current character from text */ printf( "Enter a line of text:\n" ); /* read each letter with getchar and push on stack */ while ( ( c = getchar() ) != '\n' ) { push( &stackPtr, c ); } /* end while */ printf( "\nThe line is reverse is:\n" ); /* while the stack is not empty, pop next character */ while ( !isEmpty( stackPtr ) ) { printf( "%c", pop( &stackPtr ) ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */ /* Insert a node at the stack top */ void push( StackNodePtr *topPtr, char info ) { StackNodePtr newPtr; /* temporary node pointer */ /* dynamically allocate memory */ newPtr = malloc( sizeof( StackNode ) ); /* if memory was allocated, insert node at top of stack */ if ( newPtr ) { newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } /* end if */ else { printf( "%d not inserted. No memory available.\n", info ); } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  388 Data Structures: Solutions  59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82  } /* end function push */ /* Remove a node from the stack top */ char pop( StackNodePtr *topPtr ) { StackNodePtr tempPtr; /* temporary node pointer */ int popValue; /* value of popped node */ tempPtr = *topPtr; popValue = ( *topPtr )->data; *topPtr = ( *topPtr )->nextPtr; /* reset topPtr */ free( tempPtr ); /* free memory */ return popValue; /* return value of popped node */ } /* end function pop */ /* Is the stack empty? */ int isEmpty( StackNodePtr topPtr ) { return !topPtr; /* return NULL if stack is empty */ } /* end function isEmpty */  Enter a line of text: this is a line of text The line is reverse is: txet fo enil a si siht  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 389  Chapter 12  12.11 Write a program that uses a stack to determine if a string is a palindrome (i.e., the string is spelled identically backward and forward). The program should ignore spaces and punctuation. 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 53 54 55 56 57 58  /* Exercise 12.11 Solution #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              */  #define YES 1 #define NO 0 /* stackNode structure definition */ struct stackNode { char data; /* node data */ struct stackNode *nextPtr; /* pointer to next node */ }; /* end struct stackNode */ typedef struct stackNode STACKNODE; typedef STACKNODE *STACKNODEPTR; /* function prototypes */ void push( STACKNODEPTR *topPtr, char info ); char pop( STACKNODEPTR *topPtr ); int isEmpty( STACKNODEPTR topPtr ); int main() { STACKNODEPTR stackPtr = NULL; char c; char line[ 50 ]; char condensedLine[ 50 ]; int i = 0; int j = 0; int palindrome = YES;  /* /* /* /* /* /* /*  points to the stack top */ current character from text */ text from user */ text with only letters */ length of condensed line */ length of line */ result of palindrome test */  printf( "Enter a line of text:\n" ); /* read each letter with getchar and add to line */ while ( ( c = getchar() ) != '\n' ) { line[ j++ ] = c; /* remove all spaces and punctuation */ if ( isalpha( c ) ) { condensedLine[ i++ ] = tolower( c ); push( &stackPtr, tolower( c ) ); } /* end if */ } /* end while */ line[ j ] = '\0'; /* loop through condensedLine */ for ( j = 0; j < i; j++ ) { /* if condensedLine does not equal stack */ if ( condensedLine[ j ] != pop( &stackPtr ) ) { palindrome = NO; break; /* exit loop */ } /* end if */ } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  390 Data Structures: Solutions  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 108 109 110 111 112  /* if text is a palindrome */ if ( palindrome ) { printf( "\"%s\" is a palindrome\n", line ); } /* end if */ else { printf( "\"%s\" is not a palindrome\n", line ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* Insert a node at the stack top */ void push( STACKNODEPTR *topPtr, char info ) { STACKNODEPTR newPtr; /* temporary node pointer */ /* dynamically allocate memory */ newPtr = malloc( sizeof( STACKNODE ) ); /* if memory was allocated, insert node at top of stack */ if ( newPtr ) { newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } /* end if */ else { printf( "%d not inserted. No memory available.\n", info ); } /* end else */ } /* end function push */ /* Remove a node from the stack top */ char pop( STACKNODEPTR *topPtr ) { STACKNODEPTR tempPtr; /* temporary node pointer */ int popValue; /* value of popped node */ tempPtr = *topPtr; popValue = ( *topPtr )->data; *topPtr = ( *topPtr )->nextPtr; /* reset topPtr */ free( tempPtr ); /* free memory */ return popValue; /* return value of popped node */ } /* end function pop */ /* Is the stack empty? */ int isEmpty( STACKNODEPTR topPtr ) { return !topPtr; /* return NULL if stack is empty */ } /* end function isEmpty */  Enter a line of text: able was i ere i saw elba "able was i ere i saw elba" is a palindrome  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 391  Chapter 12  Enter a line of text: this is not a palindrome "this is not a palindrome" is not a palindrome  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  392 Data Structures: Solutions  Chapter 12  12.12 Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code. In this and the next exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4 and 7 / 9 in which the operator (+ or / here) is written between its operands— this is called infix notation. Computers "prefer" postfix notation in which the operator is written to the right of its two operands. The preceding infix expressions would appear in postfix notation as 3 4 + and 7 9 /, respectively. To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation, and then evaluate the postfix version of the expression. Each of these algorithms requires only a single left-to-right pass of the expression. Each algorithm uses a stack in support of its operation, and in each the stack is used for a different purpose. In this exercise, you will write a version of the infix-to-postfix conversion algorithm. In the next exercise, you will write a version of the postfix expression evaluation algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single digit integers such as (6 + 2) * 5 - 8 / 4  to a postfix expression. The postfix version of the preceding infix expression is 6 2 + 5 * 8 4 / -  The program should read the expression into character array infix, and use modified versions of the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The algorithm for creating a postfix expression is as follows: 1) Push a left parenthesis '(' onto the stack. 2) Append a right parenthesis ')' to the end of infix. 3) While the stack is not empty, read infix from left to right and do the following: If the current character in infix is a digit, copy it to the next element of postfix. If the current character in infix is a left parenthesis, push it onto the stack. If the current character in infix is an operator, Pop operators (if there are any) at the top of the stack while they have equal or higher precedence than the current operator, and insert the popped operators in postfix. Push the current character in infix onto the stack. If the current character in infix is a right parenthesis Pop operators from the top of the stack and insert them in postfix until a left parenthesis is at the top of the stack. Pop (and discard) the left parenthesis from the stack. The following arithmetic operations are allowed in an expression: + addition - subtraction * multiplication / division ^ exponentiation % remainder The stack should be maintained with the following declarations: struct stackNode { char data; struct stackNode *nextPtr; }; typedef struct stackNode StackNode; typedef StackNode *StackNodePtr;  The program should consist of main and eight other functions with the following function headers: void convertToPostfix( char infix[], char postfix[] )  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 393  Chapter 12  Convert the infix expression to postfix notation. int isOperator( char c )  Determine if c is an operator. int precedence( char operator1, char operator2 )  Determine if the precedence of operator1 is less than, equal to, or greater than the precedence of operator2. The function returns -1, 0 and 1, respectively. void push( StackNodePtr *topPtr, char value )  Push a value on the stack. char pop( StackNodePtr *topPtr )  Pop a value off the stack. char stackTop( StackNodePtr topPtr )  Return the top value of the stack without popping the stack. int isEmpty( StackNodePtr topPtr )  Determine if the stack is empty. void printStack( StackNodePtr topPtr )  Print the stack. 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  /* Exercise 12.12 Solution */ /* Infix to postfix conversion */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #define MAXCOLS 100 /* stackNode structure definition */ typedef struct stackNode { char data; /* node data */ struct stackNode *nextPtr; /* pointer to next node */ } STACKNODE; /* end struct stackNode */ typedef STACKNODE *STACKNODEPTR; /* function prototypes */ void convertToPostfix( char inFix[], char postFix[] ); int isOperator( char c ); int precedence( char operator1, char operator2 ); void push( STACKNODEPTR *topPtr, char info ); char pop( STACKNODEPTR *topPtr ); char stackTop( STACKNODEPTR topPtr ); int isEmpty( STACKNODEPTR topPtr ); void printStack( STACKNODEPTR currentPtr ); int main() { char c; char inFix[ MAXCOLS ];  /* current character from expression */ /* expression in infix notation */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  394 Data Structures: Solutions  32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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  Chapter 12  char postFix[ MAXCOLS ]; /* expression in postfix notation */ int pos = 0; /* indexing variable */ printf( "Enter the infix expression.\n" ); /* read each character with getchar */ while ( ( c = getchar() ) != '\n' ) { /* remove any spaces */ if ( c != ' ' ) { inFix[ pos++ ] = c; } /* end if */ } /* end while */ inFix[ pos ] = '\0'; /* print infix expression, convert to postfix and print */ printf( "%s\n%s\n", "The original infix expression is:", inFix ); convertToPostfix( inFix, postFix ); printf( "The expression in postfix notation is:\n%s\n", postFix ); return 0; /* indicate successful termination */ } /* end main */ /* convert infix expression to postfix notation */ void convertToPostfix( char inFix[], char postFix[] ) { STACKNODEPTR stackPtr = NULL; /* points to the stack top */ int i; /* loop counter */ int j; /* indexing variable */ int higher; /* operator flag */ char popValue; /* value of popped node */ /* push left parenthesis onto the stack */ push( &stackPtr, '(' ); printStack( stackPtr ); /* add a right parenthesis to infix */ strcat( inFix, " )" ); /* convert the infix expression to postfix */ for ( i = 0, j = 0; stackTop( stackPtr ); i++ ) { /* if current character is a digit */ if ( isdigit( inFix[ i ] ) ) { postFix[ j++ ] = inFix[ i ]; } /* end if */ /* if character is left else if ( inFix[ i ] == push( &stackPtr, '(' printStack( stackPtr } /* end else if */  parenthesis, push on stack */ '(' ) { ); );  /* if character is an operator */ else if ( isOperator( inFix[ i ] ) ) { higher = 1; /* used to store value of precedence test */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 395  Chapter 12  92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151  /* loop while current operator does not have the highest precedence */ while ( higher ) { /* if the top of the stack is an operator */ if ( isOperator( stackTop( stackPtr ) ) ) { /* compare precedence of operators */ if ( precedence( stackTop( stackPtr ), inFix[ i ] ) ) { postFix[ j++ ] = pop( &stackPtr ); printStack( stackPtr ); } /* end if */ else { higher = 0; /* reset flag */ } /* end else */ } /* end if */ else { higher = 0; /* reset flag */ } /* end else */ } /* end while */ push( &stackPtr, inFix[ i ] ); printStack( stackPtr ); } /* end else if */ /* if character is a right parenthesis */ else if ( inFix[ i ] == ')' ) { /* pop stack until popped value is a left parenthesis */ while ( ( popValue = pop( &stackPtr ) ) != '(' ) { printStack( stackPtr ); postFix[ j++ ] = popValue; } /* end while */ printStack( stackPtr ); } /* end else if */ } /* end for */ postFix[ j ] = '\0'; } /* end function convertToPostfix */ /* check if c is an operator */ int isOperator( char c ) { /* if c is an operator return true */ if ( c == '+' || c == '-' || c == '*' || c == '/' || c == '^' ) { return 1; } /* end if */ else { /* return false */ return 0; } /* end else */ } /* end function isOperator */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  396 Data Structures: Solutions  152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212  /* if the precedence of operator1 is >= operator2, return 1 ( true ), else return 0 ( false ) */ int precedence( char operator1, char operator2 ) { /* compare precedence of operator1 and operator2 */ if ( operator1 == '^' ) { return 1; } /* end if */ else if ( operator2 == '^' ) { return 0; } /* end else if */ else if ( operator1 == '*' || operator1 == '/' ) { return 1; } /* end else if */ else if ( operator1 == '+' || operator1 == '-' ) { /* if operator2 is * or / than return true */ if ( operator2 == '*' || operator2 == '/' ) { return 0; } /* end if */ else { return 1; } /* end else */ } /* end else if */ return 0; /* default */ } /* end function precedence */ /* Insert a node at the stack top */ void push( STACKNODEPTR *topPtr, char info ) { STACKNODEPTR newPtr; /* temporary node pointer */ /* dynamically allocate memory */ newPtr = malloc( sizeof( STACKNODE ) ); /* if memory was allocated, insert node at top of stack */ if ( newPtr ) { newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } /* end if */ else { printf( "%c not inserted. No memory available.\n", info ); } /* end else */ } /* end function push */ /* Remove a node from the stack top */ char pop( STACKNODEPTR *topPtr ) { STACKNODEPTR tempPtr; /* temporary node pointer */ char popValue; /* value of popped node */ tempPtr = *topPtr; popValue = ( *topPtr )->data; *topPtr = ( *topPtr )->nextPtr; /* reset topPtr */ free( tempPtr ); /* free memory */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 397  Chapter 12  213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258  return popValue; /* return value of popped node */ } /* end function pop */ /* View the top element of the stack */ char stackTop( STACKNODEPTR topPtr ) { /* if the stack is not empty */ if ( !isEmpty( topPtr ) ) { return topPtr->data; } /* end if */ else { return 0; } /* end else */ } /* end function stackTop */ /* Is the stack empty? */ int isEmpty( STACKNODEPTR topPtr ) { return !topPtr; /* return NULL if stack is empty */ } /* end function isEmpty */ /* Print the stack */ void printStack( STACKNODEPTR currentPtr ) { /* if the stack if ( currentPtr printf( "The } /* end if */ else { /* print  is empty */ == NULL ) { stack is empty.\n\n" ); stack */  /* loop through stack */ while ( currentPtr != NULL ) { printf( "%c ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "NULL\n" ); } /* end else */ } /* end function printStack */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  398 Data Structures: Solutions  Enter the infix expression. 1+(2*3-(4/5^6)*7)*8 The original infix expression is: 1+(2*3-(4/5^6)*7)*8 ( NULL + ( NULL ( + ( NULL * ( + ( NULL ( + ( NULL ( + ( NULL ( ( + ( NULL / ( ( + ( NULL ^ / ( ( + ( NULL / ( ( + ( NULL ( ( + ( NULL ( + ( NULL * ( + ( NULL ( + ( NULL ( + ( NULL + ( NULL * + ( NULL + ( NULL ( NULL The stack is empty. The expression in postfix notation is: 123*456^/7*-8*+  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 399  Chapter 12  12.13 Write a program that evaluates a postfix expression (assume it is valid) such as 6 2 + 5 * 8 4 / -  The program should read a postfix expression consisting of digits and operators into a character array. Using modified versions of the stack functions implemented earlier in this chapter, the program should scan the expression and evaluate it. The algorithm is as follows: 1) Append the null character ('\0') to the end of the postfix expression. When the null character is encountered, no further processing is necessary. 2) While '\0' has not been encountered, read the expression from left to right. If the current character is a digit, Push its integer value onto the stack (the integer value of a digit character is its value in the computer's character set minus the value of '0' in the computer's character set). Otherwise, if the current character is an operator, Pop the two top elements of the stack into variables x and y. Calculate y operator x. Push the result of the calculation onto the stack. 3) When the null character is encountered in the expression, pop the top value of the stack. This is the result of the postfix expression. [Note: In 2) above, if the operator is '/', the top of the stack is 2, and the next element in the stack is 8, then pop 2 into x, pop 8 into y, evaluate 8 / 2, and push the result, 4, back on the stack. This note also applies to operator '-'.] The arithmetic operations allowed in an expression are: + addition - subtraction * multiplication / division ^ exponentiation % remainder] The stack should be maintained with the following declarations: struct stackNode { int data; struct stackNode *nextPtr; }; typedef struct stackNode StackNode; typedef StackNode *StackNodePtr;  The program should consist of main and six other functions with the following function headers: int evaluatePostfixExpression( char *expr )  Evaluate the postfix expression. int calculate( int op1, int op2, char operator )  Evaluate the expression op1 operator op2. void push( StackNodePtr *topPtr, int value )  Push a value on the stack. int pop( StackNodePtr *topPtr )  Pop a value off the stack. int isEmpty( StackNodePtr topPtr )  Determine if the stack is empty. void printStack( StackNodePtr topPtr ) © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  400 Data Structures: Solutions  Print the stack. 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 53 54 55 56 57 58  /* Exercise 12.13 Solution */ /* Using a stack to evaluate an expression in postfix notation */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* StackNode structure definition */ struct StackNode { int data; /* node data */ struct StackNode *nextPtr; /* pointer to next node */ }; /* end struct StackNode */ typedef struct StackNode StackNode; typedef StackNode *StackNodePtr; /* function prototypes */ int evaluatePostfixExpression( char *expr ); int calculate( int op1, int op2, char operator ); void push( StackNodePtr *topPtr, int info ); int pop( StackNodePtr *topPtr ); int isEmpty( StackNodePtr topPtr ); void printStack( StackNodePtr currentPtr ); int main() { char expression[ 100 ]; /* postfix expression */ char c; /* current character from expression */ int answer; /* expression answer */ int i = 0; /* indexing variable */ printf( "Enter a postfix expression:\n" ); /* read each character with getchar */ while ( ( c = getchar() ) != '\n' ) { /* remove any spaces */ if ( c != ' ' ) { expression[ i++ ] = c; } /* end if */ } /* end while */ expression[ i ] = '\0'; /* calculate answer and print result */ answer = evaluatePostfixExpression( expression ); printf( "The value of the expression is: %d\n", answer ); return 0; /* indicate successful termination */ } /* end main */ /* evaluate the postfix expression */ int evaluatePostfixExpression( char *expr ) { int i; /* loop counter */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 401  Chapter 12  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 108 109 110 111 112 113 114 115 116 117 118 119  int popVal1; /* int popVal2; /* StackNodePtr stackPtr = NULL; /* char c; /*  right value of current operation */ left value of current operation */ points to the stack top */ current character */  /* loop through expression */ for ( i = 0; ( c = expr[ i ] ) != '\0'; i++ ) { /* if character is a digit, if ( isdigit( c ) ) { push( &stackPtr, c - '0' printStack( stackPtr ); } /* end if */ else { /* calculate current popVal2 = pop( &stackPtr printStack( stackPtr ); popVal1 = pop( &stackPtr printStack( stackPtr );  push it on stack */ );  operation */ ); );  /* calculate answer and push on stack */ push( &stackPtr, calculate( popVal1, popVal2, c ) ); printStack( stackPtr ); } /* end else */ } /* end for */ return pop( &stackPtr ); /* return final answer */ } /* end function evaluatePostfixExpression */ /* evaluate the expression op1 operator op2 */ int calculate( int op1, int op2, char operator ) { /* use correct operator to calculate answer */ switch( operator ) { case '+': /* addition */ return op1 + op2; case '-': /* subtraction */ return op1 - op2; case '*': /* multiplication */ return op1 * op2; case '/': /* division */ return op1 / op2; case '^': /* exponentiation */ return pow( op1, op2 ); } /* end switch */ return 0; /* default */ } /* end function calculate */ /* Insert a node at the stack top */ void push( StackNodePtr *topPtr, int info ) { StackNodePtr newPtr; /* temporary node pointer */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  402 Data Structures: Solutions  120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169  /* dynamically allocate memory */ newPtr = malloc( sizeof( StackNode ) ); /* if memory was allocated, insert node at top of stack */ if ( newPtr ) { newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } /* end if */ else { printf( "%d not inserted. No memory available.\n", info ); } /* end else */ } /* end function push */ /* Remove a node from the stack top */ int pop( StackNodePtr *topPtr ) { StackNodePtr tempPtr; /* temporary node pointer */ int popValue; /* value of popped node */ tempPtr = *topPtr; popValue = ( *topPtr )->data; *topPtr = ( *topPtr )->nextPtr; /* reset topPtr */ free( tempPtr ); /* free memory */ return popValue; /* return value of popped node */ } /* end function pop */ /* Is the stack empty? */ int isEmpty( StackNodePtr topPtr ) { return !topPtr; /* return NULL if stack is empty */ } /* end function isEmpty */ /* Print the stack */ void printStack( StackNodePtr currentPtr ) { /* loop through stack */ while ( currentPtr != NULL ) { printf( "%d ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "NULL\n" ); } /* end function printStack */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 403  Chapter 12  Enter a postfix expression: 123*456^/7*-8*+ 1 NULL 2 1 NULL 3 2 1 NULL 2 1 NULL 1 NULL 6 1 NULL 4 6 1 NULL 5 4 6 1 NULL 6 5 4 6 1 NULL 5 4 6 1 NULL 4 6 1 NULL 15625 4 6 1 NULL 4 6 1 NULL 6 1 NULL 0 6 1 NULL 7 0 6 1 NULL 0 6 1 NULL 6 1 NULL 0 6 1 NULL 6 1 NULL 1 NULL 6 1 NULL 8 6 1 NULL 6 1 NULL 1 NULL 48 1 NULL 1 NULL NULL 49 NULL The value of the expression is: 49  12.14 Modify the postfix evaluator program of Exercise 12.13 so that it can process integer operands larger than 9.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  404 Data Structures: Solutions  Chapter 12  12.15 (Supermarket Simulation) Write a program that simulates a check-out line at a supermarket. The line is a queue. Customers arrive in random integer intervals of 1 to 4 minutes. Also, each customer is serviced in random integer intervals of 1 to 4 minutes. Obviously, the rates need to be balanced. If the average arrival rate is larger than the average service rate, the queue will grow infinitely. Even with balanced rates, randomness can still cause long lines. Run the supermarket simulation for a 12-hour day (720 minutes) using the following algorithm: Choose a random integer between 1 and 4 to determine the minute at which the first customer arrives. 2) At the first customer's arrival time: Determine customer's service time (random integer from 1 to 4); Begin servicing the customer; Schedule arrival time of next customer (random integer 1 to 4 added to the current time). 3) For each minute of the day: If the next customer arrives, Say so; Enqueue the customer; Schedule the arrival time of the next customer; If service was completed for the last customer; Say so; Dequeue next customer to be serviced; Determine customer's service completion time (random integer from 1 to 4 added to the current time). Now run your simulation for 720 minutes and answer each of the following: a) What is the maximum number of customers in the queue at any time? b) What is the longest wait any one customer experienced? c) What happens if the arrival interval is changed from 1 to 4 minutes to 1 to 3 minutes?  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 405  Chapter 12  12.16 Modify the program of Fig. 12.19 to allow the binary tree to contain duplicate values. 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 53 54 55 56 57 58  /* Exercise 12.16 Solution */ /* This is a modification of figure 12.19 */ /* Only function insertNode has been modified */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* TreeNode structure definition struct TreeNode { struct TreeNode *leftPtr; /* int data; /* struct TreeNode *rightPtr; /* }; /* end struct TreeNode */  */ pointer to left subtree */ node data */ pointer to right subtree */  typedef struct TreeNode TreeNode; typedef TreeNode *TreeNodePtr; /* function prototypes */ void insertNode( TreeNodePtr *treePtr, int value ); void inOrder( TreeNodePtr treePtr ); void preOrder( TreeNodePtr treePtr ); void postOrder( TreeNodePtr treePtr ); int main() { int i; /* loop counter */ int item; /* random value to insert in tree */ TreeNodePtr rootPtr = NULL; /* points to the tree root */ srand( time( NULL ) ); /* randomize */ printf( "The numbers being placed in the tree are:\n" ); /* insert random values between 1 and 15 in the tree */ for ( i = 1; i <= 10; i++ ) { item = rand() % 15; printf( "%3d", item ); insertNode( &rootPtr, item ); } /* end for */ /* traverse the tree preorder */ printf( "\n\nThe preorder traversal is:\n" ); preOrder( rootPtr ); /* traverse the tree inorder */ printf( "\n\nThe inorder traversal is:\n" ); inOrder( rootPtr ); /* traverse the tree postorder */ printf( "\n\nThe postorder traversal is:\n" ); postOrder( rootPtr ); return 0; /* indicate successful termination */ } /* end main */ /* insert a node into the tree */ void insertNode( TreeNodePtr *treePtr, int value ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  406 Data Structures: Solutions  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 108 109 110 111 112 113 114 115 116 117  /* if treePtr is NULL */ if ( !*treePtr ) { /* dynamically allocate memory */ *treePtr = malloc( sizeof( TreeNode ) ); /* if memory was allocated, insert node */ if ( *treePtr ) { ( *treePtr )->data = value; ( *treePtr )->leftPtr = NULL; ( *treePtr )->rightPtr = NULL; } /* end if */ else { printf( "%d not inserted. No memory available.\n", value ); } /* end else */ return; } /* end if */ else { /* recursively call insertNode */ /* insert node in left subtree */ if ( value <= ( *treePtr )->data ) { insertNode( &( ( *treePtr )->leftPtr ), value ); } /* end if */ else { /* insert node in right subtree */ insertNode( &( ( *treePtr )->rightPtr ), value ); } /* end else */ } /* end else */ } /* end function insertNode */ /* traverse the tree inorder */ void inOrder( TreeNodePtr treePtr ) { /* traverse left subtree, print node, traverse right subtree */ if ( treePtr ) { inOrder( treePtr->leftPtr ); printf( "%3d", treePtr->data ); inOrder( treePtr->rightPtr ); } /* end if */ } /* end function inOrder */ /* traverse the tree preorder */ void preOrder( TreeNodePtr treePtr ) { /* print node, traverse left subtree, traverse right subtree */ if ( treePtr ) { printf( "%3d", treePtr->data ); preOrder( treePtr->leftPtr ); preOrder( treePtr->rightPtr ); } /* end if */ } /* end function preOrder */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 407  Chapter 12  118 119 120 121 122 123 124 125 126 127 128 129  /* traverse the tree postorder */ void postOrder( TreeNodePtr treePtr ) { /* traverse left subtree, traverse right subtree, print node */ if ( treePtr ) { postOrder( treePtr->leftPtr ); postOrder( treePtr->rightPtr ); printf( "%3d", treePtr->data ); } /* end if */ } /* end function postOrder */  The numbers being placed in the tree are: 14 3 7 7 3 12 7 11 1 2 The preorder traversal is: 14 3 3 1 2 7 7 7 12 11 The inorder traversal is: 1 2 3 3 7 7 7 11 12 14 The postorder traversal is: 2 1 3 7 7 11 12 7 3 14  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  408 Data Structures: Solutions  Chapter 12  12.17 Write a program based on the program of Fig. 12.19 that inputs a line of text, tokenizes the sentence into separate words, inserts the words in a binary search tree, and prints the inorder, preorder, and postorder traversals of the tree. [Hint: Read the line of text into an array. Use strtok to tokenize the text. When a token is found, create a new node for the tree, assign the pointer returned by strtok to member string of the new node, and insert the node in the tree.] 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 53 54 55  /* Exercise 12.17 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* TreeNode structure definition struct TreeNode { struct TreeNode *leftPtr; /* char *token; /* struct TreeNode *rightPtr; /* }; /* end struct TreeNode */  */ pointer to left subtree */ node data */ pointer to right subtree */  typedef struct TreeNode TreeNode; typedef TreeNode *TreeNodePtr; /* function prototypes */ void insertNode( TreeNodePtr *treePtr, char *tokenPtr ); void inOrder( TreeNodePtr treePtr ); void preOrder( TreeNodePtr treePtr ); void postOrder( TreeNodePtr treePtr ); int main() { TreeNodePtr rootPtr = NULL; /* points to the tree root */ char sentence[ 80 ]; /* text from user */ char *tokenPtr; /* pointer to current token */ /* prompt user and read a sentence */ printf( "Enter a sentence:\n" ); gets( sentence ); /* tokenize the sentence */ tokenPtr = strtok( sentence, " " ); /* insert the tokens in the tree */ while ( tokenPtr ) { insertNode( &rootPtr, tokenPtr ); tokenPtr = strtok( NULL, " " ); } /* end while */ /* traverse the tree preorder */ printf( "\nThe preorder traversal is:\n" ); preOrder( rootPtr ); /* traverse the tree inorder */ printf( "\n\nThe inorder traversal is:\n" ); inOrder( rootPtr ); /* traverse the tree postorder */ printf( "\n\nThe postorder traversal is:\n" ); postOrder( rootPtr ); return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 409  Chapter 12  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 108 109 110 111 112 113 114 115 116  /* insert a node into the tree */ void insertNode( TreeNodePtr *treePtr, char *tokenPtr ) { /* if treePtr is NULL */ if ( !*treePtr ) { /* dynamically allocate memory */ *treePtr = malloc( sizeof( TreeNode ) ); /* if memory was allocated, insert node */ if ( *treePtr ) { ( *treePtr )->token = tokenPtr; ( *treePtr )->leftPtr = NULL; ( *treePtr )->rightPtr = NULL; } /* end if */ else { printf( "\"%s\" not inserted. No memory available.\n", tokenPtr ); } /* end else */ return; } /* end if */ else { /* recursively call insertNode */ /* insert node in left subtree */ if ( strcmp( tokenPtr, ( *treePtr )->token ) <= 0 ) { insertNode( &( ( *treePtr )->leftPtr ), tokenPtr ); } /* end if */ else { /* insert node in right subtree */ insertNode( &( ( *treePtr )->rightPtr ), tokenPtr ); } /* end else */ } /* end else */ } /* end function insertNode */ /* traverse the tree inorder */ void inOrder( TreeNodePtr treePtr ) { /* traverse left subtree, print node, traverse right subtree */ if ( treePtr ) { inOrder( treePtr->leftPtr ); printf( "%s ", treePtr->token ); inOrder( treePtr->rightPtr ); } /* end if */ } /* end function inOrder */ /* traverse the tree preorder */ void preOrder( TreeNodePtr treePtr ) { /* print node, traverse left subtree, traverse right subtree */ if ( treePtr ) { printf( "%s ", treePtr->token ); preOrder( treePtr->leftPtr ); preOrder( treePtr->rightPtr ); } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  410 Data Structures: Solutions  117 118 119 120 121 122 123 124 125 126 127 128 129 130 131  Chapter 12  } /* end function preOrder */ /* traverse the tree postorder */ void postOrder( TreeNodePtr treePtr ) { /* traverse left subtree, traverse right subtree, print node */ if ( treePtr ) { postOrder( treePtr->leftPtr ); postOrder( treePtr->rightPtr ); printf( "%s ", treePtr->token ); } /* end if */ } /* end function postOrder */  Enter a sentence: this program inserts strings of different lengths in a tree The preorder traversal is: this program inserts different a in of lengths strings tree The inorder traversal is: a different in inserts lengths of program strings this tree The postorder traversal is: a in different lengths of inserts strings program tree this  12.18 In this chapter, we saw that duplicate elimination is straightforward when creating a binary search tree. Describe how you would perform duplicate elimination using only a single subscripted array. Compare the performance of array-based duplicate elimination with the performance of binary-search-tree-based duplicate elimination. ANS: Using a single subscripted array, it is necessary to compare each value to be inserted in the array with all the array elements until a match is found or until it is determined that there is not a duplicate value in the array. If there is not a duplicate, the value can be inserted in the array. On average, half the array elements must be searched when the value is a duplicate and all the array elements must be searched when the value is not a duplicate. The binary search tree only compares the value to be inserted with the values in its path down the tree. If a leaf node is reached, and the value does not match the value in the leaf node, the value can be inserted. Otherwise the value can be discarded. 12.19 Write a function depth that receives a binary tree and determines how many levels it has. 12.20 (Recursively Print a List Backwards) Write a function printListBackwards that recursively outputs the items in a list in reverse order. Use your function in a test program that creates a sorted list of integers and prints the list in reverse order. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  /* Exercise 12.20 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* ListNode structure definition */ struct ListNode { int data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ }; /* end struct ListNode */ typedef struct ListNode ListNode; typedef ListNode *ListNodePtr; /* function prototype */ void printList( ListNodePtr currentPtr ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 411  Chapter 12  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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76  void printListBackwards( ListNodePtr currentPtr ); void insertItem( ListNodePtr *sPtr, int value ); int main() { ListNodePtr startPtr = NULL; /* list pointer */ int item; /* loop counter */ /* insert integers into list */ for ( item = 1; item < 11; item++ ) { insertItem( &startPtr, item ); } /* end for */ printList( startPtr ); printf( "\n" ); printListBackwards( startPtr ); return 0; /* indicate successful termination */ } /* end main */ /* Insert a new value into the list in sorted order */ void insertItem( ListNodePtr *sPtr, int value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else { printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insertItem */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  412 Data Structures: Solutions  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 108 109 110 111 112  /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%d ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "*\n\n" ); } /* end else */ } /* end function printList */ /* Print the list recursively backwards */ void printListBackwards( ListNodePtr currentPtr ) { /* if at end of list */ if ( currentPtr == NULL ) { printf( "The list reversed is:\n" ); } /* end if */ else { /* recursive call */ printListBackwards( currentPtr->nextPtr ); printf( "%d ", currentPtr->data ); } /* end else */ } /* end function printListBackwards */  the list is: 1 2 3 4 5 6 7 8 9 10 The list reversed is: 10 9 8 7 6 5 4 3 2 1  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 413  Chapter 12  12.21 (Recursively Search a List) Write a function searchList that recursively searches a linked list for a specified value. The function should return a pointer to the value if it is found; otherwise, NULL should be returned. Use your function in a test program that creates a list of integers. The program should prompt the user for a value to locate in the list. 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 53 54 55 56  /* Exercise 12.21 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* ListNode structure definition */ struct ListNode { int data; /* node data */ struct ListNode *nextPtr; /* pointer to next node */ }; /* end struct ListNode */ typedef struct ListNode ListNode; typedef ListNode *ListNodePtr; /* function prototypes */ void insertItem( ListNodePtr *sPtr, int value ); void printList( ListNodePtr currentPtr ); void instructions( void ); ListNodePtr searchList( ListNodePtr currentPtr, const int key ); int main() { ListNodePtr startPtr = NULL; ListNodePtr searchResultPtr; int choice; int item; int searchKey;  /* /* /* /* /*  list pointer */ pointer to search result */ user's menu choice */ value to insert into list */ value to search for in list */  instructions(); /* display the menu */ printf( "? " ); scanf( "%d", &choice ); /* while user does not choose 3 */ while ( choice != 3 ) { /* determine user's choice */ switch ( choice ) { /* insert an integer into the list */ case 1: /* prompt user and read integer */ printf( "Enter an integer: " ); scanf( "\n%d", &item ); /* insert integer and print list */ insertItem( &startPtr, item ); printList( startPtr ); break; /* exit switch */ /* search for given integer */ case 2: /* prompt user and read integer */ printf( "Enter integer to recursively search for: " ); scanf( "%d", &searchKey );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  414 Data Structures: Solutions  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 108 109 110 111 112 113 114 115 116 117 118  searchResultPtr = searchList( startPtr, searchKey ); /* if searchKey not found */ if ( searchResultPtr == NULL ) { printf( "%d is not in the list.\n\n", searchKey ); } /* end if */ else { /* if searchKey was found */ printf( "%d is in the list.\n\n", searchResultPtr->data ); } /* end else */ break; /* exit switch */ /* default case */ default: printf( "Invalid choice.\n\n" ); instructions(); break; /* exit switch */ } /* end switch */ printf( "? " ); scanf( "%d", &choice ); /* get next choice */ } /* end while */ printf( "End of run.\n" ); return 0; /* indicate successful termination */ } /* end main */ /* Print the instructions */ void instructions( void ) { printf( "Enter your choice:\n" " 1 to insertItem an element into the list.\n" " 2 to recursively search list for an element.\n" " 3 to end.\n" ); } /* end function instructions */ /* Insert a new value into the list in sorted order */ void insertItem( ListNodePtr *sPtr, int value ) { ListNodePtr newPtr; /* new node */ ListNodePtr previousPtr; /* previous node */ ListNodePtr currentPtr; /* current node */ /* dynamically allocate memory */ newPtr = malloc( sizeof( ListNode ) ); /* if newPtr does not equal NULL */ if ( newPtr ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; /* set currentPtr to start of list */ /* loop to find correct location in list */ while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } /* end while */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 415  Chapter 12  119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173  /* insert at beginning of list */ if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } /* end if */ else { /* insert node between previousPtr and currentPtr */ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } /* end else */ } /* end if */ else { printf( "%c not inserted. No memory available.\n", value ); } /* end else */ } /* end function insertItem */ /* Print the list */ void printList( ListNodePtr currentPtr ) { /* if list is empty */ if ( !currentPtr ) { printf( "List is empty.\n\n" ); } /* end if */ else { /* loop while currentPtr does not equal NULL */ while ( currentPtr ) { printf( "%d --> ", currentPtr->data ); currentPtr = currentPtr->nextPtr; } /* end while */ printf( "NULL\n\n" ); } /* end else */ } /* end function printList */ /* search for key in list */ ListNodePtr searchList( ListNodePtr currentPtr, const int key ) { /* if currentPtr is at end of list */ if ( currentPtr == NULL ) { return NULL; /* key not found */ } /* end if */ else if ( currentPtr->data == key ) { return currentPtr; /* key found */ } /* end else if */ else { searchList( currentPtr->nextPtr, key ); /* keep searching */ } /* end else */ } /* end function ListNodePtr */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  416 Data Structures: Solutions  Chapter 12  Enter your choice: 1 to insertItem an element into the list. 2 to recursively search list for an element 3 to end. ? 1 Enter an integer: 7 The list is: 7 --> NULL ? 1 Enter an integer: 99 The list is: 7 --> 99 --> NULL ? 1 Enter an integer: 56 The list is: 7 --> 56 --> 99 --> NULL ? 1 Enter an integer: 73 The list is: 7 --> 56 --> 73 --> 99 --> NULL ? 2 Enter integer to recursively search for: 7 7 is in the list. ? 2 Enter integer to recursively search for: 55 55 is not in the list. ? 2 Enter integer to recursively search for: 99 99 is in the list. ? 3 End of run.  12.22 (Binary Tree Delete) In this exercise, we discuss deleting items from binary search trees. The deletion algorithm is not as straightforward as the insertion algorithm. There are three cases that are encountered when deleting an item—the item is contained in a leaf node (i.e., it has no children), the item is contained in a node that has one child, or the item is contained in a node that has two children. If the item to be deleted is contained in a leaf node, the node is deleted and the pointer in the parent node is set to NULL. If the item to be deleted is contained in a node with one child, the pointer in the parent node is set to point to the child node and the node containing the data item is deleted. This causes the child node to take the place of the deleted node in the tree. The last case is the most difficult. When a node with two children is deleted, another node must take its place. However, the pointer in the parent node cannot simply be assigned to point to one of the children of the node to be deleted. In most cases, the resulting binary search tree would not adhere to the following characteristic of binary search trees: The values in any left subtree are less than the value in the parent node, and the values in any right subtree are greater than the value in the parent node. Which node is used as a replacement node to maintain this characteristic? Either the node containing the largest value in the tree less than the value in the node being deleted, or the node containing the smallest value in the tree greater than the value in the node being deleted. Let us consider the node with the smaller value. In a binary search tree, the largest value less than a parent's value is located in the left subtree of the parent node and is guaranteed to be contained in the rightmost node of the subtree. This node is located by walking down the left subtree to the right until the pointer to the right child of the current node is NULL. We are now pointing to the replacement node which is either a leaf node or a node with one child to its left. If the replacement node is a leaf node, the steps to perform the deletion are as follows: © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 417  1) Store the pointer to the node to be deleted in a temporary pointer variable (this pointer is used to delete the dynamically allocated memory). 2) Set the pointer in the parent of the node being deleted to point to the replacement node. 3) Set the pointer in the parent of the replacement node to null. 4) Set the pointer to the right subtree in the replacement node to point to the right subtree of the node to be deleted. 5) Delete the node to which the temporary pointer variable points. The deletion steps for a replacement node with a left child are similar to those for a replacement node with no children, but the algorithm also must move the child to the replacement node's position. If the replacement node is a node with a left child, the steps to perform the deletion are as follows: 1) Store the pointer to the node to be deleted in a temporary pointer variable. 2) Set the pointer in the parent of the node being deleted to point to the replacement node. 3) Set the pointer in the parent of the replacement node to point to the left child of the replacement node. 4) Set the pointer to the right subtree in the replacement node to point to the right subtree of the node to be deleted. 5) Delete the node to which the temporary pointer variable points. Write function deleteNode which takes as its arguments a pointer to the root node of the tree and the value to be deleted. The function should locate in the tree the node containing the value to be deleted and use the algorithms discussed here to delete the node. If the value is not found in the tree, the function should print a message that indicates whether or not the value is deleted. Modify the program of Fig. 12.19 to use this function. After deleting an item, call the inOrder, preOrder and postOrder traversal functions to confirm that the delete operation was performed correctly.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  418 Data Structures: Solutions  Chapter 12  12.23 (Binary Tree Search) Write function binaryTreeSearch that attempts to locate a specified value in a binary search tree. The function should take as arguments a pointer to the root node of the binary tree and a search key to be located. If the node containing the search key is found, the function should return a pointer to that node; otherwise, the function should return a NULL pointer. 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 53 54 55  /* Exercise 12.23 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* TreeNode structure definition struct TreeNode { struct TreeNode *leftPtr; /* int data; /* struct TreeNode *rightPtr; /* }; /* end struct TreeNode */  */ pointer to left subtree */ node data */ pointer to right subtree */  typedef struct TreeNode TreeNode; typedef TreeNode *TreeNodePtr; /* function prototypes */ void insertNode( TreeNodePtr *treePtr, int value ); TreeNodePtr binaryTreeSearch( TreeNodePtr treePtr, const int key ); int main() { int i; int item; int searchKey; TreeNodePtr rootPtr = NULL; TreeNodePtr searchResultPtr;  /* /* /* /* /*  loop counter */ random value to insert in tree */ value to search for */ points to the tree root */ pointer to search result */  srand( time( NULL ) ); /* randomize */ printf( "The numbers being placed in the tree are:\n" ); /* insert random values between 1 and 20 in the tree */ for ( i = 1; i <= 10; i++ ) { item = 1 + rand() % 20; printf( "%3d", item ); insertNode( &rootPtr, item ); } /* end for */ /* prompt user and read integer search key */ printf( "\n\nEnter an integer to search for: " ); scanf( "%d", &searchKey ); searchResultPtr = binaryTreeSearch( rootPtr, searchKey ); /* if searchKey not found */ if ( searchResultPtr == NULL ) { printf( "\n%d was not found in the tree.\n\n", searchKey ); } /* end if */ else { /* if key found */ printf( "\n%d was found in the tree.\n\n", searchResultPtr->data ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 419  Chapter 12  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 108 109 110 111 112 113 114 115 116  /* insert a node into the tree */ void insertNode( TreeNodePtr *treePtr, int value ) { /* if treePtr is NULL */ if ( *treePtr == NULL ) { /* dynamically allocate memory */ *treePtr = malloc( sizeof( TreeNode ) ); /* if memory was allocated, insert node */ if ( *treePtr != NULL ) { ( *treePtr )->data = value; ( *treePtr )->leftPtr = NULL; ( *treePtr )->rightPtr = NULL; } /* end if */ else { printf( "%d not inserted. No memory available.\n", value ); } /* end else */ } /* end if */ else { /* recursively call insertNode */ /* insert node in left subtree */ if ( value < ( *treePtr )->data ) { insertNode( &( ( *treePtr )->leftPtr ), value ); } /* end if */ else { /* insert node in right subtree */ if ( value > ( *treePtr )->data ) { insertNode( &( ( *treePtr )->rightPtr ), value ); } /* end if */ else { /* duplicate value */ printf( "dup" ); } /* end else */ } /* end else */ } /* end else */ } /* end function insertNode */ /* search for key in tree */ TreeNodePtr binaryTreeSearch( TreeNodePtr treePtr, const int key ) { /* traverse the tree inOrder */ if ( treePtr == NULL ) { return NULL; /* key not found */ } /* end if */ else if ( treePtr->data == key ) { return treePtr; /* key found */ } /* end else if */ else if ( key < treePtr->data ) { binaryTreeSearch( treePtr->leftPtr, key ); /* search left */ } /* end else if */ else if ( key > treePtr->data ) { binaryTreeSearch( treePtr->rightPtr, key ); /* search right */ } /* end else if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  420 Data Structures: Solutions  Chapter 12  117 118 } /* end function binaryTreeSearch */ The numbers being placed in the tree are: 18 9 7 2 13 2dup 10 1 19 2dup Enter an integer to search for: 8 8 was not found in the tree.  12.24 (Level Order Binary Tree Traversal) The program of Fig. 12.19 illustrated three recursive methods of traversing a binary tree—inorder traversal, preorder traversal, and postorder traversal. This exercise presents the level order traversal of a binary tree in which the node values are printed level-by-level starting at the root node level. The nodes on each level are printed from left to right. The level order traversal is not a recursive algorithm. It uses the queue data structure to control the output of the nodes. The algorithm is as follows: 1) Insert the root node in the queue 2) While there are nodes left in the queue, Get the next node in the queue Print the node's value If the pointer to the left child of the node is not null Insert the left child node in the queue If the pointer to the right child of the node is not null Insert the right child node in the queue. Write function levelOrder to perform a level order traversal of a binary tree. The function should take as an argument a pointer to the root node of the binary tree. Modify the program of Fig. 12.19 to use this function. Compare the output from this function to the outputs of the other traversal algorithms to see that it worked correctly. [Note: You will also need to modify and incorporate the queue processing functions of Fig. 12.13 in this program.] 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  /* Exercise 12.24 solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* TreeNode structure definition struct TreeNode { struct TreeNode *leftPtr; /* int data; /* struct TreeNode *rightPtr; /* }; /* end struct TreeNode */  */ pointer to left subtree */ node data */ pointer to right subtree */  typedef struct TreeNode TreeNode; typedef TreeNode *TreeNodePtr; /* tree function prototypes */ void insertNode( TreeNodePtr *treePtr, int value ); void levelOrderTraversal( TreeNodePtr treePtr ); /* QueueNode structure definition */ struct QueueNode { TreeNodePtr data; /* node data */ struct QueueNode *nextPtr; /* pointer to next node */ }; /* end struct QueueNode */ typedef struct QueueNode QueueNode; typedef QueueNode *QueueNodePtr;  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 421  Chapter 12  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 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  /* queue function prototypes */ int isEmpty( QueueNodePtr headPtr ); TreeNodePtr dequeue( QueueNodePtr *headPtr, QueueNodePtr * tailPtr ); void enqueue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr, TreeNodePtr node ); int main() { int i; /* loop counter */ int item; /* random value to insert in tree */ TreeNodePtr rootPtr = NULL; /* points to the tree root */ srand( time( NULL ) ); /* randomize */ printf( "The values being inserted in the tree are:\n" ); /* insert random values between 1 and 15 in the tree */ for ( i = 1; i <= 15; i++ ) { item = 1 + rand() % 20; printf( " %d", item ); insertNode( &rootPtr, item ); } /* end for */ /* traverse the tree level order */ printf( "\n\nThe level order traversal is:\n" ); levelOrderTraversal( rootPtr ); printf( "\n" ); return 0; /* indicate successful termination */ } /* end main */ /* Level order traversal of a binary tree */ void levelOrderTraversal( TreeNodePtr ptr ) { QueueNodePtr head = NULL; /* points to queue head */ QueueNodePtr tail = NULL; /* points to queue tail */ TreeNodePtr node; /* current tree node */ /* if tree is not empty */ if ( ptr != NULL ) { enqueue( &head, &tail, ptr ); /* enqueue root nood */ /* while queue is not empty */ while ( !isEmpty( head ) ) { /* dequeue next node and print data */ node = dequeue( &head, &tail ); printf( "%d ", node->data ); /* insert left child node in the queue */ if ( node->leftPtr != NULL ) { enqueue( &head, &tail, node->leftPtr ); } /* end if */ /* insert right child node in the queue */ if ( node->rightPtr != NULL ) { enqueue( &head, &tail, node->rightPtr ); } /* end if */ } /* end while */ } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  422 Data Structures: Solutions  91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151  } /* end function levelOrderTraversal */ /* insert a node into the tree */ void insertNode( TreeNodePtr *treePtr, int value ) { /* if treePtr is NULL */ if ( *treePtr == NULL ) { /* dynamically allocate memory */ *treePtr = malloc( sizeof( TreeNode ) ); /* if memory was allocated, insert node */ if ( *treePtr != NULL ) { ( *treePtr )->data = value; ( *treePtr )->leftPtr = NULL; ( *treePtr )->rightPtr = NULL; } /* end if */ else { printf( "%d not inserted. No memory available.\n", value ); } /* end else */ } /* end if */ else { /* recursively call insertNode */ /* insert node in left subtree */ if ( value < ( *treePtr )->data ) { insertNode( &( ( *treePtr )->leftPtr ), value ); } /* end if */ else { /* insert node in right subtree */ if ( value > ( *treePtr )->data ) { insertNode( &( ( *treePtr )->rightPtr ), value ); } /* end if */ else { /* duplicate value */ printf( "dup" ); } /* end else */ } /* end else */ } /* end else */ } /* end function insertNode */ /* enqueue node */ void enqueue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr, TreeNodePtr node ) { QueueNodePtr newPtr; /* temporary node pointer */ /* dynamically allocate memory */ newPtr = malloc( sizeof( QueueNode ) ); /* if newPtr does not equal NULL */ if ( newPtr != NULL ) { newPtr->data = node; newPtr->nextPtr = NULL; /* if queue is empty, insert at head */ if ( isEmpty( *headPtr ) ) {  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 12  Data Structures: Solutions 423  Chapter 12  152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193  *headPtr = newPtr; } /* end if */ else { /* insert at tail */ ( *tailPtr )->nextPtr = newPtr; } /* end else */ *tailPtr = newPtr; } /* end if */ else { printf( "Node not inserted\n" ); } /* end else */ } /* end function enqueue */ /* dequeue node from queue */ TreeNodePtr dequeue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr ) { TreeNodePtr node; /* dequeued node */ QueueNodePtr tempPtr; /* temporary node pointer */ /* dequeue node and reset queue headPtr */ node = ( *headPtr )->data; tempPtr = *headPtr; *headPtr = ( *headPtr )->nextPtr; /* if queue is empty */ if ( *headPtr == NULL ) { *tailPtr = NULL; } /* end if */ free( tempPtr ); /* free memory */ return node; /* return dequeued node */ } /* end function dequeue */ /* is queue empty? */ int isEmpty( QueueNodePtr headPtr ) { return headPtr == NULL; /* return NULL is queue is empty */ } /* end function isEmpty */  The values being inserted in the tree are: 5 10 7 5dup 11 9 15 1 7dup 20 6 20dup 4 16 4dup The level order traversal is: 5 1 10 4 7 11 6 9 15 20 16  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  424 Data Structures: Solutions  Chapter 12  12.25 (Printing Trees) Write a recursive function outputTree to display a binary tree on the screen. The function should output the tree row-by-row with the top of the tree at the left of the screen and the bottom of the tree toward the right of the screen. Each row is output vertically. For example, the binary tree illustrated in Fig. 12.22 is output as follows:  99 97 92 83 72 71 69 49 44 40 32 28 19 18 11  Note the rightmost leaf node appears at the top of the output in the rightmost column, and the root node appears at the left of the output. Each column of output starts five spaces to the right of the previous column. Function outputTree should receive as arguments a pointer to the root node of the tree and an integer totalSpaces representing the number of spaces preceding the value to be output (this variable should start at zero so the root node is output at the left of the screen). The function uses a modified inorder traversal to output the tree—it starts at the rightmost node in the tree and works back to the left. The algorithm is as follows: While the pointer to the current node is not null Recursively call outputTree with the right subtree of the current node and totalSpaces + 5  Use a for statement to count from 1 to totalSpaces and output spaces Output the value in the current node Set the pointer to the current node to point to the left subtree of the current node Increment totalSpaces by 5. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  /* Exercise 12.25 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* TreeNode structure definition struct TreeNode { struct TreeNode *leftPtr; /* int data; /* struct TreeNode *rightPtr; /* }; /* end struct TreeNode */  */ pointer to left subtree */ node data */ pointer to right subtree */  typedef struct TreeNode TreeNode; typedef TreeNode *TreeNodePtr; /* function prototypes */ void insertNode( TreeNodePtr *treePtr, int value ); void outputTree( TreeNodePtr treePtr, int spaces ); int main() { int i;  /* loop counter */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 425  Chapter 12  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 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  int item; /* random value to be inserted */ int totalSpaces = 0; /* spaces preceeding output */ TreeNodePtr rootPtr = NULL; /* points to the tree root */ srand( time( NULL ) ); /* randomize */ printf( "The numbers being placed in the tree are:\n" ); /* insert random values between 1 and 10 in the tree */ for ( i = 1; i <= 10; i++ ) { item = rand() % 15; printf( "%3d", item ); insertNode( &rootPtr, item ); } /* end for */ printf( "\n\n" ); outputTree( rootPtr, totalSpaces ); /* display tree */ return 0; /* indicate successful termination */ } /* end main */ /* insert a node into the tree */ void insertNode( TreeNodePtr *treePtr, int value ) { /* if treePtr is NULL */ if ( *treePtr == NULL ) { /* dynamically allocate memory */ *treePtr = malloc( sizeof( TreeNode ) ); /* if memory was allocated, insert node */ if ( *treePtr != NULL ) { ( *treePtr )->data = value; ( *treePtr )->leftPtr = NULL; ( *treePtr )->rightPtr = NULL; } /* end if */ else { printf( "%d not inserted. No memory available.\n", value ); } /* end else */ } /* end if */ else { /* recursively call insertNode */ /* insert node in left subtree */ if ( value < ( *treePtr )->data ) { insertNode( &( ( *treePtr )->leftPtr ), value ); } /* end if */ else { /* insert node in right subtree */ if ( value > ( *treePtr )->data ) { insertNode( &( ( *treePtr )->rightPtr ), value ); } /* end if */ else { /* duplicate value */ printf( "dup" ); } /* end else */ } /* end else */ } /* end else */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  426 Data Structures: Solutions  84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110  Chapter 12  } /* end function insertNode */ /* display the tree */ void outputTree( TreeNodePtr treePtr, int spaces ) { int loop; /* loop counter */ /* while not the end of tree */ while ( treePtr != NULL ) { /* recursive call with right subtree */ outputTree( treePtr->rightPtr, spaces + 5 ); /* loop and output spaces */ for ( loop = 1; loop <= spaces; loop++ ) { printf( " " ); } /* end for */ printf( "%d\n", treePtr->data ); /* set pointer to left subtree and make recursive call */ outputTree( treePtr->leftPtr, spaces + 5 ); treePtr = NULL; } /* end while */ } /* end function outputTree */  The numbers being placed in the tree are: 1 5 6 14 11 2 9 9dup 14dup 8 14 11 9 8 6 5 2 1  SPECIAL SECTION: BUILDING YOUR OWN COMPILER In Exercise 7.18 and Exercise 7.19, we introduced Simpletron Machine Language (SML) and created the Simpletron computer simulator to execute programs written in SML. In this section, we build a compiler that converts programs written in a high-level programming language to SML. This section "ties" together the entire programming process. We will write programs in this new high-level language, compile the programs on the compiler we build, and run the programs on the simulator we built in Exercise 7.19. 12.26 (The Simple Language) Before we begin building the compiler, we discuss a simple, yet powerful, high-level language similar to early versions of the popular language BASIC. We call the language Simple. Every Simple statement consists of a line number and a Simple instruction. Line numbers must appear in ascending order. Each instruction begins with one of the following Simple commands: rem, input, let, print, goto, if…goto or end (see Fig. 12.23). All commands except end can be used repeatedly. Simple evaluates only integer expressions using the +, -, * and / operators. These operators have the same precedence as in C. Parentheses can be used to change the order of evaluation of an expression.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 427  Chapter 12  Command  Example statement  Description  rem  50 rem this is a remark  Any text following the command rem is for documentation purposes only and is ignored by the compiler.  input  30 input x  Display a question mark to prompt the user to enter an integer. Read that integer from the keyboard and store the integer in x.  let  80 let u = 4 * (j - 56))  Assign u the value of 4 * (j - 56). Note that an arbitrarily complex expression can appear to the right of the equal sign.  print  10 print w  Display the value of w.  goto  70 goto 45  Transfer program control to line 45.  if…goto  35 if i == z goto 80  Compare i and z for equality and transfer program control to line 80 if the condition is true; otherwise, continue execution with the next statement.  end  99 end  Terminate program execution.  Fig. 12.1  Simple commands.  Our Simple compiler recognizes only lowercase letters. All characters in a Simple file should be lowercase (uppercase letters result in a syntax error unless they appear in a rem statement in which case they are ignored). A variable name is a single letter. Simple does not allow descriptive variable names, so variables should be explained in remarks to indicate their use in the program. Simple uses only integer variables. Simple does not have variable declarations—merely mentioning a variable name in a program causes the variable to be declared and initialized to zero automatically. The syntax of Simple does not allow string manipulation (reading a string, writing a string, comparing strings, etc.). If a string is encountered in a Simple program (after a command other than rem), the compiler generates a syntax error. Our compiler will assume that Simple programs are entered correctly. Exercise 12.29 asks the student to modify the compiler to perform syntax error checking. Simple uses the conditional if…goto statement and the unconditional goto statement to alter the flow of control during program execution. If the condition in the if…goto statement is true, control is transferred to a specific line of the program. The following relational and equality operators are valid in an if…goto statement: <, >, <=, >=, == or !=. The precedence of these operators is the same as in C. Let us now consider several Simple programs that demonstrate Simple's features. The first program (Fig. 12.24) reads two integers from the keyboard, stores the values in variables a and b, and computes and prints their sum (stored in variable c).  1 2 3 4 5 6 7 8 9 10 11 12 13  10 15 20 30 40 45 50 60 65 70 80 90 99  rem rem rem input input rem rem let c rem rem print rem end  determine and print the sum of two integers input the two integers a b add integers and store result in c = a + b print the result c terminate program execution  Figure 12.25 determines and prints the larger of two integers. The integers are input from the keyboard and stored in s and t. The if…goto statement tests the condition s >= t. If the condition is true, control is transferred to line 90 and s is output; otherwise, t is output and control is transferred to the end statement in line 99 where the program terminates.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  428 Data Structures: Solutions  1 2 3 4 5 6 7 8 9 10 11 12 13 14  10 20 30 32 35 40 45 50 60 70 75 80 90 99  Chapter 12  rem determine the larger of two integers input s input t rem rem test if s >= t if s >= t goto 90 rem rem t is greater than s, so print t print t goto 99 rem rem s is greater than or equal to t, so print s print s end  Simple does not provide a repetition structure (such as C's for, while or do…while). However, Simple can simulate each of C's repetition structures using the if…goto and goto statements. Figure 12.26 uses a sentinel-controlled loop to calculate the squares of several integers. Each integer is input from the keyboard and stored in variable j. If the value entered is the sentinel 9999, control is transferred to line 99 where the program terminates. Otherwise, k is assigned the square of j, k is output to the screen and control is passed to line 20 where the next integer is input.  1 2 3 4 5 6 7 8 9 10 11 12 13  10 20 23 25 30 33 35 40 50 53 55 60 99  rem calculate the squares of several integers input j rem rem test for sentinel value if j == -9999 goto 99 rem rem calculate square of j and assign result to k let k = j * j print k rem rem loop to get next j goto 20 end  Using the sample programs of Fig. 12.24, Fig. 12.25 and Fig. 12.26 as your guide, write a Simple program to accomplish each of the following: a) Input three integers, determine their average and print the result. ANS: 1 2 3 4 5 6 7 8 9 10  5 rem 6 rem 10 input 15 input 10 input 21 rem 25 let a 26 rem 30 print 99 end  Exercise 12.26 Part A Solution x y x calculate average a = ( x + y + z ) / 3 a  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 429  Chapter 12  b) Use a sentinel-controlled loop to input 10 integers and compute and print their sum. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  5 rem Exercise 12.26 Part B Solution 6 rem 10 input n 12 rem set up sentinel loop 15 if n == 9999 goto 40 16 rem 17 rem add n to the sum of s 20 let s = s + n 21 rem 22 rem loop to get next n 25 goto 10 36 rem print sum s 40 print s 99 end  c) Use a counter-controlled loop to input seven integers, some positive and some negative, and compute and print their average. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  5 rem exercise 12.26 Part C Solution 6 rem 10 input m 11 rem increment counter by 1 12 rem c is automatically initiated to 0 13 rem when created 15 let c = c + 1 16 rem 17 rem calculate sum s 20 let s = s + m 22 rem loop to get next m 23 rem if c is not yet 7 25 if c <= 7 goto 10 26 rem 27 rem compute average a 30 let a = s / 7 31 rem 35 print a 99 end  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  430 Data Structures: Solutions  Chapter 12  d) Input a series of integers and determine and print the largest. The first integer input indicates how many numbers should be processed. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  5 rem Exercise 12.26 Part D Solution 6 rem 7 rem Enter the number of integers 8 rem to be processed 10 input n 23 rem begin entering numbers t 25 input t 26 rem check if t is larger than 1 27 rem l's initial value is zero 30 rem if t <= 1 goto 50 31 rem t must be larger than 1 32 rem so assign t as largest 35 let l = t 49 rem decrement n 50 let n = n - 1 59 rem test for loop exit condition 60 if n == 0 goto 80 69 rem loop to get next t 70 goto 25 79 rem print largest value 80 print l 99 end  e) Input 10 integers and print the smallest. 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  1 rem Exercise 12.26 Part E Solution 2 rem 3 rem set counter c equal to 1 5 let c = 1 6 rem input integer m 7 rem assign first entry to 8 rem the smallest value s 9 input m 10 let s = m 11 rem enter main loop 13 goto 20 14 rem main loop 15 input m 18 rem determine if m is smaller 19 rem than current s 20 if m < s goto 50 29 rem increment counter 30 let c = c + 1 34 rem exit when c becomes 11 35 if c == 11 goto 60 39 rem loop for next m 40 goto 15 48 rem assign m to s as 49 rem smallest value 50 let s = m 51 rem loop to counter increment 55 goto 30 59 rem print smallest value 60 print s 99 end  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 431  Chapter 12  f) Calculate and print 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  5 rem Exercise 12.26 Part F Solution 6 rem 7 rem 9 rem initialize i to 2 10 let i = 2 14 rem store sum in s 15 let s = s + 1 19 rem increment i by 2 20 let i = i + 2 28 rem set loop terminating 29 rem condition at 32 30 if < 32 goto 15 39 rem print sum 40 print s 99 end  g) Calculate and print the product of the odd integers from 1 to 9. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  5 rem Exercise 12.26 Part G Solution 6 rem 7 rem 9 rem initialize k to 1 10 let k = 1 11 rem initialize p to 1 13 let p = 1 14 rem store product in p 15 let p = p * k 19 rem increment k by 1 20 let k = k + 2 28 rem set loop terminating 29 rem condition at 10 30 if k < 10 goto 15 39 rem print product 40 print p 99 end  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  432 Data Structures: Solutions  Chapter 12  12.27 (Building A Compiler; Prerequisite: Complete Exercise 7.18, Exercise 7.19, Exercise 12.12, Exercise 12.13 and Exercise 12.26) Now that the Simple language has been presented (Exercise 12.26), we discuss how to build our Simple compiler. First, we consider the process by which a Simple program is converted to SML and executed by the Simpletron simulator (see Fig. 12.27). A file containing a Simple program is read by the compiler and converted to SML code. The SML code is output to a file on disk, in which SML instructions appear one per line. The SML file is then loaded into the Simpletron simulator, and the results are sent to a file on disk and to the screen. Note that the Simpletron program developed in Exercise 7.19 took its input from the keyboard. It must be modified to read from a file so it can run the programs produced by our compiler.  Simple file  compiler  SML file  Simpletron Simulator  output to disk  Fig. 12.2  output to screen  Writing, compiling and executing a Simple language program.  The compiler performs two passes of the Simple program to convert it to SML. The first pass constructs a symbol table in which every line number, variable name and constant of the Simple program is stored with its type and corresponding location in the final SML code (the symbol table is discussed in detail below). The first pass also produces the corresponding SML instruction(s) for each Simple statement. As we will see, if the Simple program contains statements that transfer control to a line later in the program, the first pass results in an SML program containing some incomplete instructions. The second pass of the compiler locates and completes the unfinished instructions, and outputs the SML program to a file.  First Pass The compiler begins by reading one statement of the Simple program into memory. The line must be separated into its individual tokens (i.e., "pieces" of a statement) for processing and compilation (standard library function strtok can be used to facilitate this task). Recall that every statement begins with a line number followed by a command. As the compiler breaks a statement into tokens, if the token is a line number, a variable, or a constant, it is placed in the symbol table. A line number is placed in the symbol table only if it is the first token in a statement. The symbolTable is an array of tableEntry structures representing each symbol in the program. There is no restriction on the number of symbols that can appear in the program. Therefore, the symbolTable for a particular program could be large. Make the symbolTable a 100-element array for now. You can increase or decrease its size once the program is working. The tableEntry structure definition is as follows: struct tableEntry { int symbol; char type; /* 'C', 'L' or 'V' */ int location; /* 00 to 99 */ };  Each tableEntry structure contains three members. Member symbol is an integer containing the ASCII representation of a variable (remember that variable names are single characters), a line number, or a constant. Member type is one of the following characters indicating the symbol's type: 'C' for constant, 'L' for line number, or 'V' for variable. Member location contains the Simpletron memory location (00 to 99) to which the symbol refers. Simpletron memory is an array of 100 integers in which SML instructions and data are stored. For a line number, the location is the element in the Simpletron memory array at which the SML instructions for the Simple statement begin. For a variable or constant, the location is the element in the Simpletron memory array in which the variable or constant is stored. Variables and constants are allocated from the end of Simpletron's memory backwards. The first variable or constant is stored in location at 99, the next in location at 98, etc. The symbol table plays an integral part in converting Simple programs to SML. We learned in Chapter 7 that an SML instruction is a four-digit integer that comprises two parts—the operation code and the operand. The operation code is determined by commands in Simple. For example, the simple command input corresponds to SML operation code 10 (read), and the Simple command print corresponds to SML operation code 11 (write). The operand is a memory location containing the data on which the operation code performs its task (e.g., operation code 10 reads a value from the keyboard and stores it in the memory location specified by the operand). The compiler searches symbolTable to determine the Simpletron memory location for each symbol so © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 433  Chapter 12  the corresponding location can be used to complete the SML instructions. The compilation of each Simple statement is based on its command. For example, after the line number in a rem statement is inserted in the symbol table, the remainder of the statement is ignored by the compiler, because a remark is for documentation purposes only. The input, print, goto and end statements correspond to the SML read, write, branch (to a specific location) and halt instructions. Statements containing these Simple commands are converted directly to SML [Note: That a goto statement may contain an unresolved reference if the specified line number refers to a statement further into the Simple program file; this is sometimes called a forward reference.] When a goto statement is compiled with an unresolved reference, the SML instruction must be flagged to indicate that the second pass of the compiler must complete the instruction. The flags are stored in 100-element array flags of type int in which each element is initialized to -1. If the memory location to which a line number in the Simple program refers is not yet known (i.e., it is not in the symbol table), the line number is stored in array flags in the element with the same subscript as the incomplete instruction. The operand of the incomplete instruction is set to 00 temporarily. For example, an unconditional branch instruction (making a forward reference) is left as +4000 until the second pass of the compiler. The second pass of the compiler will be described shortly. Compilation of if…goto and let statements is more complicated than other statements—they are the only statements that produce more than one SML instruction. For an if…goto statement, the compiler produces code to test the condition and to branch to another line if necessary. The result of the branch could be an unresolved reference. Each of the relational and equality operators can be simulated using SML's branch zero and branch negative instructions (or possibly a combination of both). For a let statement, the compiler produces code to evaluate an arbitrarily complex arithmetic expression consisting of integer variables and/or constants. Expressions should separate each operand and operator with spaces. Exercise 12.12 and Exercise 12.13 presented the infix-to-postfix conversion algorithm and the postfix evaluation algorithm used by compilers to evaluate expressions. Before proceeding with your compiler, you should complete each of these exercises. When a compiler encounters an expression, it converts the expression from infix notation to postfix notation, then evaluates the postfix expression. How is it that the compiler produces the machine language to evaluate an expression containing variables? The postfix evaluation algorithm contains a "hook" that allows our compiler to generate SML instructions rather than actually evaluating the expression. To enable this "hook" in the compiler, the postfix evaluation algorithm must be modified to search the symbol table for each symbol it encounters (and possibly insert it), determine the symbol's corresponding memory location, and push the memory location on the stack instead of the symbol. When an operator is encountered in the postfix expression, the two memory locations at the top of the stack are popped and machine language for effecting the operation is produced using the memory locations as operands. The result of each subexpression is stored in a temporary location in memory and pushed back onto the stack so the evaluation of the postfix expression can continue. When postfix evaluation is complete, the memory location containing the result is the only location left on the stack. This is popped and SML instructions are generated to assign the result to the variable at the left of the let statement.  Second Pass The second pass of the compiler performs two tasks: resolve any unresolved references and output the SML code to a file. Resolution of references occurs as follows: 1) Search the flags array for an unresolved reference (i.e., an element with a value other than -1). 2) Locate the structure in array symbolTable containing the symbol stored in the flags array (be sure that the type of the symbol is 'L' for line number). 3) Insert the memory location from structure member location into the instruction with the unresolved reference (remember that an instruction containing an unresolved reference has operand 00). 4) Repeat steps 1, 2 and 3 until the end of the flags array is reached. After the resolution process is complete, the entire array containing the SML code is output to a disk file with one SML instruction per line. This file can be read by the Simpletron for execution (after the simulator is modified to read its input from a file).  A Complete Example The following example illustrates a complete conversion of a Simple program to SML as it will be performed by the Simple compiler. Consider a Simple program that inputs an integer and sums the values from 1 to that integer. The program and the SML instructions produced by the first pass are illustrated in Fig. 12.3. The symbol table constructed by the first pass is shown in Fig. 12.29 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  434 Data Structures: Solutions  Chapter 12  SML location and instruction  Simple program 5 rem  sum 1 to x  none  10 input x 15 rem  00  check y == x  none  20 if y == x goto 60  25 rem  45 rem  55 rem  rem ignored  load y (98) into accumulator  02  +3199  sub x (99) from accumulator  03  +4200  branch zero to unresolved location rem ignored  04  +2098  load y into accumulator  05  +3097  add 1 (97) to accumulator  06  +2196  store in temporary location 96  07  +2096  load from temporary location 96  08  +2198  store accumulator in y  add y to total  none  rem ignored  09  +2095  load t (95) into accumulator  10  +3098  add y to accumulator  11  +2194  store in temporary location 94  12  +2094  load from temporary location 94  13  +2195  store accumulator in t  14  +4001  loop y  none  50 goto 20  read x into location 99  +2098  none  40 let t = t + y  rem ignored  01  increment y  30 let y = y + 1  35 rem  +1099  Description  output result  none  rem ignored  branch to location 01 rem ignored  60 print t  15  +1195  output t to screen  99 end  16  +4300  terminate execution  Fig. 12.3  Symbol  SML instructions produced after the compiler's first pass.  Type  Location  5  L  00  10  L  00  'x'  V  99  15  L  01  20  L  01  'y'  V  98  25  L  04  30  L  04  1  C  97  35  L  09  40  L  09  Fig. 12.4  Symbol table for program of Fig. 12.3 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 435  Chapter 12  Symbol  Type  Location  't'  V  95  45  L  14  50  L  14  55  L  15  60  L  15  99  L  16  Fig. 12.4  Symbol table for program of Fig. 12.3  Most Simple statements convert directly to single SML instructions. The exceptions in this program are remarks, the if…goto statement in line 20, and the let statements. Remarks do not translate into machine language. However, the line number for a remark is placed in the symbol table in case the line number is referenced in a goto statement or an if…goto statement. Line 20 of the program specifies that if the condition y == x is true, program control is transferred to line 60. Because line 60 appears later in the program, the first pass of the compiler has not as yet placed 60 in the symbol table (line numbers are placed in  the symbol table only when they appear as the first token in a statement). Therefore, it is not possible at this time to determine the operand of the SML branch zero instruction at location 03 in the array of SML instructions. The compiler places 60 in location 03 of the flags array to indicate that the second pass completes this instruction. We must keep track of the next instruction location in the SML array because there is not a one-to-one correspondence between Simple statements and SML instructions. For example, the if…goto statement of line 20 compiles into three SML instructions. Each time an instruction is produced, we must increment the instruction counter to the next location in the SML array. Note that the size of Simpletron's memory could present a problem for Simple programs with many statements, variables and constants. It is conceivable that the compiler will run out of memory. To test for this case, your program should contain a data counter to keep track of the location at which the next variable or constant will be stored in the SML array. If the value of the instruction counter is larger than the value of the data counter, the SML array is full. In this case, the compilation process should terminate and the compiler should print an error message indicating that it ran out of memory during compilation.  Step-by-Step View of the Compilation Process Let us now walk through the compilation process for the Simple program in Fig. 12.3. The compiler reads the first line of the program 5 rem sum 1 to x  into memory. The first token in the statement (the line number) is determined using strtok (see Chapter 8 for a discussion of C's string manipulation functions). The token returned by strtok is converted to an integer using atoi, so the symbol 5 can be located in the symbol table. If the symbol is not found, it is inserted in the symbol table. Since we are at the beginning of the program and this is the first line, no symbols are in the table yet. So, 5 is inserted into the symbol table as type L (line number) and assigned the first location in SML array (00). Although this line is a remark, a space in the symbol table is allocated for the line number (in case it is referenced by a goto or an if…goto). No SML instruction is generated for a rem statement, so the instruction counter is not incremented. The statement 10 input x  is tokenized next. The line number 10 is placed in the symbol table as type L and assigned the first location in the SML array (00 because a remark began the program, so the instruction counter is currently 00). The command input indicates that the next token is a variable (only a variable can appear in an input statement). Because input corresponds directly to an SML operation code, the compiler simply has to determine the location of x in the SML array. Symbol x is not found in the symbol table. So, it is inserted into the symbol table as the ASCII representation of x, given type V, and assigned location 99 in the SML array (data storage begins at 99 and is allocated backwards). SML code can now be generated for this statement. Operation code 10 (the SML read operation code) is multiplied by 100, and the location of x (as determined in the symbol table) is added to complete the instruction. The instruction is then stored in the SML array at location 00. The instruction counter is incremented by 1 because a single SML instruction was produced. The statement © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  436 Data Structures: Solutions  15 rem  Chapter 12  check y == x  is tokenized next. The symbol table is searched for line number 15 (which is not found). The line number is inserted as type L and assigned the next location in the array, 01 (remember that rem statements do not produce code, so the instruction counter is not incremented). The statement 20 if y == x goto 60  is tokenized next. Line number 20 is inserted in the symbol table and given type L with the next location in the SML array 01. The command if indicates that a condition is to be evaluated. The variable y is not found in the symbol table, so it is inserted and given the type V and the SML location 98. Next, SML instructions are generated to evaluate the condition. Since there is no direct equivalent in SML for the if…goto, it must be simulated by performing a calculation using x and y and branching based on the result. If y is equal to x, the result of subtracting x from y is zero, so the branch zero instruction can be used with the result of the calculation to simulate the if…goto statement. The first step requires that y be loaded (from SML location 98) into the accumulator. This produces the instruction 01 +2098. Next, x is subtracted from the accumulator. This produces the instruction 02 +3199. The value in the accumulator may be zero, positive or negative. Since the operator is ==, we want to branch zero. First, the symbol table is searched for the branch location (60 in this case), which is not found. So, 60 is placed in the flags array at location 03, and the instruction 03 +4200 is generated (we cannot add the branch location because we have not assigned a location to line 60 in the SML array yet). The instruction counter is incremented to 04. The compiler proceeds to the statement 25 rem  increment y  The line number 25 is inserted in the symbol table as type L and assigned SML location 04. The instruction counter is not incremented. When the statement 30 let y = y + 1  is tokenized, the line number 30 is inserted in the symbol table as type L and assigned SML location 04. Command let indicates that the line is an assignment statement. First, all the symbols on the line are inserted in the symbol table (if they are not already there). The integer 1 is added to the symbol table as type C and assigned SML location 97. Next, the right side of the assignment is converted from infix to postfix notation. Then the postfix expression (y 1 +) is evaluated. Symbol y is located in the symbol table and its corresponding memory location is pushed onto the stack. Symbol 1 is also located in the symbol table, and its corresponding memory location is pushed onto the stack. When the operator + is encountered, the postfix evaluator pops the stack into the right operand of the operator and pops the stack again into the left operand of the operator, then produces the SML instructions 04 +2098 05 +3097  (load y) (add 1)  The result of the expression is stored in a temporary location in memory (96) with instruction 06 +2196  (store temporary)  and the temporary location is pushed on the stack. Now that the expression has been evaluated, the result must be stored in y (i.e., the variable on the left side of =). So, the temporary location is loaded into the accumulator and the accumulator is stored in y with the instructions 07 +2096 08 +2198  (load temporary) (store y)  The reader will immediately notice that SML instructions appear to be redundant. We will discuss this issue shortly. When the statement 35 rem  add y to total  is tokenized, line number 35 is inserted in the symbol table as type L and assigned location 09. The statement 40 let t = t + y © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 437  Chapter 12  is similar to line 30. The variable t is inserted in the symbol table as type V and assigned SML location 95. The instructions follow the same logic and format as line 30, and the instructions 09 +2095, 10 +3098, 11 +2194, 12 +2094, and 13 +2195 are generated. Note that the result of t + y is assigned to temporary location 94 before being assigned to t (95). Once again, the reader will note that the instructions in memory locations 11 and 12 appear to be redundant. Again, we will discuss this shortly. The statement 45 rem  loop y  is a remark, so line 45 is added to the symbol table as type L and assigned SML location 14. The statement 50 goto 20  transfers control to line 20. Line number 50 is inserted in the symbol table as type L and assigned SML location 14. The equivalent of goto in SML is the unconditional branch (40) instruction that transfers control to a specific SML location. The compiler searches the symbol table for line 20 and finds that it corresponds to SML location 01. The operation code (40) is multiplied by 100 and location 01 is added to it to produce the instruction 14 +4001. The statement 55 rem  output result  is a remark, so line 55 is inserted in the symbol table as type L and assigned SML location 15. The statement 60 print t  is an output statement. Line number 60 is inserted in the symbol table as type L and assigned SML location 15. The equivalent of print in SML is operation code 11 (write). The location of t is determined from the symbol table and added to the result of the operation code multiplied by 100. The statement 99 end  is the final line of the program. Line number 99 is stored in the symbol table as type L and assigned SML location 16. The end command produces the SML instruction +4300 (43 is halt in SML) which is written as the final instruction in the SML memory array. This completes the first pass of the compiler. We now consider the second pass. The flags array is searched for values other than -1. Location 03 contains 60, so the compiler knows that instruction 03 is incomplete. The compiler completes the instruction by searching the symbol table for 60, determining its location and adding the location to the incomplete instruction. In this case, the search determines that line 60 corresponds to SML location 15, so the completed instruction 03 +4215 is produced replacing 03 +4200. The Simple program has now been compiled successfully. To build the compiler, you will have to perform each of the following tasks: a) Modify the Simpletron simulator program you wrote in Exercise 7.19 to take its input from a file specified by the user (see Chapter 11). Also, the simulator should output its results to a disk file in the same format as the screen output. b) Modify the infix-to-postfix evaluation algorithm of Exercise 12.12 to process multi-digit integer operands and singleletter variable-name operands. [Hint: Standard library function strtok can be used to locate each constant and variable in an expression, and constants can be converted from strings to integers using standard library function atoi.] [Note: The data representation of the postfix expression must be altered to support variable names and integer constants.] c) Modify the postfix evaluation algorithm to process multi-digit integer operands and variable name operands. Also, the algorithm should now implement the previously discussed "hook" so that SML instructions are produced rather than directly evaluating the expression. [Hint: Standard library function strtok can be used to locate each constant and variable in an expression, and constants can be converted from strings to integers using standard library function atoi.] [Note: The data representation of the postfix expression must be altered to support variable names and integer constants.] d) Build the compiler. Incorporate parts (b) and (c) for evaluating expressions in let statements. Your program should contain a function that performs the first pass of the compiler and a function that performs the second pass of the compiler. Both functions can call other functions to accomplish their tasks.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  438 Data Structures: Solutions  Chapter 12  12.28 (Optimizing the Simple Compiler) When a program is compiled and converted into SML, a set of instructions is generated. Certain combinations of instructions often repeat themselves, usually in triplets called productions. A production normally consists of three instructions such as load, add and store. For example, Fig. 12.30 illustrates five of the SML instructions that were produced in the compilation of the program in Fig. 12.3. The first three instructions are the production that adds 1 to y. Note that instructions 06 and 07 store the accumulator value in temporary location 96, then load the value back into the accumulator so instruction 08 can store the value in location 98. Often a production is followed by a load instruction for the same location that was just stored. This code can be optimized by eliminating the store instruction and the subsequent load instruction that operate on the same memory location. This optimization would enable the Simpletron to execute the program faster because there are fewer instructions in this version. Figure 12.31 illustrates the optimized SML for the program of Fig. 12.3. Note that there are four fewer instructions in the optimized code—a memory-space savings of 25%. 04 05 06 07 08  +2098 +3097 +2196 +2096 +2198  (load) (add) (store) (load) (store)  Modify the compiler to provide an option for optimizing the Simpletron Machine Language code it produces. Manually compare the non-optimized code with the optimized code, and calculate the percentage reduction.  Simple program 5 rem sum 1 to x 10 input x 15 rem  check y == x  increment y  30 let y = y + 1  35 rem  add y to total  40 let t = t + y  45 rem  loop y  5 rem sum 1 to x 10 input x 15 rem  check y == x  increment y  30 let y = y + 1  Fig. 12.5  +1099  none  Description rem ignored  read x into location 99 rem ignored  01  +2098  load y (98) into accumulator  02  +3199  sub x (99) from accumulator  03  +4211  branch to location 11 if zero  none  rem ignored  04  +2098  load y into accumulator  05  +3097  add 1 (97) to accumulator  06  +2198  store accumulator in y (98)  none  rem ignored  07  +2096  load t from location (96)  08  +3098  add y (98) accumulator  09  +2196  store accumulator in t (96)  none  rem ignored  none  rem ignored  00  20 if y == x goto 60  25 rem  none 00  20 if y == x goto 60  25 rem  SML location and instruction  +1099  none  read x into location 99 rem ignored  01  +2098  load y (98) into accumulator  02  +3199  sub x (99) from accumulator  03  +4211  branch to location 11 if zero  none  rem ignored  04  +2098  load y into accumulator  05  +3097  add 1 (97) to accumulator  Optimized code for the program of Fig. 12.28. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Data Structures: Solutions 439  Chapter 12  Simple program  35 rem  add y to total  40 let t = t + y  45 rem  loop y  50 goto 20 55 rem  SML location and instruction  Description  06  store accumulator in y (98)  none  rem ignored  07  +2096  load t from location (96)  08  +3098  add y (98) accumulator  09  +2196  store accumulator in t (96)  none 10  output result  +2198  +4001  none  rem ignored  branch to location 01 rem ignored  60 print t  11  +1196  output t (96) to screen  99 end  12  +4300  terminate execution  Fig. 12.5  Optimized code for the program of Fig. 12.28.  12.29 (Modifications to the Simple Compiler) Perform the following modifications to the Simple compiler. Some of these modifications may also require modifications to the Simpletron Simulator program written in Exercise 7.19. a) Allow the modulus operator (%) to be used in let statements. Simpletron Machine Language must be modified to include a modulus instruction. b) Allow exponentiation in a let statement using ^ as the exponentiation operator. Simpletron Machine Language must be modified to include an exponentiation instruction. c) Allow the compiler to recognize uppercase and lowercase letters in Simple statements (e.g., 'A' is equivalent to 'a'). No modifications to the Simpletron Simulator are required. d) Allow input statements to read values for multiple variables such as input x, y. No modifications to the Simpletron Simulator are required. e) Allow the compiler to output multiple values in a single print statement such as print a, b, c. No modifications to the Simpletron Simulator are required. f) Add syntax checking capabilities to the compiler so error messages are output when syntax errors are encountered in a Simple program. No modifications to the Simpletron Simulator are required. g) Allow arrays of integers. No modifications to the Simpletron Simulator are required. h) Allow subroutines specified by the Simple commands gosub and return. Command gosub passes program control to a subroutine and command return passes control back to the statement after the gosub. This is similar to a function call in C. The same subroutine can be called from many gosubs distributed throughout a program. No modifications to the Simpletron Simulator are required. i) Allow repetition structures of the form for x = 2 to 10 step 2 rem Simple statements next  j) This for statement loops from 2 to 10 with an increment of 2. The next line marks the end of the body of the for line. No modifications to the Simpletron Simulator are required. k) Allow repetition structures of the form for x = 2 to 10 rem Simple statements next  l) This for statement loops from 2 to 10 with a default increment of 1. No modifications to the Simpletron Simulator are required. m) Allow the compiler to process string input and output. This requires the Simpletron Simulator to be modified to process and store string values. [Hint: Each Simpletron word can be divided into two groups, each holding a two-digit integer. Each two-digit integer represents the ASCII decimal equivalent of a character.] Add a machine language instruction that will print a string beginning at a certain Simpletron memory location. The first half of the word at that location is © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  440 Data Structures: Solutions  Chapter 12  a count of the number of characters in the string (i.e., the length of the string). Each succeeding half word contains one ASCII character expressed as two decimal digits. The machine language instruction checks the length and prints the string by translating each two-digit number into its equivalent character. n) Allow the compiler to process floating-point values in addition to integers. The Simpletron Simulator must also be modified to process floating-point values. 12.30 (A Simple Interpreter) An interpreter is a program that reads a high-level language program statement, determines the operation to be performed by the statement, and executes the operation immediately. The program is not converted into machine language first. Interpreters execute slowly because each statement encountered in the program must first be deciphered. If statements are contained in a loop, the statements are deciphered each time they are encountered in the loop. Early versions of the BASIC programming language were implemented as interpreters. Write an interpreter for the Simple language discussed in Exercise 12.26. The program should use the infix-to-postfix converter developed in Exercise 12.12 and the postfix evaluator developed in Exercise 12.13 to evaluate expressions in a let statement. The same restrictions placed on the Simple language in Exercise 12.26 should be adhered to in this program. Test the interpreter with the Simple programs written in Exercise 12.26. Compare the results of running these programs in the interpreter with the results of compiling the Simple programs and running them in the Simpletron simulator built in Exercise 7.19.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  13 The Preprocessor: Solutions  SOLUTIONS 13.4 Write a program that defines a macro with one argument to compute the volume of a sphere. The program should compute the volume for spheres of radius 1 to 10 and print the results in tabular format. The formula for the volume of a sphere is ( 4.0 / 3 ) * Ï€ * r3  where Ï€ is 3.14159. 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 13.4 Solution: sphere volume macro */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  #define PI 3.14159 /* constant representing Pi */ /* define preprocessor directive sphere volume */ #define SPHEREVOLUME( r ) ( 4.0 / 3.0 * PI * ( r ) * ( r ) * ( r ) ) int main() { int i; /* loop counter */ /* print header */ printf( "%10s%10s\n", "Radius", "Volume" ); /* use sphere volume macro */ for ( i = 1; i <= 10; i++ ) { printf( "%10d%10.3f\n", i, SPHEREVOLUME( i ) ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  442 The Preprocessor: Solutions  Radius 1 2 3 4 5 6 7 8 9 10  13.5  Chapter 13  Volume 4.189 33.510 113.097 268.082 523.598 904.778 1436.754 2144.659 3053.625 4188.787  Write a program that produces the following output:  The sum of x and y is 13  The program should define macro SUM with two arguments, x and y, and use SUM to produce the output. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  /* Exercise 13.5 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* macro to add two value */ #define SUM( x, y ) ( ( x ) + ( y ) ) int main() { /* display sum of x and y using macro SUM */ printf( "The sum of x and y is %d\n", SUM( 6, 7 ) ); return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  The Preprocessor: Solutions 443  Chapter 13  13.6 Write a program that defines and uses macro MINIMUM2 to determine the smallest of two numeric values. Input the values from the keyboard. 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  /* Exercise 13.6 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* macro to determine smallest of two values */ #define MINIMUM2( x, y ) ( ( x ) < ( y ) ? ( x ) : ( y ) ) int main() { int a; int b; double c; double d;  /* /* /* /*  first integer */ second integer */ first double */ second double */  /* prompt user and read two integers */ printf( "Enter two integers: " ); scanf( "%d%d", &a, &b ); /* use macro MINIMUM to determine and display smallest user entered integer */ printf( "The minimum of %d and %d is %d\n\n", a, b, MINIMUM2( a,b ) ); /* prompt user and read two doubles */ printf( "Enter two doubles: " ); scanf( "%lf%lf", &c, &d ); /* use macro MINIMUM to determine and display smallest user entered double */ printf( "The minimum of %.2f and %.2f is %.2f\n\n", c, d, MINIMUM2( c,d ) ); return 0; /* indicate successful termination */ } /* end main */  Enter two integers: 4 9 The minimum of 4 and 9 is 4 Enter two doubles: 45.7 13.2 The minimum of 45.70 and 13.20 is 13.20  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  444 The Preprocessor: Solutions  Chapter 13  13.7  Write a program that defines and uses macro MINIMUM3 to determine the smallest of three numeric values. Macro MINIMUM3 should use macro MINIMUM2 defined in Exercise 13.6 to determine the smallest number. Input the values from the keyboard. 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  /* Exercise 13.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* macro to determine smallest of two values */ #define MINIMUM2( x, y ) ( ( x ) < ( y ) ? ( x ) : ( y ) ) /* macro that uses MINIMUM2 to determine smallest of three values */ #define MINIMUM3( u, v, w ) ( MINIMUM2( w, MINIMUM2( u, v ) ) ) int main() { int a; int b; int c; double d; double e; double f;  /* /* /* /* /* /*  first integer */ second integer */ third integer */ first double */ second double */ third double */  /* prompt user and read three integers */ printf( "Enter three integers: " ); scanf( "%d%d%d", &a, &b, &c ); /* use macro MINIMUM3 to determine smallest of three user input integers */ printf( "The minimum of %d, %d, and %d is %d\n\n", a, b, c, MINIMUM3( a, b, c ) ); /* prompt user and read three doubles */ printf( "Enter three doubles: " ); scanf( "%lf%lf%lf", &d, &e, &f ); /* use macro MINIMUM3 to determine smallest ofthree user input doubles */ printf( "The minimum of %.2f, %.2f, and %.2f is %.2f\n\n", d, e, f, MINIMUM3( d, e, f ) ); return 0; /* indicate successful termination */ } /* end main */  Enter three integers: 7 2 10 The minimum of 7, 2, and 10 is 2 Enter three doubles: 4.9 93.2 1.3 The minimum of 4.90, 93.20, and 1.30 is 1.30  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  The Preprocessor: Solutions 445  Chapter 13  13.8  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  Write a program that defines and uses macro PRINT to print a string value. ANS: /* Exercise 13.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* macro that prints its argument */ #define PRINT( string ) printf( "%s", ( string ) ) int main() { char text[ 20 ]; /* array to hold user input string */ /* prompt user and read string */ PRINT( "Enter a string: " ); scanf( "%s", text ); /* use PRINT( PRINT( PRINT(  macro to output string entered by user */ "The string entered was: " ); text ); "\n" );  return 0; /* indicate successful termination */ } /* end main */  Enter a string: Hello The string entered was: Hello  13.9 Write a program that defines and uses macro PRINTARRAY to print an array of integers. The macro should receive the array and the number of elements in the array as arguments. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  /* Exercise 13.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      /* macro that prints an array of values */ #define PRINTARRAY( a, n ) for ( i = 0; i < ( n ); i++ ) \ printf( "%d ", a[ i ] ) int main() { int i; /* defines i for use in PRINTARRAY */ /* initialize array to be printed */ int b[ 10 ] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; printf( "The array values are:\n" ); PRINTARRAY( b, 10 ); /* print the array */ return 0; /* indicate successful termination */ } /* end main */  The array values are: 2 4 6 8 10 12 14 16 18 20  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  446 The Preprocessor: Solutions  Chapter 13  13.10 Write a program that defines and uses macro SUMARRAY to sum the values in a numeric array. The macro should receive the array and the number of elements in the array as arguments. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  /* Exercise 13.10 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          /* macro that adds values of a numeric array */ #define SUMARRAY( a, n ) for ( i = 0; i < ( n ); i++ ) \ sum += a[ i ] int main() { int i; /* loop counter */ int sum = 0; /* sum of array elements */ /* initialize array whose values will be added */ int b[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* use macro SUMARRAY to add elements of array */ SUMARRAY( b, 10 ); printf( "The sum of the elements of array b is %d\n", sum ); return 0; /* indicate successful termination */ } /* end main */  The sum of the elements of array b is 55  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  14 Other C Topics: Solutions  SOLUTIONS 14.2 Write a program that calculates the product of a series of integers that are passed to function product using a variablelength argument list. Test your function with several calls, each with a different number of arguments. 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  /* Exercise 14.2 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* function with variable length argument list */ int sum( int i, ... ); int main() { int a = int b = int c = int d = int e =  1; /* values to sum */ 2; 3; 4; 5;  /* display integer values */ printf( "%s%d, %s%d, %s%d, %s%d, %s%d\n", "a = ", a, "b = ", b, "c = ", c, "d = ", d, "e = ", e ); /* call printf( sum( "The "The  sum with different number of arguments in each call */ "%s%d\n%s%d\n%s%d\n%s%d\n", "The sum of a and b is: ", 2, a, b ), "The sum of a, b, and c is: ", sum( 3, a, b, c ), sum of a, b, c, and d is: ", sum( 4, a, b, c, d ), sum of a, b, c, d, and e is: ", sum( 5, a, b, c, d, e ) );  return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  448 Other C Topics: Solutions  30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 a = The The The The  14.3  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  Chapter 14  /* sums integers passed as arguments */ int sum( int i, ... ) { int total = 0; /* sum of integers */ int j; /* loop counter */ va_list ap; /* variable length argument list */ va_start( ap, i ); /* invoke macro to access arguments */ /* calculate total */ for ( j = 1; j <= i; j++ ) { total += va_arg( ap, int ); } /* end for */ va_end( ap ); /* perform termination housekeeping */ return total; /* return sum of arguments */ } /* end function sum */ 1, b = sum of sum of sum of sum of  2, c = 3, d = 4, e = 5 a and b is: 3 a, b, and c is: 6 a, b, c, and d is: 10 a, b, c, d, and e is: 15  Write a program that prints the command-line arguments of the program. ANS: /* Exercise 14.3 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      int main( int argc, char *argv[] ) { int i; /* loop counter */ printf( "The command line arguments are:\n" ); /* display arguments given to program at command line */ for ( i = 0; i < argc; i++ ) { printf( "%s ", argv[ i ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  The command line arguments are: C:\P14_3.exe arg1 arg2 arg3  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Other C Topics: Solutions 449  Chapter 14  14.4 Write a program that sorts an array of integers into ascending order or descending order. The program should use commandline arguments to pass either argument -a for ascending order or -d for descending order. [Note: This is the standard format for passing options to a program in UNIX.] ANS: The DOS command line p14_4.exe -a < p14_4.dat produces the first output shown below, and the DOS command line p14_4.exe -d < p14_4.dat produces the second output shown below. The data file p14_4.dat contains the values 8, 2, 1, 7, 5, 4, 9, 11, 19, and 13.  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  /* Exercise 14.4 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main( int argc, char *argv[] ) { int a[ 100 ]; /* array of integers int count; /* count of integers int temp; /* temporary integer int i; /* loop counter */ int j; /* loop counter */ int order; /* sort in ascending  from user */ entered */ for swapping */  or descending order */  /* tell user if improper arguments were passed */ if ( argc != 2 ) { printf( "Usage: p14_4 -option\n" ); } /* end if */ else { /* prompt user for integers to be sorted */ printf( "Enter up to 100 integers ( EOF to end input ): " ); /* store integers until 100 elements or EOF entered */ for ( count = 0; !feof( stdin ) && count < 100; count++ ) { scanf( "%d", &a[ count ] ); } /* end for */ /* set order based on command-line argument */ order = ( argv[ 1 ][ 1 ] == 'd' ) ? 0 : 1; /* loop through array and swap elements as needed */ for ( i = 1; i < count - 1; i++ ) { for ( j = 0; j < count - 1; j++ ) { /* swap in ascending order if that option specified */ if ( order == 1 ) { if ( a[ i ] < a[ j ] ) { temp = a[ i ]; a[ i ] = a[ j ]; a[ j ] = temp; } /* end if */ } /* end if */ else { /* swap in descending order */ if ( a[ i ] > a[ j ] ) { temp = a[ i ]; a[ i ] = a[ j ]; a[ j ] = temp; } /* end if */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  450 Other C Topics: Solutions  52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71  Chapter 14  } /* end else */ } /* end for */ } /* end for */ printf( "\n\nThe sorted array is:\n" ); /* display sorted array */ for ( i = 0; i < count - 1; i++ ) { printf( "%d ", a[ i ] ); } /* end for */ printf( "\n" ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  The sorted array is: 1 2 4 5 7 8 9 11 13 19  The sorted array is: 19 13 11 9 8 7 5 4 2 1  14.5 Write a program that places a space between each character in a file. The program should first write the contents of the file being modified into a temporary file with spaces between each character, then copy the file back to the original file. This operation should overwrite the original contents of the file. 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  /* Exercise 14.5 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              int main() { FILE *filePtr; FILE *tempFilePtr; int c; char fileName[ 30 ];  /* /* /* /*  pointer to file being modified */ temporary file pointer */ current character */ name of file to be modified */  /* prompt user and read file name */ printf( "This program inserts spaces between each character\n" "of a file. Enter a file to be modified: " ); scanf( "%s", fileName ); /* exit program if file cannot be opened */ if ( ( filePtr = fopen( fileName, "r+" ) ) != NULL ) { /* exit program if temporary file cannot be opened */ if ( ( tempFilePtr = tmpfile() ) != NULL ) { printf( "\nThe file before modification is:\n" ); /* read each character from file */ while ( ( c = getc( filePtr ) ) != EOF ) { putchar( c ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Other C Topics: Solutions 451  Chapter 14  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 55 56 57  putc( c, tempFilePtr ); /* put character in temp file */ /* write a space to temp file */ if ( c != '\n' ) { putc( ' ', tempFilePtr ); } /* end if */ } /* end while */ rewind( tempFilePtr ); /* rewind both file pointers */ rewind( filePtr ); printf( "\n\nThe file after modification is:\n" ); /* read each character from temp file */ while ( ( c = getc( tempFilePtr ) ) != EOF ) { putchar( c ); putc( c, filePtr ); /* rewrite character to file */ } /* end while */ } /* end if */ else { printf( "Unable to open temporary file\n" ); } /* end else */ } /* end if */ else { printf( "Unable to open %s\n", fileName ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */  This program inserts spaces between each character of a file. Enter a file to be modified: test.dat The file before modification is: This is a test file for exercise 14.5.  The file after modification is: T h i s i s a t e s t f i l e e x e r c i s e 1 4 . 5 .  f o r  14.6 Read the manuals for your compiler to determine what signals are supported by the signal handling library (signal.h). Write a program that contains signal handlers for the standard signals SIGABRT and SIGINT. The program should test the trapping of these signals by calling function abort to generate a signal of type SIGABRT and by typing                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  c to generate a signal of type SIGINT.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  452 Other C Topics: Solutions  Chapter 14  14.7 Write a program that dynamically allocates an array of integers. The size of the array should be input from the keyboard. The elements of the array should be assigned values input from the keyboard. Print the values of the array. Next, reallocate the memory for the array to 1/2 of the current number of elements. Print the values remaining in the array to confirm that they match the first half of the values in the original array. 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  /* Exercise 14.7 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          int main() { int count; /* number of elements in array */ int i; /* loop counter */ int *array; /* pointer to the array */ /* prompt user and read integer size of array */ printf( "This program dynamically allocates an array of integers.\n" "Enter the number of elements in the array: " ); scanf( "%d", &count ); /* dynamically allocate memory */ array = calloc( count, sizeof( int ) ); /* initialize elements of array with user-entered data */ for ( i = 0; i < count; i++ ) { printf( "Enter an integer: " ); scanf( "%d", &array[ i ] ); } /* end for */ printf( "\nThe elements of the array are:\n" ); /* display the original array */ for ( i = 0; i < count; i++ ) { printf( "%d ", array[ i ] ); } /* end for */ /* reallocate to half the original size */ realloc( array, count / 2 * sizeof( int ) ); printf( "\n\nThe elements of the array after reallocation are:\n" ); /* display array after cut in half */ for ( i = 0; i < count / 2; i++ ) { printf( "%d ", array[ i ] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Other C Topics: Solutions 453  Chapter 14  This program dynamically allocates an array of integers. Enter the number of elements in the array: 10 Enter an integer: 1 Enter an integer: 2 Enter an integer: 3 Enter an integer: 4 Enter an integer: 5 Enter an integer: 6 Enter an integer: 7 Enter an integer: 8 Enter an integer: 9 Enter an integer: 10 The elements of the array are: 1 2 3 4 5 6 7 8 9 10 The elements of the array after reallocation are: 1 2 3 4 5  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  454 Other C Topics: Solutions  Chapter 14  14.8 Write a program that takes two command-line arguments that are file names, reads the characters from the first file one at a time and writes the characters in reverse order to the second file. 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  /* Exercise 14.8 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              /* function prototype */ void reverseFile( FILE *inPtr, FILE *outPtr ); int main( int argc, int *argv[] ) { FILE *inFilePtr; /* input file pointer */ FILE *outFilePtr; /* output file pointer */ /* tell user if invalid arguments */ if ( argc != 3 ) { printf( "Usage: copy infile outfile\n" ); } /* end if */ else { /* exit program if input file cannot be opened */ if ( ( inFilePtr = fopen( argv[ 1 ], "r" ) ) != NULL ) { /* exit program if output file cannot be opened */ if ( ( outFilePtr = fopen( argv[ 2 ], "w" ) ) != NULL ) { reverseFile( inFilePtr, outFilePtr ); } /* end if */ else { printf( "File \"%s\" could not be opened\n", argv[ 2 ] ); } /* end else */ } /* end if */ else { printf( "File \"%s\" could not be opened\n", argv[ 1 ] ); } /* end else */ } /* end else */ return 0; /* indicate successful termination */ } /* end main */ /* function that writes characters in reverse order */ void reverseFile( FILE *inPtr, FILE *outPtr ) { int c; /* current character */ /* if not end of file */ if ( ( c = fgetc( inPtr ) ) != EOF ) { reverseFile( inPtr, outPtr ); } /* end if */ fputc( c, outPtr ); /* write character to output file */ } /* end function reverseFile */  .stnemugra enil dnammoc eht rof ecnetnes tset a si sihT  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Other C Topics: Solutions 455  Chapter 14  14.9  Write a program that uses goto statements to simulate a nested looping structure that prints a square of asterisks as follows:  ***** * * * * * * *****  The program should use only the following three printf statements: printf( "*" ); printf( " " ); printf( "\n" );  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  456 Other C Topics: Solutions  Chapter 14  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  /* Exercise 14.9 Solution */ #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  int main() { int size; int row = 0; int col;  /* length of square sides */ /* number of rows */ /* number of columns */  /* obtain length of side of square from user */ printf( "Enter the side length of the square: " ); scanf( "%d", &size ); start: /* label */ ++row; printf( "\n" ); /* if all rows have been made end program */ if ( row > size ) { goto end; } /* end if */ col = 1; /* set column variable to first character of line */ innerLoop: /* label */ /* if all columns have been displayed return to top of loop */ if ( col > size ) { goto start; } /* end if */ /* display stars and spaces in appropriate positions */ if ( row == 1 || row == size || col == 1 || col == size ) { printf( "*" ); } /* end if */ else { printf( " " ); } /* end else */ ++col; /* increment column */ goto innerLoop; /* continue displaying columns */ end: /* label */ return 0; /* indicate successful termination */ } /* end main */  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  15 C++ as a "Better C": Solutions  SOLUTIONS 15.5 Write a C++ program that uses an inline function circleArea to prompt the user for the radius of a circle and to calculate and print the area of that circle. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  // Exercise 15.5 Solution #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      using std::cout; using std::endl; using std::cin; double pi = 3.14159;  // global variable  inline double circleArea( double r ) { return pi * r * r; } int main() { double radius; cout << "Enter the radius of the circle: "; cin >> radius; cout << "The area of the circle is " << circleArea( radius ) << endl; return 0; }  Enter the radius of the circle: 10 The area of the circle is 314.159  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  458 C++ as a "Better C": Solutions  15.6  Chapter 15  Write a complete C++ program with the two alternate functions specified below, of which each simply triples the variable  count defined in main. Then compare and contrast the two approaches. These two functions are a) Function tripleCallByValue that passes a copy of count call-by-value, triples the copy and returns the new value. b) Function tripleByReference that passes count with true call-by-reference via a reference parameter and triples the original copy of count through its alias (i.e., the reference parameter).  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  // Exercise 15.6 Solution #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          using std::cout; using std::endl; using std::cin; int tripleCallByValue( int ); void tripleByReference( int & ); int main() { int value, &valueRef = value; cout << "Enter an integer: "; cin >> value; cout << << << << << <<  "\nValue before call to tripleCallByValue() is: " value << "\nValue returned from tripleCallByValue() is: " tripleCallByValue( value ) "\nValue (in main) after tripleCallByValue() is: " << value "\n\nValue before call to tripleByReference() is: " value << '\n';  tripleByReference( valueRef ); cout << "Value (in main) after call to tripleByReference() is: " << value << endl; return 0; } int tripleCallByValue( int valueCopy ) { return valueCopy *= 3; } void tripleByReference( int &aliasRef ) { aliasRef *= 3; }  Enter an integer: 8 Value before call to tripleCallByValue() is: 8 Value returned from tripleCallByValue() is: 24 Value (in main) after tripleCallByValue() is: 8 Value before call to tripleByReference() is: 8 Value (in main) after call to tripleByReference() is: 24  15.7  What is the purpose of the unary scope resolution operator? ANS: The unary score resolution operator is used to access a global variable. In particular, the unary scope resolution operator is useful when a global variable needs to be accessed and a local variable has the same name. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C++ as a "Better C": Solutions 459  Chapter 15  15.8 Write a program that uses a function template called min to determine the smaller of two arguments. Test the program using integer, character and floating-point number pairs. 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  // Exercise 15.8 Solution #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              using std::cout; using std::endl; template < class T > void minimum( T value1, { if ( value1 > value2 cout << value2 << else cout << value1 <<  T value2 )  // find the smallest value  ) " is smaller than " << value1; " is smaller than " << value2;  cout << endl; } int main() { minimum( 7, 54 ); // integers minimum( 4.35, 8.46 ); // doubles minimum( 'g', 'T' ); // characters return 0; }  7 is smaller than 54 4.35 is smaller than 8.46 T is smaller than g  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  460 C++ as a "Better C": Solutions  Chapter 15  15.9 Write a program that uses a function template called max to determine the largest of three arguments. Test the program using integer, character and floating-point number pairs. 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  // Exercise 15.9 Solution #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  using std::cout; using std::endl; template < class T > void max( T value1, T value2, T value3 ) // find the largest value { if ( value1 > value2 && value1 > value3 ) cout << value1 << " is greater than " << value2 << " and " << value3; else if ( value2 > value1 && value2 > value3 ) cout << value2 << " is greater than " << value1 << " and " << value3; else cout << value3 << " is greater than " << value1 << " and " << value2; cout << endl; } int main() { max( 7, 5, 2 ); max( 9.35, 8.461, 94.3 ); max( '!', 'T', '$' );  // integers // doubles // characters  return 0; }  7 is greater than 5 and 2 94.3 is greater than 9.35 and 8.461 T is greater than ! and $  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  C++ as a "Better C": Solutions 461  Chapter 15  15.10 Determine whether the following program segmentss contain errors. For each error, explain how it can be corrected. [Note: For a particular program segment, it is possible that no errors are present in the segment.] a) template < class A > int sum( int num1, int num2, int num3 ) { return num1 + num2 + num3; }  ANS: The function return type and parameter types should be A. b) void printResults( int x, int y ) { cout << "The sum is " << x + y << '\n'; return x + y; }  ANS: The function specifies a void return type and attempts to return a value. Two possible solutions: (1) change void to int or (2) remove the line return x + y;. c) template < A > A product( A num1, A num2, A num3 ) { return num1 * num2 * num3; }  ANS: The keyword class is needed in the template declaration template                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          . d) double cube( int ); int cube( int );  ANS: The signatures are not different. Overloaded functions must have different signatures meaning that the name and parameter list must be different. If only return types differ, the compiler generates an error message.  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  462 C++ as a "Better C": Solutions  © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.  Chapter 15  16 C++ Classes and Data Abstraction: Solutions  SOLUTIONS 16.3  What is the purpose of the scope resolution operator? ANS: The scope resolution operator is used to specify the class to which a function belongs. It also resolves the ambiguity caused by multiple classes having member functions of the same name.  16.4 Provide a constructor that is capable of using the current time from the time function—declared in the C Standard Library header ctime—to initialize an object of the Time class. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  // p16_4.H #ifndef p16_4_H #define p16_4_H  22 23 24 25 26 27  // p16_4.cpp // member function definitions for p16_4.cpp #include                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          class Time { public: Time(); void setHour( int ); void setMinute( int ); void setSecond( int ); int getHour( void ) const; int getMinute( void ) const; int getSecond( void ) const; void printStandard( void ) const; private: int hour; int minute; int second; };