Write a Program That Reads the Three Strings Suzy, "Suzy" and 'suzy'.
Chtp4IM(chtp4_01) C How To Program Solution Manual
User Manual: Pdf
Open the PDF directly: View 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 */ #includeint 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