编辑推荐

相关资源

下载专区

TI最新应用解决方案

- 具有集成信号和电源的隔离式 RS-485 参考设计
- 电容式触摸屏显示器参考设计
- 通过 IEC61000-4 测试的工业电流输出压力传感器发送器参考设计
- 雷达脉冲飞行时间参考设计
- 具有 IO-Link 的超声波距离传感器参考设计
- 支持 BLE 连接、由 4mA 至 20mA 电流回路供电的现场发送器参考设计
- EtherCAT 从属设备和多协议工业以太网参考设计
- 具有 MSP430 智能模拟组合并且由回路供电的 4mA 至 20mA RTD 温度变送器参考设计
- 适用于 24 位 ADC 的无变压器、双极隔离式电源参考设计
- 嵌入式 USB 2.0 参考设计
- 支持 M-Bus 和 RS-485 协议转换的数据收集器参考设计
- 用于空气断路器的高分辨率、快速启动模拟前端参考设计

上传者其他资源

应用技术热门资源

本周本月全部

测试测量相关资料

文档简介

c how to problem PDF

文档预览

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 14 Other C Topics 15 C++ as a “Better C” 16 C++ Classes and Data Abstraction 17 C++ Classes: Part II 18 C++ Operator Overloading 19 C++ Inheritance 20 C++ Virtual Functions and Polymorphism 21 C++ Stream Input/Output 22 C++ Templates 23 C++ Exception Handling: Solution 24 Introduction to Java Applications and Applets 25 Beyond C & C++: Operators, Methods & Arrays in Java 26 Java Object-Based Programming 27 Java Object-Oriented Programming 28 Java Graphics and Java2D 29 Java Graphical User Interface Components 30 Java Multimedia: Images, Animation, and Audio 441 447 457 463 485 493 499 511 519 537 543 547 557 585 603 617 633 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 de- vices 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 Introduction to Computers, the Internet and the World Wide Web: Solutions 3 1.10 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 Chapter 1 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. Chapter 2 Introduction to C Programming: Solutions 7 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 state- ment 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: 56 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 /* Exercise 2.16 Solution */ 2 #include 3 4 int main() 5{ 6 int x; /* define first number */ 7 int y; /* define second number */ 8 9 printf( "Enter two numbers: "); /* prompt user */ 10 scanf( "%d%d", &x, &y ); /* read values from keyboard */ 11 12 /* output results */ 13 printf( "The sum is %d\n", x + y ); 14 printf( "The product is %d\n", x * y ); 15 printf( "The difference is %d\n", x - y ); 16 printf( "The quotient is %d\n", x / y ); 17 printf( "The modulus is %d\n", x % y ); 18 19 return 0; /* indicate successful termination */ 20 21 } /* 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 Chapter 2 2.17 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: 1 /* Exercise 2.17 Solution */ 2 #include 3 4 int main() 5{ 6 printf( "1 2 3 4\n\n" ); /* part a */ 7 8 printf( "%d %d %d %d\n\n", 1, 2, 3, 4 ); /* part b */ 9 10 printf( "1 " ); /* part c */ 11 printf( "2 " ); 12 printf( "3 " ); 13 printf( "4\n" ); 14 15 return 0; /* indicates successful termination */ 16 17 } /* end main */ 1234 1234 1234 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 /* Exercise 2.18 Solution */ 2 #include 3 4 int main() 5{ 6 int x; /* define first number */ 7 int y; /* define second number */ 8 9 printf( "Enter two numbers: " ); /* prompt */ 10 scanf( "%d%d", &x, &y ); /* read two integers */ 11 12 /* compare the two numbers */ 13 if ( x > y ) { 14 printf( "%d is larger\n", x ); 15 } /* end if */ 16 17 if ( x < y ) { 18 printf( "%d is larger\n", y ); 19 } /* end if */ 20 21 if ( x == y ) { 22 printf( "These numbers are equal\n" ); 23 } /* end if */ 24 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Introduction to C Programming: Solutions 9 25 return 0; /* indicate successful termination */ 26 27 } /* 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 /* Exercise 2.19 Solution */ 2 #include 3 4 int main() 5{ 6 int a; /* define first integer */ 7 int b; /* define second integer */ 8 int c; /* define third integer */ 9 int smallest; /* smallest integer */ 10 int largest; /* largest integer */ 11 12 printf( "Input three different integers: " ); /* prompt user */ 13 scanf( "%d%d%d", &a, &b, &c ); /* read three integers */ 14 15 /* output sum, average and product of the three integers */ 16 printf( "Sum is %d\n", a + b + c ); 17 printf( "Average is %d\n", ( a + b + c ) / 3 ); 18 printf( "Product is %d\n", a * b * c ); 19 20 smallest = a; /* assume first number is the smallest */ 21 22 if ( b < smallest ) { /* is b smaller? */ 23 smallest = b; 24 } /* end if */ 25 26 if ( c < smallest ) { /* is c smaller? */ 27 smallest = c; 28 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 10 Introduction to C Programming: Solutions Chapter 2 29 30 printf( "Smallest is %d\n", smallest ); 31 32 largest = a; /* assume first number is the largest */ 33 34 if ( b > largest ) { /* is b larger? */ 35 largest = b; 36 } /* end if */ 37 38 if ( c > largest ) { /* is c larger? */ 39 largest = c; 40 } /* end if */ 41 42 printf( "Largest is %d\n", largest ); 43 44 return 0; /* indicate successful termination */ 45 46 } /* 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 /* Exercise 2.20 Solution */ 2 #include 3 4 int main() 5{ 6 int radius; /* circle radius */ 7 8 printf( "Input the circle radius: " ); /* prompt user */ 9 scanf( "%d", &radius ); /* read integer radius */ 10 11 /* calculate and output diameter, circumference and area */ 12 printf( "\nThe diameter is %d\n", 2 * radius ); 13 printf( "The circumference is %f\n", 2 * 3.14159 * radius ); 14 printf( "The area is %f\n", 3.14159 * radius * radius ); 15 16 return 0; /* indicate successful termination */ 17 18 } /* 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. Chapter 2 Introduction to C Programming: Solutions 11 2.21 Write a program that prints a box, an oval, an arrow and a diamond as follows: ********* * * * * * * * * * * * * * * ********* *** * * * * * * * * * * * * * * *** * *** ***** * * * * * * * ** ** * * * * * * ** ** * ANS: 1 /* Exercise 2.21 Solution */ 2 #include 3 4 int main() 5{ 6 printf( "********* *** * *\n" ); 7 printf( "* * * * *** * *\n" ); 8 printf( "* ** * ***** * *\n" ); 9 printf( "* ** * * * *\n" ); 10 printf( "* ** * * * *\n" ); 11 printf( "* ** * * * *\n" ); 12 printf( "* ** * * * *\n" ); 13 printf( "* * * * * * *\n" ); 14 printf( "********* *** * *\n" ); 15 16 return 0; /* indicates successful termination */ 17 18 } /* end main */ 2.22 What does the following code print? ANS: printf( "*\n**\n***\n****\n*****\n" ); * ** *** **** ***** 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 /* Exercise 2.23 Solution */ 2 #include 3 4 int main() 5{ 6 int largest; /* largest integer */ 7 int smallest; /* smallest integer */ 8 int int1; /* define int1 for user input */ 9 int int2; /* 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 Chapter 2 10 int int3; /* define int3 for user input */ 11 int temp; /* temporary integer for swapping */ 12 13 printf( "Input 5 integers: " ); /* prompt user and read 5 ints */ 14 scanf( "%d%d%d%d%d", &largest, &smallest, &int1, &int2, &int3 ); 15 16 if ( smallest > largest ) { /* make comparisons */ 17 temp = largest; 18 largest = smallest; 19 smallest = temp; 20 } /* end if */ 21 22 if ( int1 > largest ) { 23 largest = int1; 24 } /* end if */ 25 26 if ( int1 < smallest ) { 27 smallest = int1; 28 } /* end if */ 29 30 if ( int2 > largest ) { 31 largest = int2; 32 } /* end if */ 33 34 if ( int2 < smallest ) { 35 smallest = int2; 36 } /* end if */ 37 38 if ( int3 > largest ) { 39 largest = int3; 40 } /* end if */ 41 42 if ( int3 < smallest ) { 43 smallest = int3; 44 } /* end if */ 45 46 printf( "The largest value is %d\n", largest ); 47 printf( "The smallest value is %d\n", smallest ); 48 49 return 0; /* indicate successful termination */ 50 51 } /* 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 /* Exercise 2.24 Solution */ 2 #include 3 4 int main() 5{ 6 int integer; /* integer input by user */ 7 8 printf( "Input an integer: " ); /* prompt */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Introduction to C Programming: Solutions 13 9 scanf( "%d", &integer ); /* read integer */ 10 11 /* test if integer is even */ 12 if ( integer % 2 == 0 ) { 13 printf( "%d is an even integer\n", integer ); 14 } /* end if */ 15 16 /* test if integer is odd */ 17 if ( integer % 2 != 0 ) { 18 printf( "%d is an odd integer\n", integer ); 19 } /* end if */ 20 21 return 0; /* indicate successful termination */ 22 23 } /* 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 PP PP PP PP JJ J J J JJJJJJJ DDDDDDDDD D D D D D D DDDDD ANS: 1 /* Exercise 2.25 Solution */ 2 #include 3 4 int main() 5{ 6 printf( "PPPPPPPPP\n" ); 7 printf( " P P\n" ); 8 printf( " P P\n" ); 9 printf( " P P\n" ); 10 printf( " P P\n" ); 11 printf( "\n" ); 12 printf( " JJ\n" ); 13 printf( " J\n" ); 14 printf( "J\n" ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 14 Introduction to C Programming: Solutions Chapter 2 15 printf( " J\n" ); 16 printf( " JJJJJJJ\n" ); 17 printf( "\n" ); 18 printf( "DDDDDDDDD\n" ); 19 printf( "D D\n" ); 20 printf( "D D\n" ); 21 printf( " D D\n" ); 22 printf( " DDDDD\n" ); 23 24 return 0; /* indicate successful termination */ 25 26 } /* 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 /* Exercise 2.26 Solution */ 2 #include 3 4 int main() 5{ 6 int integer1; /* first integer */ 7 int integer2; /* second integer */ 8 9 printf( "Input two integers: " ); /* prompt user */ 10 scanf( "%d%d", &integer1, &integer2 ); /* read two integers */ 11 12 /* use remainder operator */ 13 if ( integer1 % integer2 == 0 ) { 14 printf( "%d is a multiple of %d ", integer1, integer2 ); 15 printf( "by a factor of %d\n", integer1 / integer2 ); 16 } /* end if */ 17 18 if ( integer1 % integer2 != 0 ) { 19 printf( "%d is not a multiple of %d\n", integer1, integer2 ); 20 } /* end if */ 21 22 return 0; /* indicate successful termination */ 23 24 } /* 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. Chapter 2 Introduction to C Programming: Solutions 15 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 /* Exercise 2.27 Solution */ 2 #include 3 4 int main() 5{ 6 printf( "With eight printf() statements: \n" ); 7 8 printf( "* * * * * * * *\n" ); 9 printf( " * * * * * * * *\n" ); 10 printf( "* * * * * * * *\n" ); 11 printf( " * * * * * * * *\n" ); 12 printf( "* * * * * * * *\n" ); 13 printf( " * * * * * * * *\n" ); 14 printf( "* * * * * * * *\n" ); 15 printf( " * * * * * * * *\n" ); 16 17 printf( "\nNow with one printf() statement: \n" ); 18 19 printf( "* * * * * * * *\n * * * * * * * *\n" 20 "* * * * * * * *\n * * * * * * * *\n" 21 "* * * * * * * *\n * * * * * * * *\n" 22 "* * * * * * * *\n * * * * * * * *\n" ); 23 24 return 0; /* indicate successful termination */ 25 26 } /* 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 /* Exercise 2.29 Solution */ 2 #include 3 4 int main() 5{ 6 char intEquivalent; /* letter, digit or character */ 7 8 printf( "Input a letter, digit, or character: " ); /* prompt */ 9 scanf( "%c", &intEquivalent ); /* read user input */ 10 11 printf( "%c's integer equivalent is %d\n", intEquivalent, 12 intEquivalent ); 13 14 return 0; /* indicate successful termination */ 15 16 } /* 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 42139 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Introduction to C Programming: Solutions 17 ANS: 1 /* Exercise 2.30 Solution */ 2 #include 3 4 int main() 5{ 6 int number; /* number input by user */ 7 int temp1; /* first temporary integer */ 8 int temp2; /* second temporary integer */ 9 10 printf( "Enter a five-digit number: " ); /* prompt user */ 11 scanf( "%d", &number ); /* read integer */ 12 13 printf( "%d ", number / 10000 ); /* print left-most digit */ 14 temp2 = number % 10000; 15 16 printf( " %d ", temp2 / 1000 ); 17 temp1 = temp2 % 1000; 18 19 printf( " %d ", temp1 / 100 ); 20 temp2 = temp1 % 100; 21 22 printf( " %d ", temp2 / 10 ); 23 temp1 = temp2 % 10; 24 25 printf( " %d\n", temp1 ); /* print right-most digit */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* end main */ Enter a five-digit number: 23456 23456 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 /* Exercise 2.31 Solution */ 2 #include 3 4 int main() 5{ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 18 Introduction to C Programming: Solutions 6 int count = 0; /* initialize count to zero */ 7 8 /* calculate the square and cube for the numbers 0 to 10 */ 9 printf( "\nnumber\tsquare\tcube\n" ); 10 printf( "%d\t%d\t%d\n", count, count * count, 11 count * count * count ); 12 13 count = count + 1; /* increment count by 1 */ 14 printf( "%d\t%d\t%d\n", count, count * count, 15 count * count * count ); 16 17 count = count + 1; 18 printf( "%d\t%d\t%d\n", count, count * count, 19 count * count * count ); 20 21 count = count + 1; 22 printf( "%d\t%d\t%d\n", count, count * count, 23 count * count * count ); 24 25 count = count + 1; 26 printf( "%d\t%d\t%d\n", count, count * count, 27 count * count * count ); 28 29 count = count + 1; 30 printf( "%d\t%d\t%d\n", count, count * count, 31 count * count * count ); 32 33 count = count + 1; 34 printf( "%d\t%d\t%d\n", count, count * count, 35 count * count * count ); 36 37 count = count + 1; 38 printf( "%d\t%d\t%d\n", count, count * count, 39 count * count * count ); 40 41 count = count + 1; 42 printf( "%d\t%d\t%d\n", count, count * count, 43 count * count * count ); 44 45 count = count + 1; 46 printf( "%d\t%d\t%d\n", count, count * count, 47 count * count * count ); 48 49 count = count + 1; 50 printf( "%d\t%d\t%d\n", count, count * count, 51 count * count * count ); 52 53 return 0; /* indicate successful termination */ 54 55 } /* end main */ Chapter 2 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 #include 2 3 int main() 4{ 5 int x = 1, total = 0, y; 6 7 while ( x <= 10 ) { 8 y = x * x; 9 printf( "%d\n", y ); 10 total += y; 11 ++x; 12 } 13 14 printf("Total is %d\n", total); 15 16 return 0; 17 } © 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. Chapter 3 Structured Program Development in C: Solutions 23 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 /* Exercise 3.17 Solution */ 2 #include 3 4 int main() 5{ 6 double gallons; /* gallons used for current tank*/ 7 double miles; /* miles driven for current tank*/ 8 double totalGallons = 0.0; /* total gallons used */ 9 double totalMiles = 0.0; /* total miles driven */ 10 double totalAverage; /* average miles/gallon */ 11 12 /* get gallons used for first tank */ 13 printf( "Enter the gallons used ( -1 to end): " ); 14 scanf( "%lf", &gallons ); 15 16 /* loop until sentinel value read from user */ 17 while ( gallons != -1.0 ) { 18 totalGallons += gallons; /* add current tank gallons to total */ 19 20 printf( "Enter the miles driven: " ); /* get miles driven */ 21 scanf( "%lf", &miles ); 22 totalMiles += miles; /* add current tank miles to total */ 23 24 /* display miles per gallon for current tank */ 25 printf( "The Miles / Gallon for this tank was %f\n\n", 26 miles / gallons ); 27 28 /* get next tank's gallons */ 29 printf( "Enter the gallons used ( -1 to end ): " ); 30 scanf( "%lf", &gallons ); 31 } /* end while */ 32 33 /* calculate average miles per gallon over all tanks */ 34 totalAverage = totalMiles / totalGallons; 35 printf( "\nThe overall average Miles/Gallon was %f\n", totalAverage ); 36 37 return 0; /* indicate successful termination */ 38 39 } /* 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 account number ( -1 to end ): 200 Enter beginning balance: 1000.00 Enter total charges: 123.45 Enter total credits: 321.00 Enter credit limit: 1500.00 Enter account number ( -1 to end ): 300 Enter beginning balance: 500.00 Enter total charges: 274.73 Enter total credits: 100.00 Enter 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. Chapter 3 Structured Program Development in C: Solutions 25 3) 1 /* Exercise 3.18 Solution */ 2 #include 3 4 int main() 5{ 6 int accountNumber; /* current account's number */ 7 double balance; /* current account's starting balance */ 8 double charges; /* current account's total charges */ 9 double credits; /* current account's total credits */ 10 double limit; /* current account's credit limit */ 11 12 /* get account number */ 13 printf( "\nEnter account number ( -1 to end): " ); 14 scanf( "%d", &accountNumber ); 15 16 /* loop until sentinel value read from user */ 17 while ( accountNumber != -1 ) { 18 printf( "Enter beginning balance: " ); 19 scanf( "%lf", &balance ); 20 21 printf( "Enter total charges: " ); 22 scanf( "%lf", &charges ); 23 24 printf( "Enter total credits: " ); 25 scanf( "%lf", &credits ); 26 27 printf( "Enter credit limit: " ); 28 scanf( "%lf", &limit ); 29 30 balance += charges - credits; /* calculate balance */ 31 32 /* if balance is over limit, display account number 33 with credit limit and balance to two digits of precision */ 34 if ( balance > limit ) { 35 printf( "%s%d\n%s%.2f\n%s%.2f\n%s\n", 36 "Account: ", accountNumber, "Credit limit: ", limit, 37 "Balance: ", balance, "Credit Limit Exceeded." ); 38 } /* end if */ 39 40 /* prompt for next account */ 41 printf( "\nEnter account number ( -1 to end ): " ); 42 scanf( "%d", &accountNumber ); 43 } /* end while */ 44 45 return 0; /* indicate successful termination */ 46 47 } /* 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 /* Exercise 3.19 Solution */ 2 #include 3 4 int main() 5{ 6 double sales; /* gross weekly sales */ 7 double wage; /* commissioned earnings */ 8 9 /* get first sales */ 10 printf( "Enter sales in dollars ( -1 to end): " ); 11 scanf( "%lf", &sales ); 12 13 /* loop until sentinel value read from user */ 14 while ( sales != -1.0 ) { 15 wage = 200.0 + 0.09 * sales; /* calculate wage */ 16 17 /* display salary */ 18 printf( "Salary is: $%.2f\n\n", wage ); 19 20 /* prompt for next sales */ 21 printf( "Enter sales in dollars ( -1 to end ): " ); 22 scanf( "%lf", &sales ); 23 } /* end while */ 24 25 return 0; /* indicate successful termination */ 26 27 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 27 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 /* Exercise 3.20 Solution */ 2 #include 3 4 int main() 5{ 6 double principal; /* loan principal */ 7 double rate; /* interest rate */ 8 double interest; /* interest charge */ 9 int term; /* length of loan in days */ 10 11 /* get loan principal */ 12 printf( "Enter loan principal ( -1 to end): " ); 13 scanf( "%lf", &principal ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 28 Structured Program Development in C: Solutions Chapter 3 14 15 /* loop until sentinel value is read from user */ 16 while ( principal != -1.0 ) { 17 printf( "Enter interest rate: " ); /* get rate */ 18 scanf( "%lf", &rate ); 19 20 printf( "Enter term of the loan in days: " ); /* get term */ 21 scanf( "%d", &term ); 22 23 /* calculate interest charge */ 24 interest = principal * rate * term / 365.0; 25 printf( "The interest charge is $%.2f\n\n", interest ); 26 27 /* get next loan principal */ 28 printf( "Enter loan principal ( -1 to end ): " ); 29 scanf( "%lf", &principal ); 30 } /* end while */ 31 32 return 0; /* indicate successful termination */ 33 34 } /* 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 ): 39 Enter hourly rate of the worker ( $00.00 ): 10.00 Salary is $390.00 Enter number of hours worked ( -1 to end ): 40 Enter hourly rate of the worker ( $00.00 ): 10.00 Salary is $400.00 Enter number of hours worked ( -1 to end ): 41 Enter hourly rate of the worker ( $00.00 ): 10.00 Salary is $415.00 Enter number of hours worked ( -1 to end ): -1 ANS: 2) 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. Chapter 3 Structured Program Development in C: Solutions 29 3) 1 /* Exercise 3.21 Solution */ 2 #include 3 4 int main( void ) 5{ 6 double hours; /* total hours worked */ 7 double rate; /* hourly pay rate */ 8 double salary; /* gross pay */ 9 10 /* get first employee's hours worked */ 11 printf( "Enter number of hours worked ( -1 to end ): " ); 12 scanf( "%lf", &hours ); 13 14 /* loop until sentinel value read from user */ 15 while ( hours != -1.0 ) { 16 17 /* get hourly rate */ 18 printf( "Enter hourly rate of the worker ( $00.00 ): " ); 19 scanf( "%lf", &rate ); 20 21 /* if employee worked less than 40 hours */ 22 if ( hours <= 40 ) { 23 salary = hours * rate; 24 } /* end if */ 25 else { /* compute "time-and-a-half" pay */ 26 salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5; 27 } /* end else */ 28 29 /* display gross pay */ 30 printf( "Salary is $%.2lf\n\n", salary ); 31 32 /* prompt for next employee's data */ 33 printf( "Enter number of hours worked ( -1 to end ): " ); 34 scanf( "%lf", &hours ); 35 } /* end while */ 36 37 return 0; /* indicate successful termination */ 38 39 } /* end main */ 3.22 Write a program that demonstrates the difference between predecrementing and postdecrementing using the decrement operator --. ANS: 1 /* Exercise 3.22 Solution */ 2 #include 3 4 int main() 5{ 6 int c; /* define c to use decrement operator */ 7 8 c = 5; 9 printf( "%d\n", c ); 10 printf( "%d\n", --c ); /* predecrement */ 11 printf( "%d\n\n", c ); 12 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 30 Structured Program Development in C: Solutions Chapter 3 13 c = 5; 14 printf( "%d\n", c ); 15 printf( "%d\n", c-- ); /* postdecrement */ 16 printf( "%d\n\n", c ); 17 18 return 0; /* indicate successful termination */ 19 20 } /* 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 /* Exercise 3.23 Solution */ 2 #include 3 4 int main() 5{ 6 int i = 0; /* initialize i */ 7 8 /* loop while i is less than 11 */ 9 while ( ++i < 11 ) { 10 printf( "%d ", i ); 11 } /* end while */ 12 13 return 0; /* indicate successful termination */ 14 15 } /* end main */ 1 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. Chapter 3 Structured Program Development in C: Solutions 31 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 /* Exercise 3.24 Solution */ 2 #include 3 4 int main() 5{ 6 int counter; /* counter for 10 repetitions */ 7 int number; /* current number input */ 8 int largest; /* largest number found so far */ 9 10 /* get first number */ 11 printf( "Enter the first number: " ); 12 scanf( "%d", &largest ); 13 counter = 2; 14 15 /* loop 9 more times */ 16 while ( counter <= 10 ) { 17 printf( "Enter next number: " ); /* get next number */ 18 scanf( "%d", &number ); 19 20 /* if current number input is greater than largest number, 21 update largest */ 22 if ( number > largest ) { 23 largest = number; 24 } /* end if */ 25 26 counter++; 27 } /* end while */ 28 29 printf( "Largest is %d\n", largest ); /* display largest number */ 30 31 return 0; /* indicate successful termination */ 32 33 } /* 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 Write a program that utilizes looping to print the following table of values: N 10 * N 100 * N 1000 * N 1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000 6 60 600 6000 7 70 700 7000 8 80 800 8000 9 90 900 9000 10 100 1000 10000 The tab character, \t, may be used in the printf statement to separate the columns with tabs. ANS: 1 /* Exercise 3.25 Solution */ 2 #include 3 4 int main() 5{ 6 int n = 0; /* counter */ 7 8 /* display table headers */ 9 printf( "\tN\t\t10 * N\t\t100 * N\t\t1000 * N\n\n" ); 10 11 /* loop 10 times */ 12 while ( ++n <= 10 ) { 13 14 /* calculate and display table values */ 15 printf( "\t%-2d\t\t%-5d\t\t%-5d\t\t%-6d\n", 16 n, 10 * n, 100 * n, 1000 * n ); 17 } /* end while */ 18 19 return 0; /* indicate successful termination */ 20 21 } /* end main */ 3.26 Write a program that utilizes looping to produce the following table of values: A A+2 A+4 A+6 3 5 7 9 6 8 10 12 9 11 13 15 12 14 16 18 15 17 19 21 Chapter 3 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 33 ANS: 1 /* Exercise 3.26 Solution */ 2 #include 3 4 int main() 5{ 6 int a = 3; /* counter */ 7 8 /* display table headers */ 9 printf( "A\tA+2\tA+4\tA+6\n\n" ); 10 11 /* loop 5 times */ 12 while ( a <= 15 ) { 13 14 /* calculate and display table values */ 15 printf( "%d\t%d\t%d\t%d\n", a, a + 2, a + 4, a + 6 ); 16 a += 3; 17 } /* end while */ 18 19 return 0; /* indicate successful termination */ 20 21 } /* 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 /* Exercise 3.27 Solution */ 2 #include 3 4 int main() 5 6{ 7 int counter; /* counter for 10 repetitions */ 8 int number; /* current number input */ 9 int largest; /* largest number found */ 10 int secondLargest = 0; /* second largest number found */ 11 12 printf( "Enter the first number: " ); /* get first number */ 13 scanf( "%d", &largest ); 14 counter = 2; 15 16 /* loop 9 more times */ 17 while ( counter <= 10 ) { 18 printf( "Enter next number: " ); /* prompt for next number */ 19 scanf( "%d", &number ); 20 21 /* if current number is greater than largest */ 22 if ( number > largest ) { 23 24 /* update second largest with previous largest */ 25 secondLargest = largest; 26 27 /* update largest with current number */ 28 largest = number; 29 } /* end if */ 30 else { 31 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 34 Structured Program Development in C: Solutions Chapter 3 32 /* if number is between secondLargest and largest */ 33 if ( number > secondLargest ) { 34 secondLargest = number; 35 } /* end if */ 36 37 } /* end else */ 38 39 ++counter; 40 } /* end while */ 41 42 /* display largest two numbers */ 43 printf( "Largest is %d\n", largest ); 44 printf( "Second largest is %d\n", secondLargest ); 45 46 return 0; /* indicate successful termination */ 47 48 } /* 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 /* Exercise 3.28 Solution */ 2 #include 3 4 int main() 5{ 6 int passes = 0; /* number of passes */ 7 int failures = 0; /* number of failures */ 8 int student = 1; /* student counter */ 9 int result; /* one exam result */ 10 11 /* process 10 students using counter-controlled loop */ 12 while ( student <= 10 ) { 13 14 /* prompt user for input and obtain value from user */ 15 printf( "Enter result ( 1=pass, 2=fail ): " ); 16 scanf( "%d", &result ); 17 18 /* loop until valid input */ 19 while ( result != 1 && result != 2 ) { 20 printf( "Invalid result\nEnter result ( 1=pass, 2=fail ): " ); 21 scanf( "%d", &result ); 22 } /* end inner while */ 23 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 35 24 /* if result 1, increment passes */ 25 if ( result == 1 ) { 26 ++passes; 27 } /* end if */ 28 else { /* if result is not 1, increment failures */ 29 ++failures; 30 } /* end else */ 31 32 ++student; 33 } /* end while */ 34 35 printf( "Passed %d\nFailed %d\n", passes, failures ); 36 37 /* if more than eight students passed, print "raise tuition" */ 38 if ( passes >= 8 ) { 39 printf( "Raise tuition\n" ); 40 } /* end if */ 41 42 return 0; /* indicate successful termination */ 43 44 } /* end main */ Enter result ( 1=pass, 2=fail ): 1 Enter result ( 1=pass, 2=fail ): 2 Enter result ( 1=pass, 2=fail ): 3 Invalid result Enter result ( 1=pass, 2=fail ): 4 Invalid result Enter result ( 1=pass, 2=fail ): 2 Enter result ( 1=pass, 2=fail ): 2 Enter result ( 1=pass, 2=fail ): 2 Enter result ( 1=pass, 2=fail ): 1 Enter result ( 1=pass, 2=fail ): 1 Enter result ( 1=pass, 2=fail ): 1 Enter result ( 1=pass, 2=fail ): 1 Enter result ( 1=pass, 2=fail ): 1 Passed 6 Failed 4 3.29 What does the following program print? 1 #include 2 3 /* function main begins program execution */ 4 int main() 5{ 6 int count = 1; /* initialize count */ 7 8 while ( count <= 10 ) { /* loop 10 times */ 9 10 /* output line of text */ 11 printf( "%s\n", count % 2 ? "****" : "++++++++" ); 12 count++; /* increment count */ 13 } /* end while */ 14 15 return 0; /* indicate program ended successfully */ 16 17 } /* 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 What does the following program print? 1 #include 2 3 /* function main begins program execution */ 4 int main() 5{ 6 int row = 10; /* initialize row */ 7 int column; /* define column */ 8 9 while ( row >= 1 ) { /* loop until row < 1 */ 10 column = 1; /* set column to 1 as iteration begins */ 11 12 while ( column <= 10 ) { /* loop 10 times */ 13 printf( "%s", row % 2 ? "<": ">" ); /* output */ 14 column++; /* increment column */ 15 } /* end inner while */ 16 17 row--; /* decrement row */ 18 printf( "\n" ); /* begin new output line */ 19 } /* end outer while */ 20 21 return 0; /* indicate program ended successfully */ 22 23 } /* end function main */ ANS: >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< Chapter 3 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 37 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. Chapter 3 Structured Program Development in C: Solutions 39 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 /* Exercise 3.33 Solution */ 2 #include 3 4 int main() 5{ 6 int side; /* side counter */ 7 int temp; /* temporary integer */ 8 int asterisk; /* asterisk counter */ 9 10 printf( "Enter the square side: " ); /* get size of square */ 11 scanf( "%d", &side ); 12 13 temp = side; 14 15 /* loop through rows of square */ 16 while ( side-- > 0 ) { 17 asterisk = temp; 18 19 /* loop through columns of square */ 20 while ( asterisk-- > 0 ) { 21 printf( "*" ); 22 } /* end inner while */ 23 24 putchar( '\n' ); 25 } /* end outer while */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* 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 /* Exercise 3.34 Solution */ 2 #include 3 4 int main() 5{ 6 int side; /* side counter */ 7 int rowPosition; /* row counter */ 8 int size; /* length of side */ 9 10 printf( "Enter the square side: " ); /* prompt for side length */ 11 scanf( "%d", &side ); 12 13 size = side; /* set size counter to length of side */ 14 15 /* loop side number of times */ 16 while ( side > 0 ) { 17 rowPosition = size; /* set row counter to length of size */ 18 19 /* loop rowPosition number of times */ 20 while ( rowPosition > 0 ) { 21 22 /* if side or row counter is 1 or size print an '*' */ 23 if ( size == side ) { 24 printf( "*" ); 25 } /* end if */ 26 else if ( side == 1 ) { 27 printf( "*" ); 28 } /* end else if */ 29 else if ( rowPosition == 1 ) { 30 printf( "*" ); 31 } /* end else if */ 32 else if ( rowPosition == size ) { 33 printf( "*" ); 34 } /* end else if */ 35 else { /* otherwise, print a space */ 36 printf( " " ); 37 } /* end else */ 38 39 --rowPosition; /* decrement row counter */ 40 } /* end inner while */ 41 42 printf( "\n" ); /* new line for next row */ 43 --side; /* decrement side counter */ 44 } /* end outer while */ 45 46 return 0; /* indicate successful termination */ 47 48 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 41 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 /* Exercise 3.35 Solution */ 2 #include 3 4 int main() 5{ 6 int number; /* input number */ 7 int temp1; /* first temporary integer */ 8 int temp2; /* second temporary integer */ 9 int firstDigit; /* first digit of input */ 10 int secondDigit; /* second digit of input */ 11 int fourthDigit; /* fourth digit of input */ 12 int fifthDigit; /* fifth digit of input */ 13 14 printf( "Enter a five-digit number: " ); /* get number */ 15 scanf( "%d", &number ); 16 17 temp1 = number; 18 19 /* determine first digit by integer division by 10000 */ 20 firstDigit = temp1 / 10000; 21 temp2 = temp1 % 10000; 22 23 /* determine second digit by integer division by 1000 */ 24 secondDigit = temp2 / 1000; 25 temp1 = temp2 % 1000; 26 27 temp2 = temp1 % 100; 28 29 /* determine fourth digit by integer division by 10 */ 30 fourthDigit = temp2 / 10; 31 temp1 = temp2 % 10; 32 33 fifthDigit = temp1; 34 35 /* if first and fifth digits are equal */ 36 if ( firstDigit == fifthDigit ) { 37 38 /* if second and fourth digits are equal */ 39 if ( secondDigit == fourthDigit ) { 40 41 /* number is a palindrome */ 42 printf( "%d is a palindrome\n", number ); 43 } /* end if */ 44 else { /* number is not a palindrome */ 45 printf( "%d is not a palindrome\n", number ); 46 } /* end else */ 47 48 } /* end if */ 49 else { /* number is not a palindrome */ 50 printf( "%d is not a palindrome\n", number ); 51 } /* end else */ 52 53 return 0; /* indicate successful termination */ 54 55 } /* 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 /* Exercise 3.36 Solution */ 2 #include 3 4 int main() 5{ 6 int binary; /* current value of binary number */ 7 int number; /* input binary number */ 8 int decimal = 0; /* current value of decimal number */ 9 int highBit = 16; /* value of highest bit */ 10 int factor = 10000; /* factor of 10 to pick off digits */ 11 12 /* prompt for binary input */ 13 printf( "Enter a binary number ( 5 digits maximum ): " ); 14 scanf( "%d", &binary ); 15 16 number = binary; /* save in number for final display */ 17 18 /* loop 5 times using powers of 2 */ 19 while ( highBit >= 1 ) { 20 21 /* update decimal value with decimal value corresponding 22 to current highest binary bit */ 23 decimal += binary / factor * highBit; 24 25 /* reduce high bit by factor of 2, i.e., 26 move one bit to the right */ 27 highBit /= 2; 28 29 /* reduce binary number to eliminate current highest bit */ 30 binary %= factor; 31 32 /* reduce factor by power of 10, i.e., 33 move one bit to the right */ 34 factor /= 10; 35 } /* end while */ 36 37 /* display decimal value */ 38 printf( "The decimal equivalent of %d is %d\n", number, decimal ); 39 40 return 0; /* indicate successful termination */ 41 42 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 43 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 /* Exercise 3.37 Solution */ 2 #include 3 4 int main() 5{ 6 long int count = 1; /* counter */ 7 8 /* loop to 300,000,000 */ 9 while( count <= 300000000 ) { 10 11 if ( count % 100000000 == 0 ) { 12 printf( "Multiple is %d\n", count / 100000000 ); 13 } /* end if */ 14 15 ++count; /* increment count */ 16 } /* end while */ 17 18 return 0; /* indicate successful termination */ 19 20 } /* 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 /* Exercise 3.38 Solution */ 2 #include 3 4 int main() 5{ 6 int count = 0; /* counter */ 7 8 /* loop to 100 */ 9 while( ++count <= 100 ) 10 11 /* print a new line after every 10th asterisk */ 12 count % 10 == 0 ? printf( "*\n" ) : printf( "*" ); 13 14 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 Chapter 3 15 16 } /* end main */ ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** 3.39 Write a program that reads an integer and determines and prints how many digits in the integer are 7s. ANS: 1 /* Exercise 3.39 Solution */ 2 #include 3 4 int main() 5{ 6 int number; /* user input */ 7 int numCopy; /* copy of number */ 8 int factor = 10000; /* set factor to pick off digits */ 9 int digit; /* individual digit of number */ 10 int sevens = 0; /* sevens counter */ 11 12 printf( "Enter a 5-digit number: " ); /* get number from user */ 13 scanf( "%d", &number ); 14 15 numCopy = number; 16 17 /* loop through each of the 5 digits */ 18 while ( factor >= 1 ) { 19 digit = numCopy / factor; /* pick off next digit */ 20 21 if ( digit == 7 ) { /* if digit equals 7, increment sevens */ 22 ++sevens; 23 } /* end if */ 24 25 numCopy %= factor; 26 factor /= 10; 27 } /* end while */ 28 29 /* output number of sevens */ 30 printf( "The number %ld has %d seven(s) in it\n", number, sevens ); 31 32 return 0; /* indicate successful termination */ 33 34 } /* 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 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 /* Exercise 3.40 Solution */ 2 #include 3 4 int main() 5{ 6 int side = 8; /* side counter */ 7 int row; /* row counter */ 8 int mod; /* remainder */ 9 10 /* loop 8 times */ 11 while ( side >= 1 ) { 12 row = 8; /* reset row counter */ 13 mod = side % 2; 14 15 /* loop 8 times */ 16 while ( row >= 1 ) { 17 18 /* if odd row, begin with a space */ 19 if ( mod != 0 ) { 20 printf( " " ); 21 mod = 0; 22 } /* end if */ 23 24 printf( "* " ); 25 --row; 26 } /* end while */ 27 28 printf( "\n" ); /* go to next line */ 29 --side; 30 } /* end while */ 31 32 return 0; /* indicate successful termination */ 33 34 } /* 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 /* Exercise 3.41 Solution */ 2 #include 3 4 int main() 5{ 6 int multiple = 1; /* counter */ 7 8 /* infinite loop */ 9 while ( multiple > 0 ) { 10 11 /* calculate the next power of two */ 12 multiple *= 2; 13 printf( "%d\n", multiple ); 14 } /* end while */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* 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. Chapter 3 Structured Program Development in C: Solutions 47 ANS: 1 /* Exercise 3.42 Solution */ 2 #include 3 4 int main() 5{ 6 float radius; /* input radius */ 7 float pi = 3.14159; /* value for pi */ 8 9 printf( "Enter the radius: "); /* get radius value */ 10 scanf( "%f", &radius ); 11 12 /* compute and display diameter */ 13 printf( "The diameter is %.2f\n", radius * 2 ); 14 15 /* compute and display circumference */ 16 printf( "The circumference is %.2f\n", 2 * pi * radius ); 17 18 /* compute and display area */ 19 printf( "The area is %.2f\n", pi * radius * radius ); 20 21 return 0; /* indicate successful termination */ 22 23 } /* 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 /* Exercise 3.44 Solution */ 2 #include 3 4 int main() 5{ 6 double a; /* first number */ 7 double b; /* second number */ 8 double c; /* third number */ 9 10 /* input 3 numbers */ 11 printf( "Enter three doubleing point numbers: " ); 12 scanf( "%lf%lf%lf", &a, &b, &c); 13 14 /* use Pythagorean Theorem */ 15 if ( c * c == a * a + b * b ) { 16 printf( "The three numbers could be sides of a triangle\n" ); 17 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 48 Structured Program Development in C: Solutions Chapter 3 18 else { 19 printf( "The three numbers probably"); 20 printf( " are not the sides of a triangle\n" ); 21 } /* end if */ 22 23 return 0; /* indicate successful termination */ 24 25 } /* 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 Write a program that reads three nonzero integers and determines and prints if they could be the sides of a right triangle. ANS: 1 /* Exercise 3.45 Solution */ 2 #include 3 4 int main() 5{ 6 int a; /* first number */ 7 int b; /* second number */ 8 int c; /* third number */ 9 10 /* input three numbers */ 11 printf( "Enter three integers: "); 12 scanf( "%d%d%d", &a, &b, &c ); 13 14 /* use Pythagorean Theorem */ 15 if ( c * c == a * a + b * b ) { 16 printf( "The three integers are the sides of"); 17 printf( " a right triangle\n" ); 18 } /* end if */ 19 else { 20 printf( "The three integers are not the sides"); 21 printf( " of a right triangle\n" ); 22 } /* end else */ 23 24 return 0; /* indicate successful termination */ 25 26 } /* 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. Chapter 3 Structured Program Development in C: Solutions 49 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 /* Exercise 3.46 Part A solution */ 2 #include 3 4 int main() 5{ 6 int first; /* first digit replacement */ 7 int second; /* second digit replacement */ 8 int third; /* third digit replacement */ 9 int fourth; /* fourth digit replacement */ 10 int digit; /* input number */ 11 int temp1; /* temporarily hold digit */ 12 int temp2; /* temporarily hold digit */ 13 int encryptedNumber; /* resulting encrypted number */ 14 15 /* prompt for input */ 16 printf( "Enter a four digit number to be encrypted: " ); 17 scanf( "%d", &digit ); 18 19 temp1 = digit; 20 21 /* retrieve each digit and replace with 22 (sum of digit and 7) mod 10 */ 23 first = ( temp1 / 1000 + 7 ) % 10; 24 temp2 = temp1 % 1000; 25 26 second = ( temp2 / 100 + 7 ) % 10; 27 temp1 = temp2 % 100; 28 29 third = ( temp1 / 10 + 7 ) % 10; 30 temp2 = temp1 % 10; 31 32 fourth = ( temp2 + 7 ) % 10; 33 34 /* swap first and third */ 35 temp1 = first; 36 first = third * 1000; /* multiply by 1000 for 1st digit component */ 37 third = temp1 * 10; /* multiply by 10 for 3rd digit component */ 38 39 /* swap second and fourth */ 40 temp1 = second; 41 second = fourth * 100; /* multiply by 100 for 2nd digit component */ 42 fourth = temp1 * 1; 43 44 /* add components to obtain encrypted number */ 45 encryptedNumber = first + second + third + fourth; 46 47 /* display encrypted number */ 48 printf( "Encrypted number is %d\n", encryptedNumber ); 49 50 return 0; /* indicate successful termination */ 51 52 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 50 Structured Program Development in C: Solutions Chapter 3 Enter a four digit number to be encrypted: 5678 Encrypted number is 4523 1 /* Exercise 3.46 Part B Solution */ 2 #include 3 4 int main() 5{ 6 int first; /* first decrypted digit */ 7 int second; /* second decrypted digit */ 8 int third; /* third decrypted digit */ 9 int fourth; /* fourth decrypted digit */ 10 int decrypted; /* decrypted number */ 11 int temp1; /* temporarily hold digit */ 12 int temp2; /* temporarily hold digit */ 13 int encryptedNumber; /* input number */ 14 15 /* prompt for input */ 16 printf( "Enter a four digit encrypted number: " ); 17 scanf( "%d", &encryptedNumber ); 18 19 temp1 = encryptedNumber; 20 21 /* retrieve each digit and decrypt by 22 (sum of digit and 3) mod 10 */ 23 first = ( temp1 / 1000 ); 24 temp2 = temp1 % 1000; 25 26 second = ( temp2 / 100 ); 27 temp1 = temp2 % 100; 28 29 third = ( temp1 / 10 ); 30 temp2 = temp1 % 10; 31 32 fourth = temp2; 33 34 temp1 = ( first + 3 ) % 10; 35 first = ( third + 3 ) % 10; 36 third = temp1; 37 38 temp1 = ( second + 3 ) % 10; 39 second = ( fourth + 3 ) % 10; 40 fourth = temp1; 41 42 /* add components to obtain decrypted number */ 43 decrypted = ( first * 1000 ) + ( second * 100 ) + 44 ( third * 10 ) + fourth; 45 46 /* display decrypted number */ 47 printf( "Decrypted number is %d\n", decrypted ); 48 49 return 0; /* indicate successful termination */ 50 51 } /* 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 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 /* Exercise 3.47 Part A Solution */ 2 #include 3 4 int main() 5{ 6 int n; /* current multiplication factor */ 7 int number = -1; /* input number */ 8 unsigned factorial = 1; /* resulting factorial */ 9 10 /* loop until valid input */ 11 do { 12 printf( "Enter a positive integer: " ); 13 scanf( "%d", &number ); 14 } while ( number < 0 ); /* end do...while */ 15 16 n = number; 17 18 /* compute factorial */ 19 while( n >= 0 ) { 20 21 if ( n == 0 ) { 22 factorial *= 1; 23 } /* end if */ 24 else { 25 factorial *= n; 26 } /* end else */ 27 28 --n; 29 } /* end while */ 30 31 /* display factorial */ 32 printf( "%d! is %u\n", number, factorial ); 33 34 return 0; /* indicate successful termination */ 35 36 } /* 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: ANS: e = 1 + --1-1! + -1--2! + -1--3! + … 1 /* Exercise 3.47 Part B Solution */ 2 #include 3 4 int main() 5{ 6 int n = 0; /* loop counter for accuracy */ 7 int fact = 1; /* current n factorial */ 8 int accuracy = 10; /* degree of accuracy */ 9 double e = 0; /* current estimated value of e */ 10 11 /* loop until degree of accuracy */ 12 while( n <= accuracy ) { 13 14 if ( n == 0 ) { 15 fact *= 1; 16 } /* end if */ 17 else { 18 fact *= n; 19 } /* end else */ 20 21 e += 1.0 / fact; 22 ++n; 23 } /* end while */ 24 25 printf( "e is %f\n", e ); /* display estimated value */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* end main */ e is 2.718282 c) Write a program that computes the value of ex by using the formula ex = 1 + --x-- + -x--2- + x---3- + … 1! 2! 3! ANS: 1 /* Exercise 3.47 Part C Solution */ 2 #include 3 4 int main() 5{ 6 int n = 0; /* counter */ 7 int accuracy = 15; /* degree of accuracy */ 8 int x = 3; /* exponent */ 9 int times = 0; /* counter */ 10 int count; /* copy of n */ 11 double e = 1.0; /* e raised to the x power */ 12 double exp = 0.0; /* x raised to the n power */ 13 double fact = 1.0; /* n factorial */ 14 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 Structured Program Development in C: Solutions 53 15 /* loop while less than degree of accuracy */ 16 while( n <= accuracy ) { 17 count = n; 18 19 /* update n! */ 20 if ( n == 0 ) { 21 fact *= 1.0; 22 } /* end if */ 23 else { 24 fact *= n; 25 } /* end else */ 26 27 while ( times < count ) { 28 29 /* calculate x raised to the n power */ 30 if ( times == 0 ) { 31 exp = 1.0; 32 exp *= x; 33 } /* end if */ 34 else { 35 exp *= x; 36 } /* end else */ 37 38 ++times; 39 } /* end while */ 40 41 e += exp / fact; /* update e raised to the x power */ 42 ++n; 43 } /* end while */ 44 45 /* display result */ 46 printf( "e raised to the %d power is %f\n", x, e ); 47 48 return 0; /* indicate successful termination */ 49 50 } /* 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 Chapter 3 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. Chapter 4 C Program Control: Solutions 57 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 What does the following program do? 1 #include 2 3 /* function main begins program execution */ 4 int main() 5{ 6 int x; 7 int y; 8 int i; 9 int j; 10 11 /* prompt user for input */ 12 printf( "Enter two integers in the range 1-20: " ); 13 scanf( "%d%d", &x, &y ); /* read values for x and y */ 14 15 for ( i = 1; i <= y; i++ ) { /* count from 1 to y */ 16 17 for ( j = 1; j <= x; j++ ) { /* count from 1 to x */ 18 printf( "@" ); /* output @ */ 19 } /* end inner for */ 20 21 printf( "\n" ); /* begin new line */ 22 } /* end outer for */ 23 24 return 0; /* indicate program ended successfully */ 25 26 } /* 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 /* Exercise 4.9 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int sum = 0; /* current sum */ 7 int number; /* number of values */ 8 int value; /* current value */ 9 int i; /* counter */ 10 11 /* display prompt */ 12 printf( "Enter the number of values" 13 " to be processed: " ); 14 scanf( "%d", &number ); /* input number of values */ 15 16 /* loop number times */ 17 for ( i = 1; i <= number; i++ ) { 18 printf( "Enter a value: " ); 19 scanf( "%d", &value ); 20 sum += value; /* add to sum */ 21 } /* end for */ 22 23 /* display sum */ 24 printf( "Sum of the %d values is %d\n", number, sum ); 25 26 return 0; /* indicate successful termination */ 27 28 } /* 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 /* Exercise 4.10 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int value; /* current value */ 7 int count = 0; /* number of values */ 8 int total = 0; /* sum of integers */ 9 10 /* display prompt */ 11 printf( "Enter an integer ( 9999 to end ): " ); 12 scanf( "%d", &value ); 13 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 59 14 /* loop while sentinel value not read from user */ 15 while ( value != 9999 ) { 16 total += value; /* update total */ 17 ++count; 18 19 /* get next value */ 20 printf( "Enter next integer ( 9999 to end ): " ); 21 scanf( "%d", &value ); 22 } /* end while */ 23 24 /* show average if more than 0 values entered */ 25 if ( count != 0 ) { 26 printf( "\nThe average is: %.2f\n", ( double ) total / count ); 27 } /* end if */ 28 else { 29 printf( "\nNo values were entered.\n" ); 30 } /* end else */ 31 32 return 0; /* indicate successful termination */ 33 34 } /* end main */ Enter an integer ( 9999 to end ): 1 Enter next integer ( 9999 to end ): 2 Enter next integer ( 9999 to end ): 3 Enter next integer ( 9999 to end ): 4 Enter next integer ( 9999 to end ): 5 Enter next integer ( 9999 to end ): 6 Enter next integer ( 9999 to end ): 9999 The average is: 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 /* Exercise 4.11 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int number; /* number of integers */ 7 int value; /* value input by user */ 8 int smallest; /* smallest number */ 9 int i; /* counter */ 10 11 /* prompt user for number of integers */ 12 printf( "Enter the number of integers to be processed: " ); 13 scanf( "%d", &number ); 14 15 /* prompt user for an integer */ 16 printf( "Enter an integer: " ); 17 scanf( "%d", &smallest ); 18 19 /* loop until user has entered all integers */ 20 for ( i = 2; i <= number; i++ ) { 21 printf( "Enter next integer: " ); /* get next integer */ 22 scanf( "%d", &value ); 23 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 60 C Program Control: Solutions Chapter 4 24 /* if value is smaller than smallest */ 25 if ( value < smallest ) { 26 smallest = value; 27 } /* end if */ 28 29 } /* end for */ 30 31 printf( "\nThe smallest integer is: %d\n", smallest ); 32 33 return 0; /* indicate successful termination */ 34 35 } /* end main */ Enter the number of integers to be processed: 5 Enter an integer: 372 Enter next integer: 920 Enter next integer: 73 Enter next integer: 8 Enter next integer: 3433 The smallest integer is: 8 4.12 Write a program that calculates and prints the sum of the even integers from 2 to 30. ANS: 1 /* Exercise 4.12 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int i; /* counter */ 7 int sum = 0; /* current sum of integers */ 8 9 /* loop through even integers up to 30 */ 10 for ( i = 2; i <= 30; i += 2 ) { 11 sum += i; /* add i to sum */ 12 } /* end for */ 13 14 printf( "Sum of the even integers from 2 to 30 is: %d\n", sum ); 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ Sum of the even integers from 2 to 30 is: 240 4.13 Write a program that calculates and prints the product of the odd integers from 1 to 15. ANS: 1 /* Exercise 4.13 Solution */ 2 #include 3 4 int main( void ) 5{ 6 long i; /* counter */ 7 long product = 1; /* current product */ 8 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 61 9 /* loop through odd integers up to 15 */ 10 for ( i = 3; i <= 15; i += 2 ) { 11 product *= i; /* update product */ 12 } /* end for */ 13 14 printf( "Product of the odd integers from 1 to 15 is: %ld\n", product ); 15 16 return 0; /* indicate successful termination */ 17 18 } /* 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 /* Exercise 4.14 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int i; /* outer counter */ 7 int j; /* inner counter */ 8 int factorial; /* current factorial value */ 9 10 printf( "X\tFactorial of X\n" ); /* display table headers */ 11 12 /* compute the factorial for 1 to 5 */ 13 for ( i = 1; i <= 5; i++ ) { 14 factorial = 1; 15 16 /* calculate factorial of current number */ 17 for ( j = 1; j <= i; j++ ) { 18 factorial *= j; 19 } /* end inner for */ 20 21 printf( "%d\t%d\n", i, factorial ); 22 } /* end outer for */ 23 24 return 0; /* indicate successful termination */ 25 26 } /* end main */ X Factorial of X 1 1 2 2 3 6 4 24 5 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 ANS: 1 /* Exercise 4.15 Solution */ 2 #include 3 #include 4 5 int main( void ) 6{ 7 int year; /* year counter */ 8 int rate; /* interest rate */ 9 double amount; /* amount on deposit */ 10 double principal = 1000.0; /* starting principal */ 11 12 /* loop through interest rates 5% to 10% */ 13 for ( rate = 5; rate <= 10; rate++ ) { 14 15 /* display table headers */ 16 printf( "Interest Rate: %f\n", rate / 100.0 ); 17 printf( "%s%21s\n", "Year","Amount on deposit" ); 18 19 /* calculate amount on deposit for each of ten years */ 20 for ( year = 1; year <= 10; year++ ) { 21 22 /* calculate new amount for specified year */ 23 amount = principal * pow( 1 + ( rate / 100.0 ), year ); 24 25 /* output one table row */ 26 printf( "%4d%21.2f\n", year, amount ); 27 } /* end for */ 28 29 printf( "\n" ); 30 } /* end for */ 31 32 return 0; /* indicate successful termination */ 33 34 } /* end main */ Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 63 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 /* Exercise 4.16 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int row; /* row counter */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 64 C Program Control: Solutions Chapter 4 7 int col; /* column counter */ 8 int space; /* spaces counter */ 9 10 /* Pattern A, loop 10 times for rows */ 11 for ( row = 1; row <= 10; row++ ) { 12 13 /* print row asterisks */ 14 for ( col = 1; col <= row; col++ ) { 15 printf( "*" ); 16 } /* end for */ 17 18 printf( "\n" ); 19 } /* end for */ 20 21 printf( "\n" ); 22 23 /* Pattern B, loop 10 times for rows 24 row counts down to correspond to number of asterisks */ 25 for ( row = 10; row >= 1; row-- ) { 26 27 /* print row asterisks */ 28 for ( col = 1; col <= row; col++ ) { 29 printf( "*" ); 30 } /* end for */ 31 32 printf( "\n" ); 33 } /* end for */ 34 35 printf( "\n" ); 36 37 /* Pattern C, loop 10 times for rows 38 row counts down to correspond to number of asterisks */ 39 for ( row = 10; row >= 1; row-- ) { 40 41 /* print (10 - row) number of preceding spaces */ 42 for ( space = 1; space <= 10 - row; space++ ) { 43 printf( " " ); 44 } /* end for */ 45 46 /* print row asterisks */ 47 for ( col = 1; col <= row; col++ ) { 48 printf( "*" ); 49 } /* end for */ 50 51 printf( "\n" ); 52 } /* end for */ 53 54 printf( "\n" ); 55 56 /* Pattern D, loop 10 times for rows */ 57 for ( row = 1; row <= 10; row++ ) { 58 59 /* print (10 - row) number of preceding spaces */ 60 for ( space = 1; space <= 10 - row; space++ ) { 61 printf( " " ); 62 } /* end for */ 63 64 /* print row asterisks */ 65 for ( col = 1; col <= row; col++ ) { 66 printf( "*" ); 67 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 65 68 69 printf( "\n" ); 70 } /* end for */ 71 72 printf( "\n" ); 73 74 return 0; /* indicate successful termination */ 75 76 } /* 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 /* Exercise 4.17 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int account; /* current account number */ 7 int i; /* counter */ 8 double limit; /* current credit limit */ 9 double balance; /* current balance */ 10 double newLimit; /* new credit limit */ 11 12 /* loop three times */ 13 for ( i = 1; i <= 3; i++ ) { 14 15 /* get account number, credit limit and balance */ 16 printf( "\nEnter account, limit, balance: " ); 17 scanf( "%d%lf%lf", &account, &limit, &balance ); 18 19 newLimit = limit / 2.0; /* calculate new limit */ 20 printf( "New credit limit for account %d is %.2f\n", account, newLimit ); 21 22 /* if balance is greater than new credit limit */ 23 if ( balance > newLimit ) { 24 printf( "Limit exceeded for account %d\n", account ); 25 } /* end if */ 26 27 } /* end for */ 28 29 return 0; /* indicate successful termination */ 30 31 } /* 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 /* Exercise 4.18 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int i; /* outer counter */ 7 int j; /* inner counter */ 8 int number; /* current number */ 9 10 printf( "Enter 5 numbers between 1 and 30: " ); 11 12 /* loop 5 times */ 13 for ( i = 1; i <= 5; i++ ) { 14 scanf( "%d", &number ); 15 16 /* print asterisks corresponding to current input */ 17 for ( j = 1; j <= number; j++ ) { 18 printf( "*" ); 19 } /* end for */ 20 21 printf( "\n" ); 22 } /* end for */ 23 24 return 0; /* indicate successful termination */ 25 26 } /* 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. Chapter 4 C Program Control: Solutions 67 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 /* Exercise 4.19 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int product; /* current product number */ 7 int quantity; /* quantity of current product sold */ 8 double total = 0.0; /* current total retail value */ 9 10 /* prompt for input */ 11 printf( "Enter pairs of item numbers and quantities.\n"); 12 printf( "Enter -1 for the item number to end input.\n" ); 13 scanf( "%d", &product ); 14 15 /* loop while sentinel value not read from user */ 16 while ( product != -1 ) { 17 scanf( "%d", &quantity ); 18 19 /* determine product number and corresponding retail price */ 20 switch ( product ) { 21 22 case 1: 23 total += quantity * 2.98; /* update total */ 24 break; 25 26 case 2: 27 total += quantity * 4.50; /* update total */ 28 break; 29 30 case 3: 31 total += quantity * 9.98; /* update total */ 32 break; 33 34 case 4: 35 total += quantity * 4.49; /* update total */ 36 break; 37 38 case 5: 39 total += quantity * 6.87; /* update total */ 40 break; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 68 C Program Control: Solutions 41 42 default: 43 printf( "Invalid product code: %d\n", product ); 44 printf( " Quantity: %d\n", quantity ); 45 } /* end switch */ 46 47 scanf( "%d", &product ); /* get next input */ 48 } /* end while */ 49 50 /* display total retail value */ 51 printf( "The total retail value was: %.2f\n", total ); 52 53 return 0; /* indicate successful termination */ 54 55 } /* end main */ Enter pairs of item numbers and quantities. Enter -1 for the item number to end input. 11 21 31 41 51 61 Invalid product code: 6 Quantity: 1 11 -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 && Condition2 0 0 0 0 nonzero 0 nonzero 0 0 nonzero nonzero 1 Condition1 0 0 nonzero nonzero Condition2 0 nonzero 0 nonzero Condition1 || Condition2 0 1 1 1 Condition1 0 nonzero !Condition1 1 0 Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 69 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 /* Exercise 4.21 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int counter = 1; /* initialize counter */ 7 8 /* leave first statement empty */ 9 for ( ; counter <= 10; counter++ ) { 10 printf( "%d\n", counter ); 11 } /* end for */ 12 13 return 0; /* indicate successful termination */ 14 15 } /* end main */ 1 2 3 4 5 6 7 8 9 10 4.22 Modify the program of Fig. 4.7 so that it calculates the average grade for the class. ANS: 1 /* Exercise 4.22 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int grade; /* current grade */ 7 int aCount = 0; /* total a grades */ 8 int bCount = 0; /* total b grades */ 9 int cCount = 0; /* total c grades */ 10 int dCount = 0; /* total d grades */ 11 int fCount = 0; /* total f grades */ 12 double averageGrade; /* average grade for class */ 13 14 /* prompt user for grades */ 15 printf( "Enter the letter grades.\n"); 16 printf( "Enter the EOF character to end input.\n" ); 17 18 /* loop while not end of file */ 19 while ( ( grade = getchar() ) != EOF ) { 20 21 /* determine which grade was input */ 22 switch ( grade ) { 23 24 case 'A': /* grade was uppercase A */ 25 case 'a': /* grade was lowercase a */ 26 ++aCount; /* update grade A counter */ 27 break; /* exit switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 70 C Program Control: Solutions Chapter 4 28 29 case 'B': /* grade was uppercase B */ 30 case 'b': /* grade was lowercase b */ 31 ++bCount; /* update grade B counter */ 32 break; /* exit switch */ 33 34 case 'C': /* grade was uppercase C */ 35 case 'c': /* grade was lowercase c */ 36 ++cCount; /* update grade C counter */ 37 break; /* exit switch */ 38 39 case 'D': /* grade was uppercase C */ 40 case 'd': /* grade was lowercase c */ 41 ++dCount; /* update grade C counter */ 42 break; /* exit switch */ 43 44 case 'F': /* grade was uppercase C */ 45 case 'f': /* grade was lowercase c */ 46 ++fCount; /* update grade C counter */ 47 break; /* exit switch */ 48 49 case '\n': /* ignore newlines, */ 50 case '\t': /* tabs, */ 51 case ' ': /* and spaces in input */ 52 break; /* exit switch */ 53 54 default: /* catch all other characters */ 55 printf( "Incorrect letter grade entered." ); 56 printf( " Enter a new grade.\n" ); 57 break; /* optional, will exit switch anyway */ 58 } /* end switch */ 59 60 } /* end while */ 61 62 /* output totals for each grade */ 63 printf( "\nThe totals for each letter grade are:\n" ); 64 printf( "A: %d\n", aCount ); 65 printf( "B: %d\n", bCount ); 66 printf( "C: %d\n", cCount ); 67 printf( "D: %d\n", dCount ); 68 printf( "F: %d\n", fCount ); 69 70 /* calculate average grade */ 71 averageGrade = 72 ( 4 * aCount + 3 * bCount + 2 * cCount + dCount ) / 73 ( aCount + bCount + cCount + dCount + fCount ); 74 75 /* output appropriate message for average grade */ 76 if ( averageGrade > 3.4 ) { 77 printf( "Average grade is A\n" ); 78 } /* end if */ 79 else if ( averageGrade > 2.4 ) { 80 printf( "Average grade is B\n" ); 81 } /* end else if */ 82 else if ( averageGrade > 1.4 ) { 83 printf( "Average grade is C\n" ); 84 } /* end else if */ 85 else if ( averageGrade > 0.4 ) { 86 printf( "Average grade is D\n" ); 87 } /* end else if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 71 88 else { 89 printf( "Average grade is F\n" ); 90 } /* end else */ 91 92 return 0; /* indicate successful termination */ 93 94 } /* end main */ Enter the letter grades. Enter the EOF character to end input. ABBBCDF CCCDDDCB BAABCCC ^Z 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 /* Exercise 4.23 Solution */ 2 #include 3 #include 4 5 int main( void ) 6{ 7 int year; /* year counter */ 8 int amount; /* amount on deposit, in pennies */ 9 int dollars; /* dollar portion of amount */ 10 int cents; /* cents portion of amount */ 11 int principal = 100000; /* starting principal, in pennies ($1000) */ 12 double rate = .05; /* interest rate */ 13 14 /* display headers for table */ 15 printf( "%s%21s\n", "Year", "Amount on deposit" ); 16 17 /* loop 10 times */ 18 for ( year = 1; year <= 10; year++ ) { 19 20 /* determine new amount (in pennies) */ 21 amount = principal * pow( 1.0 + rate, year ); 22 23 /* determine cents portion of amount (last two digits) */ 24 cents = amount % 100; 25 26 /* determine dollars portion of amount */ 27 /* integer division truncates decimal places */ 28 dollars = amount / 100; 29 30 /* display year, dollar portion followed by period */ 31 printf( "%4d%18d.", year, dollars ); 32 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 72 C Program Control: Solutions Chapter 4 33 /* display cents portion */ 34 /* if cents portion only 1 digit, insert 0 */ 35 if ( cents < 10 ) { 36 printf("0%d\n", cents); 37 } /* end if */ 38 else { 39 printf("%d\n", cents); 40 } /* end else */ 41 42 } /* end for */ 43 44 return 0; /* indicate successful termination */ 45 46 } /* end main */ Year 1 2 3 4 5 6 7 8 9 10 Amount on deposit 1050.00 1102.50 1157.62 1215.50 1276.28 1340.09 1407.10 1477.45 1551.32 1628.89 4.24 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. Chapter 4 C Program Control: Solutions 73 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 /* Exercise 4.26 Solution */ 2 #include 3 4 int main( void ) 5{ 6 long double pi = 0.0; /* approximated value for pi */ 7 long double num = 4.0; /* numerator */ 8 long double denom = 1.0; /* denominator of current term */ 9 long int loop; /* loop counter */ 10 long int accuracy; /* number of terms */ 11 12 accuracy = 400000; /* set decimal accuracy */ 13 14 /* display table headers */ 15 printf( "Accuracy set at: %ld\n", accuracy ); 16 printf( "term\t\t pi\n" ); 17 18 /* loop through each term */ 19 for ( loop = 1; loop <= accuracy; loop++ ) { 20 21 /* if odd-numbered term, add current term */ 22 if ( loop % 2 != 0 ) { 23 pi += num / denom; 24 } /* end if */ 25 else { /* if even-numbered term, subtract current term */ 26 pi -= num / denom; 27 } /* end else */ 28 29 /* display number of terms and approximated 30 value for pi with 8 digits of precision */ 31 printf( "%ld\t\t%Lf\n", loop, pi ); 32 33 denom += 2.0; /* update denominator */ 34 35 } /* end for */ 36 37 return 0; /* indicate successful termination */ 38 39 } /* 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 3.142598 996 3.140589 997 3.142596 998 3.140591 999 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 /* Exercise 4.27 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int count = 0; /* number of triples found */ 7 long int side1; /* side1 value counter */ 8 long int side2; /* side2 value counter */ 9 long int hypotenuse; /* hypotenuse value counter */ 10 long int hyptSquared; /* hypotenuse squared */ 11 long int sidesSquared; /* sum of squares of sides */ 12 13 /* side1 values range from 1 to 500 */ 14 for ( side1 = 1; side1 <= 500; side1++ ) { 15 16 /* side2 values range from current side1 to 500 */ 17 for ( side2 = 1; side2 <= 500; side2++ ) { 18 19 /* hypotenuse values range from current side2 to 500 */ 20 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) { 21 22 /* calculate square of hypotenuse value */ 23 hyptSquared = hypotenuse * hypotenuse; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 75 24 25 /* calculate sum of squares of sides */ 26 sidesSquared = side1 * side1 + side2 * side2; 27 28 /* if hypotenuse squared = side1 squared + side2 squared, 29 Pythagorean triple */ 30 if ( hyptSquared == sidesSquared ) { 31 32 /* display triple */ 33 printf( "%ld %ld %ld\n", side1, side2, hypotenuse ); 34 ++count; /* update count */ 35 } /* end if */ 36 37 } /* end for */ 38 39 } /* end for */ 40 41 } /* end for */ 42 43 /* display total number of triples found */ 44 printf( "A total of %d triples were found.\n", count ); 45 46 return 0; /* indicate successful termination */ 47 48 } /* end main */ 345 435 5 12 13 6 8 10 7 24 25 8 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 /* Exercise 4.28 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int payCode; /* current employee's pay code */ 7 int managers = 0; /* total number of managers */ 8 int hWorkers = 0; /* total number of hourly workers */ 9 int cWorkers = 0; /* total number of commission workers */ 10 int pWorkers = 0; /* total number of pieceworkers */ 11 int pieces; /* current pieceworker's number of pieces */ 12 double mSalary; /* manager's salary */ 13 double hSalary; /* hourly worker's salary */ 14 double cSalary; /* commission worker's salary */ 15 double pSalary; /* pieceworker's salary */ 16 double hours; /* total hours worked */ 17 double otPay; /* overtime pay */ 18 double otHours; /* overtime hours */ 19 double pay; /* current employee's weekly pay */ 20 21 /* prompt for first employee input */ 22 printf( "Enter paycode ( -1 to end): " ); 23 scanf( "%d", &payCode ); 24 25 /* loop while sentinel value not read from user */ 26 while ( payCode != -1 ) { 27 28 /* switch to appropriate computation according to pay code */ 29 switch ( payCode ) { 30 31 /* pay code 1 corresponds to manager */ 32 case 1: 33 34 /*prompt for weekly salary */ 35 printf( "Manager selected.\n" ); 36 printf( "Enter weekly salary: " ); 37 scanf( "%lf", &mSalary ); 38 39 /* manager's pay is weekly salary */ 40 printf( "The manager's pay is $%.2f\n", mSalary ); 41 42 ++managers; /* update total number of managers */ 43 break; /* exit switch */ 44 45 /* pay code 2 corresponds to hourly worker */ 46 case 2: 47 48 /* prompt for hourly salary */ 49 printf( "Hourly worker selected.\n" ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 77 50 printf( "Enter the hourly salary: " ); 51 scanf( "%lf", &hSalary ); 52 53 /* prompt for number of hours worked */ 54 printf( "Enter the total hours worked: " ); 55 scanf( "%lf", &hours ); 56 57 /* pay fixed for up to 40 hours, 1.5 for hours over 40 */ 58 if ( hours > 40.0 ) { 59 60 /* calculate OT hours and total pay */ 61 otHours = hours - 40.0; 62 otPay = hSalary * 1.5 * otHours + hSalary * 40.0; 63 64 printf( "Worker has worked %.1f overtime hours.\n", otHours ); 65 printf( "Workers pay is $%.2f\n", otPay ); 66 } /* end if */ 67 else { /* no overtime */ 68 pay = hSalary * hours; 69 printf( "Worker's pay is $%.2f\n", pay ); 70 } /* end else */ 71 72 ++hWorkers; /* update total number of hourly workers */ 73 break; /* exit switch */ 74 75 /* pay code 3 corresponds to commission worker */ 76 case 3: 77 78 /* prompt for gross weekly sales */ 79 printf( "Commission worker selected.\n" ); 80 printf( "Enter gross weekly sales: " ); 81 scanf( "%lf", &cSalary ); 82 83 /* pay $250 plus 5.7% of gross weekly sales */ 84 pay = 250.0 + 0.057 * cSalary; 85 printf( "Commission Worker's pay is $%.2f\n", pay ); 86 87 ++cWorkers; /* update total number of commission workers */ 88 break; /* exit switch */ 89 90 /* pay code 4 corresponds to pieceworker */ 91 case 4: 92 93 /* prompt for number of pieces */ 94 printf( "Piece worker selected.\nEnter number of pieces: " ); 95 scanf( "%d", &pieces ); 96 97 /* prompt for wage per piece */ 98 printf( "Enter wage per piece: " ); 99 scanf( "%lf", &pSalary ); 100 101 pay = pieces * pSalary; /* compute pay */ 102 printf( "Piece Worker's pay is $%.2f\n", pay ); 103 104 ++pWorkers; /* update total number of pieceworkers */ 105 break; /* exit switch */ 106 107 /* default case */ 108 default : 109 printf( "Invalid pay code.\n" ); 110 break; 111 } /* end switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 78 C Program Control: Solutions 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 : %d\n", managers ); 121 printf( "Total number of hourly workers paid : %d\n", hWorkers ); 122 printf( "Total number of commission workers paid: %d\n", cWorkers ); 123 printf( "Total number of piece workers paid : %d\n", pWorkers ); 124 125 return 0; /* indicate successful termination */ 126 127 } /* end main */ Enter paycode ( -1 to end): 4 Piece worker selected. Enter number of pieces: 200 Enter wage per piece: 20 Piece Worker's pay is $4000.00 Enter paycode ( -1 to end ): -1 Total number of managers paid :0 Total number of hourly workers paid : 0 Total number of commission workers paid: 0 Total number of piece workers paid :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 paycode ( -1 to end ): 4 Piece worker selected. Enter number of pieces: 200 Enter wage per piece: 20 Piece Worker's pay is $4000.00 Enter paycode ( -1 to end ): -1 Total number of managers paid :1 Total number of hourly workers paid : 1 Total number of commission workers paid: 1 Total number of piece workers paid :1 Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 79 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 /* Exercise 4.29 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int x = 10; /* define current variable value */ 7 int y = 1; /* define current variable value */ 8 int a = 3; /* define current variable value */ 9 int b = 3; /* define current variable value */ 10 int g = 5; /* define current variable value */ 11 int Y = 1; /* define current variable value */ 12 int i = 2; /* define current variable value */ 13 int j = 9; /* define current variable value */ 14 15 /* display variable values */ 16 printf( "current variable values are: \n" ); 17 printf( "x = %d, y = %d, a = %d,", x, y, a ); 18 printf( " b = %d\n", b ); 19 printf( "g = %d, Y = %d, i = %d,", g, Y, i ); 20 printf( " j = %d\n\n", j ); 21 22 /* part a */ 23 if ( ( !( x < 5 ) && !( y >= 7 ) ) == ( !( ( x < 5 ) || ( y >= 7 ) 24 ))){ 25 printf( "!( x < 5 ) && !( y >= 7 ) is equivalent to" 26 " !( ( x < 5 ) || ( y >= 7 ) )\n" ); 27 } /* end if */ 28 else { 29 printf( "!( x < 5 ) && !( y >= 7 ) is not equivalent to" 30 " !( ( x < 5 ) || ( y >= 7 ) )\n" ); 31 } /* end else */ 32 33 /* part b */ 34 if ( ( !( a == b ) || !( g != 5 ) ) == ( !( ( a == b ) && ( g != 5 ) 35 ))){ 36 printf( "!( a == b ) || !( g != 5 ) is equivalent to" 37 " !( ( a == b ) && ( g != 5 ) )\n" ); 38 } /* end if */ 39 else { 40 printf( "!( a == b ) || !( g != 5 ) is not equivalent to" 41 " !( ( a == b ) && ( g != 5 ) )\n" ); 42 } /* end else */ 43 44 /* part c */ 45 if ( !( ( x <= 8 ) && ( Y > 4 ) ) == ( !( x <= 8 ) || !( Y > 4 ) 46 )){ 47 printf( "!( ( x <= 8 ) && ( Y > 4 ) ) is equivalent to" 48 " ( !( x <= 8 ) || !( Y > 4 ) )\n" ); 49 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 80 C Program Control: Solutions Chapter 4 50 else { 51 printf( "!( ( x <= 8 ) && ( Y > 4 ) ) is not equivalent to" 52 " ( !( x <= 8 ) || !( Y > 4 ) )\n" ); 53 } /* end else */ 54 55 /* part d */ 56 if ( !( ( i > 4 ) || ( j <= 6 ) ) == ( !( i > 4 ) && !( j <= 6 ) 57 )){ 58 printf( "!( ( i > 4 ) || ( j <= 6 ) ) is equivalent to" 59 " ( !( i > 4 ) && !( j <= 6 ) )\n" ); 60 } /* end if */ 61 else { 62 printf( "!( ( i > 4 ) || ( j <= 6 ) ) is not equivalent to" 63 " ( !( i > 4 ) && !( j <= 6 ) )\n" ); 64 } /* end else */ 65 66 return 0; /* indicate successful termination */ 67 68 } /* end main */ current variable values are: x = 10, y = 1, a = 3, b = 3 g = 5, Y = 1, i = 2, j = 9 !( x < 5 ) && !( y >= 7 ) is equivalent to !( ( x < 5 ) || ( y >= 7 ) ) !( a == b ) || !( g != 5 ) is equivalent to !( ( a == b ) && ( g != 5 ) ) !( ( x <= 8 ) && ( Y > 4 ) ) is equivalent to ( !( x <= 8 ) || !( Y > 4 ) ) !( ( i > 4 ) || ( j <= 6 ) ) is equivalent to ( !( i > 4 ) && !( j <= 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 /* Exercise 4.30 Part A Solution */ 2 #include 3 4 int main( void ) 5{ 6 int grade; /* current grade */ 7 int aCount = 0; /* total A grades */ 8 int bCount = 0; /* total B grades */ 9 int cCount = 0; /* total C grades */ 10 int dCount = 0; /* total D grades */ 11 int fCount = 0; /* total F grades */ 12 13 /* prompt user for grades */ 14 printf( "Enter the letter grades." ); 15 printf( " Enter the EOF character to end input:\n" ); 16 17 /* while EOF not entered by user */ 18 while ( ( grade = getchar() ) != EOF ) { 19 20 /* Update count for appropriate grade */ 21 if ( grade == 'A' || grade == 'a' ) { 22 ++aCount; 23 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 81 24 else if ( grade == 'B' || grade == 'b' ) { 25 ++bCount; 26 } /* end else if */ 27 else if ( grade == 'C' || grade == 'c' ) { 28 ++cCount; 29 } /* end else if */ 30 else if ( grade == 'D' || grade == 'd' ) { 31 ++dCount; 32 } /* end else if */ 33 else if ( grade == 'F' || grade == 'f' ) { 34 ++fCount; 35 } /* end else if */ 36 else if ( grade == '\n' || grade == ' ' ) { 37 ; /* empty body */ 38 } /* end else if */ 39 else { 40 printf( "Incorrect letter grade entered." ); 41 printf( " Enter a new grade.\n" ); 42 } /* end else */ 43 44 } /* end while */ 45 46 /* display totals for each grade */ 47 printf( "\nTotals for each letter grade were:\n" ); 48 printf( "A: %d\n", aCount ); 49 printf( "B: %d\n", bCount ); 50 printf( "C: %d\n", cCount ); 51 printf( "D: %d\n", dCount ); 52 printf( "F: %d\n", fCount ); 53 54 return 0; /* indicate successful termination */ 55 56 } /* 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 /* Exercise 4.30 Part B Solution */ 2 #include 3 4 int main( void ) 5{ 6 int grade; /* current grade */ 7 int aCount = 0; /* total A grades */ 8 int bCount = 0; /* total B grades */ 9 int cCount = 0; /* total C grades */ 10 int dCount = 0; /* total D grades */ 11 int fCount = 0; /* total F grades */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 82 C Program Control: Solutions 12 13 /* prompt user for grades */ 14 printf( "Enter the letter grades." ); 15 printf( " Enter the EOF character to end input:\n" ); 16 17 /* while EOF not entered by user */ 18 while ( ( grade = getchar() ) != EOF ) { 19 20 /* update count for appropriate grade */ 21 if ( grade == 'A' || grade == 'a' ) { 22 ++aCount; 23 } /* end if */ 24 25 if ( grade == 'B' || grade == 'b' ) { 26 ++bCount; 27 } /* end if */ 28 29 if ( grade == 'C' || grade == 'c' ) { 30 ++cCount; 31 } /* end if */ 32 33 if ( grade == 'D' || grade == 'd' ) { 34 ++dCount; 35 } /* end if */ 36 37 if ( grade == 'F' || grade == 'f' ) { 38 ++fCount; 39 } /* end if */ 40 41 if ( grade == '\n' || grade == ' ' ) { 42 ; /* empty body */ 43 } /* end if */ 44 45 /* default */ 46 if ( grade != 'a' && grade != 'A' && 47 grade != 'B' && grade != 'b' && 48 grade != 'c' && grade != 'C' && 49 grade != 'd' && grade != 'd' && 50 grade != 'f' && grade != 'F' && 51 grade != '\n'&& grade != ' ' ) { 52 53 printf( "Incorrect letter grade entered." ); 54 printf( " Enter a new grade.\n" ); 55 } /* end if */ 56 57 } /* end while */ 58 59 /* display totals for each grade */ 60 printf( "\nTotals for each letter grade were:\n" ); 61 printf( "A: %d\n", aCount ); 62 printf( "B: %d\n", bCount ); 63 printf( "C: %d\n", cCount ); 64 printf( "D: %d\n", dCount ); 65 printf( "F: %d\n", fCount ); 66 67 return 0; /* indicate successful termination */ 68 69 } /* end main */ Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 83 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 /* Exercise 4.31 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int line; /* line counter */ 7 int space; /* space counter */ 8 int asterisk; /* asterisk counter */ 9 10 /* top half */ 11 for ( line = 1; line <= 9; line += 2 ) { 12 13 /* print preceding spaces */ 14 for ( space = ( 9 - line ) / 2; space > 0; space-- ) { 15 printf( " " ); 16 } /* end for */ 17 18 /* print asterisks */ 19 for ( asterisk = 1; asterisk <= line; asterisk++ ) { 20 printf( "*" ); 21 } /* end for */ 22 23 printf( "\n" ); 24 } /* end for */ 25 26 /* bottom half */ 27 for ( line = 7; line >= 0; line -= 2 ) { 28 29 /* print preceding spaces */ 30 for ( space = ( 9 - line ) / 2; space > 0; space-- ) { 31 printf( " " ); 32 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 84 C Program Control: Solutions Chapter 4 33 34 /* print asterisks */ 35 for ( asterisk = 1; asterisk <= line; asterisk++ ) { 36 printf( "*" ); 37 } /* end for */ 38 39 printf( "\n" ); 40 } /* end for */ 41 42 return 0; /* indicate successful termination */ 43 44 } /* 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 /* Exercise 4.32 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int line; /* line counter */ 7 int space; /* space counter */ 8 int asterisk; /* asterisk counter */ 9 int size; /* number of rows in diamond */ 10 11 /* prompt for diamond size */ 12 printf( "Enter an odd number for the diamond size ( 1-19 ):\n" ); 13 scanf( "%d", &size ); 14 15 /* top half */ 16 for ( line = 1; line <= size - 2; line += 2 ) { 17 18 /* print preceding spaces */ 19 for ( space = ( size - line ) / 2; space > 0; space-- ) { 20 printf( " " ); 21 } /* end for */ 22 23 /* print asterisks */ 24 for ( asterisk = 1; asterisk <= line; asterisk++ ) { 25 printf( "*" ); 26 } /* end for */ 27 28 printf( "\n" ); 29 } /* end for */ 30 31 /* bottom half */ 32 for ( line = size; line >= 0; line -= 2 ) { 33 34 /* print preceding spaces */ 35 for ( space = ( size - line ) / 2; space > 0; space-- ) { 36 printf( " " ); 37 } /* end for */ 38 39 /* print asterisks */ 40 for ( asterisk = 1; asterisk <= line; asterisk++ ) { 41 printf( "*" ); 42 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 85 43 44 printf( "\n" ); 45 } /* end for */ 46 47 return 0; /* indicate successful termination */ 48 49 } /* end main */ Enter an odd number for the diamond size ( 1-19 ): 13 * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** * 4.33 Write a program that prints a table of all the Roman numeral equivalents of the decimal numbers in the range 1 to 100. ANS: 1 /* Exercise 4.33 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int loop; /* loop counter */ 7 int div; /* tens digit */ 8 int mod; /* ones digit */ 9 10 /* display table headers */ 11 printf( " Roman\nNumeral\t\tDecimal\n" ); 12 13 /* loop 100 times */ 14 for ( loop = 1; loop <= 100; loop++ ) { 15 div = loop / 10; /* separate tens digit */ 16 mod = loop % 10; /* separate ones digit */ 17 18 /* switch structure for tens digit */ 19 switch ( div ) { 20 21 /* print appropriate Roman numeral for tens digit */ 22 case 0: 23 break; 24 25 case 1: 26 printf( "X" ); 27 break; /* exit switch */ 28 29 case 2: 30 printf( "XX" ); 31 break; /* exit switch */ 32 33 case 3: 34 printf( "XXX" ); 35 break; /* exit switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 86 C Program Control: Solutions Chapter 4 36 37 case 4: 38 printf( "XL" ); 39 break; /* exit switch */ 40 41 case 5: 42 printf( "L" ); 43 break; /* exit switch */ 44 45 case 6: 46 printf( "LX" ); 47 break; /* exit switch */ 48 49 case 7: 50 printf( "LXX" ); 51 break; /* exit switch */ 52 53 case 8: 54 printf( "LXXX" ); 55 break; /* exit switch */ 56 57 case 9: 58 printf( "XC" ); 59 break; /* exit switch */ 60 61 case 10: 62 printf( "C" ); 63 break; /* exit switch */ 64 65 default: 66 break; /* exit switch */ 67 } /* end switch */ 68 69 /* switch structure for ones digit */ 70 switch( mod ) { 71 72 /* print appropriate Roman numeral for ones digit */ 73 case 0: 74 printf( "\t\t%4d\n", div * 10 ); 75 break; /* exit switch */ 76 77 case 1: 78 printf( "I\t\t%4d\n", div * 10 + mod ); 79 break; /* exit switch */ 80 81 case 2: 82 printf( "II\t\t%4d\n", div * 10 + mod ); 83 break; /* exit switch */ 84 85 case 3: 86 printf( "III\t\t%4d\n", div * 10 + mod ); 87 break; /* exit switch */ 88 89 case 4: 90 printf( "IV\t\t%4d\n", div * 10 + mod ); 91 break; /* exit switch */ 92 93 case 5: 94 printf( "V\t\t%4d\n", div * 10 + mod ); 95 break; /* exit switch */ 96 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 ... LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C Decimal 1 2 3 4 5 6 7 8 9 10 89 90 91 92 93 94 95 96 97 98 99 100 C Program Control: Solutions 87 © 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 /* Exercise 4.34 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int loop; /* loop counter */ 7 int number; /* current number */ 8 int temp1; /* temporary integer */ 9 10 /* print table headers */ 11 printf( "Decimal\t\tBinary\t\tOctal\t\tHexadecimal\n" ); 12 13 /* loop through values 1 to 256 */ 14 for ( loop = 1; loop <= 256; loop++ ) { 15 printf( "%d\t\t", loop ); 16 number = loop; 17 18 /* binary numbers */ 19 printf( "%c", number == 256 ? '1' : '0' ); 20 21 printf( "%c", number < 256 && number >= 128 ? '1' : '0' ); 22 number %= 128; 23 24 printf( "%c", number < 128 && number >= 64 ? '1' : '0' ); 25 number %= 64; 26 27 printf( "%c", number < 64 && number >= 32 ? '1' : '0' ); 28 number %= 32; 29 30 printf( "%c", number < 32 && number >= 16 ? '1' : '0' ); 31 number %= 16; 32 33 printf( "%c", number < 16 && number >= 8 ? '1' : '0' ); 34 number %= 8; 35 36 printf( "%c", number < 8 && number >= 4 ? '1' : '0' ); 37 number %= 4; 38 39 printf( "%c", number < 4 && number >= 2 ? '1' : '0' ); 40 number %= 2; 41 42 printf( "%c\t", number == 1 ? '1' : '0' ); 43 44 /* octal numbers */ 45 number = loop; 46 47 printf( "%d", number < 512 && number >= 64 ? number / 64 : 0 ); 48 number %= 64; 49 50 printf( "%d", number < 64 && number >= 8 ? number / 8 : 0 ); 51 number %= 8; 52 53 printf( "%d\t\t", number == 0 ? 0 : number ); 54 55 /* hexadecimal numbers */ 56 number = loop; 57 temp1 = 16; 58 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 59 if ( number < 4096 && number >= 256 ) { 60 printf( "%d", number / 256 ); 61 } /* end if */ 62 63 if ( number < 256 && number >= 16 ) { 64 temp1 = number / 16; 65 number %= 16; 66 } /* end if */ 67 else { 68 printf( "0" ); 69 } /* end else */ 70 71 /* convert to letter if temp1 is above 9 */ 72 if ( temp1 <= 9 ) { 73 printf( "%d", temp1 ); 74 } /* end if */ 75 else if ( temp1 >= 10 && temp1 <= 15 ) { 76 printf( "%c", 'A' + ( temp1 - 10 ) ); 77 } /* end else if */ 78 79 /* convert to letter if number is above 9 */ 80 if ( number <= 9 ) { 81 printf( "%d", number ); 82 } /* end if */ 83 else if ( number >= 10 && number <= 15 ) { 84 printf( "%c", 'A' + ( number - 10 ) ); 85 } /* end else if */ 86 87 printf( "\n" ); 88 } /* end for */ 89 90 return 0; /* indicate successful termination */ 91 92 } /* end main */ Decimal 1 2 3 4 5 6 7 8 9 10 ... 250 251 252 253 254 255 256 Binary 000000001 000000010 000000011 000000100 000000101 000000110 000000111 000001000 000001001 000001010 011111010 011111011 011111100 011111101 011111110 011111111 100000000 Octal 001 002 003 004 005 006 007 010 011 012 372 373 374 375 376 377 400 Hexadecimal 01 02 03 04 05 06 07 08 09 0A FA FB FC FD FE FF 10F C Program Control: Solutions 89 © 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 /* Exercise 4.36 Solution */ 2 /* This is a simple calender solution, that does */ 3 /* not account for the shifting of dates from */ 4 /* year to year. */ 5 6 #include 7 8 int main( void ) 9{ 10 int year; /* current year */ 11 int leapYear; /* leap year, 1 = yes, 0 = no */ 12 int days; /* total days in current month */ 13 int month; /* current month */ 14 int space; /* space counter */ 15 int dayPosition; /* starting day position of year */ 16 int dayNum; /* counter for days of the month */ 17 18 /* loop until input is valid */ 19 do { 20 printf( "Enter a calendar year between 1994 and 1999: " ); 21 scanf( "%d", &year ); 22 } while ( year < 1994 || year > 1999 ); /* end do...while */ 23 24 /* determine starting day position */ 25 switch ( year ) { 26 27 case 1994: 28 dayPosition = 7; 29 break; /* exit switch */ 30 31 case 1995: 32 dayPosition = 1; 33 break; /* exit switch */ 34 35 case 1996: 36 dayPosition = 2; 37 break; /* exit switch */ 38 39 case 1997: 40 dayPosition = 4; 41 break; /* exit switch */ 42 43 case 1998: 44 dayPosition = 5; 45 break; /* exit switch */ 46 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 91 47 case 1999: 48 dayPosition = 6; 49 break; /* exit switch */ 50 } /* end switch */ 51 52 /* check for leap years */ 53 if ( year % 400 == 0 ) { 54 leapYear = 1; 55 } /* end if */ 56 else if ( year % 4 == 0 && year % 100 != 0 ) { 57 leapYear = 1; 58 } /* end else if */ 59 else { 60 leapYear = 0; 61 } /* end else */ 62 63 /* loop through months and print calendar */ 64 for ( month = 1; month <= 12; month++ ) { 65 66 /* begin with the month */ 67 switch ( month ) { 68 69 case 1: 70 printf( "\n\nJanuary %d\n", year ); 71 days = 31; 72 break; /* exit switch */ 73 74 case 2: 75 printf( "\n\nFebruary %d\n", year ); 76 days = leapYear == 1 ? 29 : 28; 77 break; /* exit switch */ 78 79 case 3: 80 printf( "\n\nMarch %d\n", year ); 81 days = 31; 82 break; /* exit switch */ 83 84 case 4: 85 printf( "\n\nApril %d\n", year ); 86 days = 30; 87 break; /* exit switch */ 88 89 case 5: 90 printf( "\n\nMay %d\n", year ); 91 days = 31; 92 break; /* exit switch */ 93 94 case 6: 95 printf( "\n\nJune %d\n", year ); 96 days = 30; 97 break; /* exit switch */ 98 99 case 7: 100 printf( "\n\nJuly %d\n", year ); 101 days = 31; 102 break; /* exit switch */ 103 104 case 8: 105 printf( "\n\nAugust %d\n", year ); 106 days = 31; 107 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 */ Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 C Program Control: Solutions 93 Enter a calendar year between 1994 and 1999: 1999 January 1999 SMTWRFS 12 3456789 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 February 1999 SMTWRFS 123456 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 March 1999 SMTWRFS 123456 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 . . . 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 /* Exercise 4.37 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int x; /* loop counter */ 7 int breakOut = 1; /* breakout condition */ 8 9 /* test for breakout condition */ 10 for ( x = 1; x <= 10 && breakOut == 1; x++ ) { 11 12 /* break out of loop after x = 4 */ 13 if ( x == 4 ) { 14 breakOut = -1; 15 } /* end if */ 16 17 printf( "%d ", x ); 18 } /* end for */ 19 20 printf( "\nBroke out of loop at x = %d\n", x ); 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 94 C Program Control: Solutions Chapter 4 1234 Broke out of loop at x = 5 4.38 What does the following program segment do? 1 for ( i = 1; i <= 5; i++ ) { 2 for ( j = 1; j <= 3; j++ ) { 3 for ( k = 1; k <= 4; k++ ) 4 printf( "*" ); 5 printf( "\n" ); 6 } 7 printf( "\n" ); 8} 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 /* Exercise 4.39 Solution */ 2 #include 3 4 int main( void ) 5{ 6 int x; /* loop counter */ 7 8 /* loop 10 times */ 9 for ( x = 1; x <= 10; x++ ) { 10 11 /* if x == 5, skip to next interation */ 12 if ( x == 5 ) { 13 ++x; 14 } /* end if */ 15 16 printf( "%d ", x ); 17 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 4 18 19 printf( "\nUsed ++x to skip printing the value 5\n" ); 20 21 return 0; /* indicate successful termination */ 22 23 } /* end main */ 1 2 3 4 6 7 8 9 10 Used ++x to skip printing the value 5 C Program Control: Solutions 95 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 96 C Program Control: Solutions Chapter 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 /* Exercise 5.9 Solution */ 2 #include 3 #include 4 5 double calculateCharges( double hours ); /* function prototype */ 6 7 int main() 8{ 9 double h; /* number of hours for current car */ 10 double currentCharge; /* parking charge for current car */ 11 double totalCharges = 0.0; /* total charges */ 12 double totalHours = 0.0; /* total number of hours */ 13 int i; /* loop counter */ 14 int first = 1; /* flag for printing table headers */ 15 16 printf( "Enter the hours parked for 3 cars: " ); 17 18 /* loop 3 times for 3 cars */ 19 for ( i = 1; i <= 3; i++ ) { 20 scanf( "%lf", &h ); 21 totalHours += h; /* add current hours to total hours */ 22 23 /* if first time through loop, display headers */ 24 if ( first ) { 25 printf( "%5s%15s%15s\n", "Car", "Hours", "Charge" ); 26 27 /* set flag to false to prevent from printing again */ 28 first = 0; 29 } /* end if */ 30 31 /* calculate current car's charge and update total */ 32 totalCharges += ( currentCharge = calculateCharges( h ) ); 33 34 /* display row data for current car */ 35 printf( "%5d%15.1f%15.2f\n", i, h, currentCharge ); 36 } /* end for */ 37 38 /* display row data for totals */ 39 printf( "%5s%15.1f%15.2f\n", "TOTAL", totalHours, totalCharges ); 40 41 return 0; /* indicate successful termination */ 42 43 } /* end main */ 44 45 /* calculateCharges returns charge according to number of hours */ 46 double calculateCharges( double hours ) 47 { 48 double charge; /* calculated charge */ 49 50 /* $2 for up to 3 hours */ 51 if ( hours < 3.0 ) { 52 charge = 2.0; 53 } /* end if */ 54 55 /* $.50 for each hour or part thereof in excess of 3 hours */ 56 else if ( hours < 19.0 ) { 57 charge = 2.0 + .5 * ceil( hours - 3.0 ); 58 } /* end else if */ 59 else { /* maximum charge $10 */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 99 60 charge = 10.0; 61 } /* end else */ 62 63 return charge; /* return calculated charge */ 64 65 } /* end function calculateCharges */ 5.10 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 /* Exercise 5.10 Solution */ 2 #include 3 #include 4 5 void calculateFloor( void ); /* function prototype */ 6 7 int main() 8{ 9 calculateFloor(); /* call function calculateFloor */ 10 11 return 0; /* indicate successful termination */ 12 13 } /* end main */ 14 15 /* calculateFloor rounds 5 inputs */ 16 void calculateFloor( void ) 17 { 18 double x; /* current input */ 19 double y; /* current input rounded */ 20 int loop; /* loop counter */ 21 22 /* loop for 5 inputs */ 23 for ( loop = 1; loop <= 5; loop++ ) { 24 printf( "Enter a floating point value: " ); 25 scanf( "%lf", &x ); 26 27 /* y holds rounded input */ 28 y = floor( x + .5 ); 29 printf( "%f rounded is %.1f\n\n", x, y ); 30 } /* end for */ 31 32 } /* 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 /* Exercise 5.11 Solution */ 2 #include 3 #include 4 5 double roundToInteger( double n ); /* function prototype */ 6 double roundToTenths( double n ); /* function prototype */ 7 double roundToHundredths( double n ); /* function prototype */ 8 double roundToThousandths( double n ); /* function prototype */ 9 10 int main() 11 { 12 int i; /* loop counter */ 13 int count; /* number of values to process */ 14 double number; /* current input */ 15 16 printf( "How many numbers do you want to process? " ); 17 scanf( "%d", &count ); 18 19 /* loop for inputs */ 20 for ( i = 0; i < count; i++ ) { 21 printf( "Enter number: " ); 22 scanf( "%lf", &number ); 23 24 /* display number rounded to nearest integer */ 25 printf( "%f rounded to an integer is %f\n", 26 number, roundToInteger( number ) ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 101 27 28 /* display number rounded to nearest tenth */ 29 printf( "%f rounded to the nearest tenth is %f\n", 30 number, roundToTenths( number ) ); 31 32 /* display number rounded to nearest hundredth */ 33 printf( "%f rounded to the nearest hundredth is %f\n", 34 number, roundToHundredths( number ) ); 35 36 /* display number rounded to nearest thousandth */ 37 printf( "%f rounded to the nearest thousandth is %f\n\n", 38 number, roundToThousandths( number ) ); 39 } /* end for */ 40 41 return 0; /* indicate successful termination */ 42 43 } /* end main */ 44 45 /* roundToInteger rounds n to nearest integer */ 46 double roundToInteger( double n ) 47 { 48 return floor( n + .5 ); 49 50 } /* end function roundToInteger */ 51 52 /* roundToTenths rounds n to nearest tenth */ 53 double roundToTenths( double n ) 54 { 55 return floor( n * 10 + .5 ) / 10; 56 57 } /* end function roundToTenths */ 58 59 /* roundToHundredths rounds n to nearest hundredth */ 60 double roundToHundredths( double n ) 61 { 62 return floor( n * 100 + .5 ) / 100; 63 64 } /* end function roundToHundredths */ 65 66 /* roundToThousandths rounds n to nearest thousandth */ 67 double roundToThousandths( double n ) 68 { 69 return floor( n * 1000 + .5 ) / 1000; 70 71 } /* 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 5.13 5.14 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. 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; 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. Chapter 5 C Functions: Solutions 103 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 /* Exercise 5.15 Solution */ 2 #include 3 #include 4 5 double hypotenuse( double s1, double s2 ); /* function prototype */ 6 7 int main() 8{ 9 int i; /* loop counter */ 10 double side1; /* value for first side */ 11 double side2; /* value for second side */ 12 13 /* loop 3 times */ 14 for ( i = 1; i <= 3; i++ ) { 15 printf( "Enter the sides of the triangle: " ); 16 scanf( "%lf%lf", &side1, &side2 ); 17 18 /* calculate and display hypotenuse value */ 19 printf( "Hypotenuse: %.1f\n\n", hypotenuse( side1, side2 ) ); 20 } /* end for */ 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ 25 26 /* hypotenuse calculates value of hypotenuse of 27 a right triangle given two side values */ 28 double hypotenuse( double s1, double s2 ) 29 { 30 return sqrt( pow( s1, 2 ) + pow( s2, 2 ) ); 31 32 } /* 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 Chapter 5 5.16 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 /* Exercise 5.16 Solution */ 2 #include 3 4 int integerPower( int b, int e ); 5 6 int main() 7{ 8 int exp; /* integer exponent */ 9 int base; /* integer base */ 10 11 printf( "Enter integer base and exponent: " ); 12 scanf( "%d%d", &base, &exp ); 13 14 printf( "%d to the power %d is: %d\n", 15 base, exp, integerPower( base, exp ) ); 16 17 return 0; /* indicate successful termination */ 18 19 } /* end main */ 20 21 /* integerPower calculates and returns b raised to the e power */ 22 int integerPower( int b, int e ) 23 { 24 int product = 1; /* resulting product */ 25 int i; /* loop counter */ 26 27 /* multiply product times b (e repetitions) */ 28 for ( i = 1; i <= e; i++ ) { 29 product *= b; 30 } /* end for */ 31 32 return product; /* return resulting product */ 33 34 } /* 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. Chapter 5 C Functions: Solutions 105 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 /* Exercise 5.17 Solution */ 2 #include 3 4 int multiple( int a, int b ); /* function prototype */ 5 6 int main() 7{ 8 int x; /* first integer */ 9 int y; /* second integer */ 10 int i; /* loop counter */ 11 12 /* loop 3 times */ 13 for ( i = 1; i <= 3; i++ ) { 14 printf( "Enter two integers: " ); 15 scanf( "%d%d", &x, &y ); 16 17 /* determine if second is multiple of first */ 18 if ( multiple( x, y ) ) { 19 printf( "%d is a multiple of %d\n\n", y, x ); 20 } /* end if */ 21 else { 22 printf( "%d is not a multiple of %d\n\n", y, x ); 23 } /* end else */ 24 25 } /* end for */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* end main */ 30 31 /* multiple determines if b is multiple of a */ 32 int multiple( int a, int b ) 33 { 34 return !( b % a ); 35 36 } /* 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 /* Exercise 5.18 Solution */ 2 #include 3 4 int even( int a ); /* function prototype */ 5 6 int main() 7{ 8 int x; /* current input */ 9 int i; /* loop counter */ 10 11 /* loop for 3 inputs */ 12 for ( i = 1; i <= 3; i++ ) { 13 printf( "Enter an integer: " ); 14 scanf( "%d", &x ); 15 16 /* determine if input is even */ 17 if ( even( x ) ) { 18 printf( "%d is an even integer\n\n", x ); 19 } /* end if */ 20 else { 21 printf( "%d is not an even integer\n\n", x ); 22 } /* end else */ 23 24 } /* end for */ 25 26 return 0; /* indicate successful termination */ 27 28 } /* end main */ 29 30 /* even returns true if a is even */ 31 int even( int a ) 32 { 33 return !( a % 2 ); 34 35 } /* 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. Chapter 5 C Functions: Solutions 107 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 /* Exercise 5.19 Solution */ 2 #include 3 4 void square( int s ); /* function prototype */ 5 6 int main() 7{ 8 int side; /* input side length */ 9 10 printf( "Enter side: " ); 11 scanf( "%d", &side ); 12 13 square( side ); /* display solid square of asterisks */ 14 15 return 0; /* indicate successful termination */ 16 17 } /* end main */ 18 19 /* square displays solid square of asterisks with specified side */ 20 void square( int s ) 21 { 22 int i; /* outer loop counter */ 23 int j; /* inner loop counter */ 24 25 /* loop side times for number of rows */ 26 for ( i = 1; i <= s; i++ ) { 27 28 /* loop side times for number of columns */ 29 for ( j = 1; j <= s; j++ ) { 30 printf( "*" ); 31 } /* end for */ 32 33 printf( "\n" ); 34 } /* end for */ 35 36 } /* 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 /* Exercise 5.20 Solution */ 2 #include 3 4 void square( int side, char fillCharacter ); /* function prototype */ 5 6 int main() 7{ 8 int s; /* side length */ 9 char c; /* fill character */ 10 11 printf( "Enter a character and the side length: " ); 12 scanf( "%c%d", &c, &s ); 13 14 square( s, c ); /* display solid square of input character */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* square displays solid square of fillCharacter with specified side */ 21 void square( int side, char fillCharacter ) 22 { 23 int loop; /* outer loop counter */ 24 int loop2; /* inner loop counter */ 25 26 /* loop side times for number of rows */ 27 for ( loop = 1; loop <= side; loop++ ) { 28 29 /* loop side times for number of columns */ 30 for ( loop2 = 1; loop2 <= side; loop2++ ) { 31 printf( "%c", fillCharacter ); 32 } /* end for */ 33 34 printf( "\n" ); 35 } /* end for */ 36 37 } /* 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. Chapter 5 C Functions: Solutions 109 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: 4562 ANS: 1 /* Exercise 5.22 Solution */ 2 #include 3 4 int quotient( int a, int b ); /* function prototype */ 5 int remainder( int a, int b ); /* function prototype */ 6 7 int main() 8{ 9 int number; /* input number */ 10 int divisor = 10000; /* current divisor */ 11 12 printf( "Enter an integer between 1 and 32767: " ); 13 scanf( "%d", &number ); 14 15 printf( "The digits in the number are:\n" ); 16 17 /* determine and print each digit */ 18 while ( number >= 10 ) { 19 20 /* if number is >= current divisor, determine digit */ 21 if ( number >= divisor ) { 22 23 /* use quotient to determine current digit */ 24 printf( "%d ", quotient( number, divisor ) ); 25 26 /* update number to be remainder */ 27 number = remainder( number, divisor ); 28 29 /* update divisor for next digit */ 30 divisor = quotient( divisor, 10 ); 31 } /* end if */ 32 else { /* if number < current divisor, no digit */ 33 divisor = quotient( divisor, 10 ); 34 } /* end else */ 35 36 } /* end while */ 37 38 printf( "%d\n", number ); 39 40 return 0; /* indicate successful termination */ 41 42 } /* end main */ 43 44 /* Part A: determine quotient using integer division */ 45 int quotient( int a, int b ) 46 { 47 return a / b; 48 49 } /* end function quotient */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 110 C Functions: Solutions 50 51 /* Part B: determine remainder using the remainder operator */ 52 int remainder( int a, int b ) 53 { 54 return a % b; 55 56 } /* end function remainder */ Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 111 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 /* Exercise 5.23 Solution */ 2 #include 3 #include 4 5 /* function prototype */ 6 unsigned seconds( unsigned h, unsigned m, unsigned s ); 7 8 int main() 9{ 10 int hours; /* current time's hours */ 11 int minutes; /* current time's minutes */ 12 int secs; /* current time's seconds */ 13 int first; /* first time, in seconds */ 14 int second; /* second time, in seconds */ 15 int difference; /* difference between two times, in seconds */ 16 17 printf( "Enter the first time as three integers: " ); 18 scanf( "%d%d%d", &hours, &minutes, &secs ); 19 20 /* calculate first time in seconds */ 21 first = seconds( hours, minutes, secs ); 22 23 printf( "Enter the second time as three integers: " ); 24 scanf( "%d%d%d", &hours, &minutes, &secs ); 25 26 /* calculate second time in seconds */ 27 second = seconds( hours, minutes, secs ); 28 29 /* calculate difference */ 30 difference = fabs( first - second ); 31 32 /* display difference */ 33 printf( "The difference between the times is %d seconds\n", 34 difference ); 35 36 return 0; /* indicate successful termination */ 37 38 } /* end main */ 39 40 /* seconds returns number of seconds since clock "struck 12" 41 given input time as hours h, minutes m, seconds s */ 42 unsigned seconds( unsigned h, unsigned m, unsigned s ) 43 { 44 return 3600 * h + 60 * m + s; 45 46 } /* 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 Chapter 5 5.24 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: 1 /* Exercise 5.24 Solution */ 2 #include 3 4 int celcius( int fTemp ); /* function prototype */ 5 int fahrenheit( int cTemp ); /* function prototype */ 6 7 int main() 8{ 9 int i; /* loop counter */ 10 11 /* display table of Fahrenheit equivalents of Celsius temperature */ 12 printf( "Fahrenheit equivalents of Celcius temperatures:\n" ); 13 printf( "Celcius\t\tFahrenheit\n" ); 14 15 /* display Fahrenheit equivalents of Celsius 0 to 100 */ 16 for ( i = 0; i <= 100; i++ ) { 17 printf( "%d\t\t%d\n", i, fahrenheit( i ) ); 18 } /* end for */ 19 20 /* display table of Celsius equivalents of Fahrenheit temperature */ 21 printf( "\nCelcius equivalents of Fahrenheit temperatures:\n" ); 22 printf( "Fahrenheit\tCelcius\n" ); 23 24 /* display Celsius equivalents of Fahrenheit 32 to 212 */ 25 for ( i = 32; i <= 212; i++ ) { 26 printf( "%d\t\t%d\n", i, celcius( i ) ); 27 } /* end for */ 28 29 return 0; /* indicate successful termination */ 30 31 } /* end main */ 32 33 /* celsius returns Celsius equivalent of fTemp, 34 given in Fahrenheit */ 35 int celcius( int fTemp ) 36 { 37 return ( int ) ( 5.0 / 9.0 * ( fTemp - 32 ) ); 38 39 } /* end function celsius */ 40 41 /* fahrenheit returns Fahrenheit equivalent of cTemp, 42 given in Celsius */ 43 int fahrenheit( int cTemp ) 44 { 45 return ( int ) ( 9.0 / 5.0 * cTemp + 32 ); 46 47 } /* end function fahrenheit */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 . . . C Functions: Solutions 113 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 114 C Functions: Solutions 5.25 Write a function that returns the smallest of three floating point numbers. ANS: 1 /* Exercise 5.25 Solution */ 2 #include 3 4 /* function prototype */ 5 double smallest3( double a, double b, double c ); 6 7 int main() 8{ 9 double x; /* first input */ 10 double y; /* second input */ 11 double z; /* third input */ 12 13 printf( "Enter three doubleing point values: " ); 14 scanf( "%lf%lf%lf", &x, &y, &z ); 15 16 /* determine smallest value */ 17 printf( "The smallest value is %f\n", smallest3( x, y, z ) ); 18 19 return 0; /* indicate successful termination */ 20 21 } /* end main */ 22 23 /* smallest3 returns the smallest of a, b and c */ 24 double smallest3( double a, double b, double c ) 25 { 26 double smallest = a; /* assume a is the smallest */ 27 28 if ( b < smallest ) { /* if b is smaller */ 29 smallest = b; 30 } /* end if */ 31 32 if ( c < smallest ) { /* if c is smaller */ 33 smallest = c; 34 } /* end if */ 35 36 return smallest; /* return smallest value */ 37 38 } /* 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 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 115 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 /* Exercise 5.26 Solution */ 2 #include 3 4 int perfect( int value ); /* function prototype */ 5 6 int main() 7{ 8 int j; /* loop counter */ 9 10 printf( "For the integers from 1 to 1000:\n" ); 11 12 /* loop from 2 to 1000 */ 13 for ( j = 2; j <= 1000; j++ ) { 14 15 /* if current integer is perfect */ 16 if ( perfect( j ) ) { 17 printf( "%d is perfect\n", j ); 18 } /* end if */ 19 20 } /* end for */ 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ 25 26 /* perfect returns true if value is perfect integer, 27 i.e., if value is equal to sum of its factors */ 28 int perfect( int value ) 29 { 30 int factorSum = 1; /* current sum of factors */ 31 int i; /* loop counter */ 32 33 /* loop through possible factor values */ 34 for ( i = 2; i <= value / 2; i++ ) { 35 36 /* if i is factor */ 37 if ( value % i == 0 ) { 38 factorSum += i; /* add to sum */ 39 } /* end if */ 40 41 } /* end for */ 42 43 /* return true if value is equal to sum of factors */ 44 if ( factorSum == value ) { 45 return 1; 46 } /* end if */ 47 else { 48 return 0; 49 } /* end else */ 50 51 } /* 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 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 117 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 /* Exercise 5.27 Solution Part B Solution */ 2 #include 3 4 int prime( int n ); 5 6 int main() 7{ 8 int loop; /* loop counter */ 9 int count = 0; /* total number of primes found */ 10 11 printf( "The prime numbers from 1 to 10000 are:\n" ); 12 13 /* loop through 1 to 10000 */ 14 for ( loop = 1; loop <= 10000; loop++ ) { 15 16 /* if current number is prime */ 17 if ( prime( loop ) ) { 18 ++count; 19 printf( "%6d", loop ); 20 21 /* new line after 10 values displayed */ 22 if ( count % 10 == 0 ) { 23 printf( "\n" ); 24 } /* end if */ 25 26 } /* end if */ 27 28 } /* end for */ 29 30 return 0; /* indicate successful termination */ 31 32 } /* end main */ 33 34 /* prime returns 1 if n is prime */ 35 int prime( int n ) 36 { 37 int loop2; /* loop counter */ 38 39 /* loop through possible factors */ 40 for ( loop2 = 2; loop2 <= n / 2; loop2++ ) { 41 42 /* if factor found, not prime */ 43 if ( n % loop2 == 0 ) { 44 return 0; 45 } /* end if */ 46 47 } /* end for */ 48 49 return 1; /* return 1 if prime */ 50 51 } /* end function prime */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 118 C Functions: Solutions Chapter 5 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 17 59 103 157 9787 9859 9949 19 61 107 163 9791 9871 9967 23 67 109 167 9803 9883 9973 1 /* Exercise 5.27 Part C Solution */ 2 #include 3 #include 4 5 int prime( int n ); /* function prototype */ 6 7 int main() 8{ 9 int j; /* loop counter */ 10 int count = 0; /* total number of primes found */ 11 12 printf( "The prime numbers from 1 to 10000 are:\n" ); 13 14 /* loop through numbers 1 to 10000 */ 15 for ( j = 1; j <= 10000; j++ ) { 16 17 /* if current number prime */ 18 if ( prime( j ) ) { 19 ++count; 20 printf( "%5d", j ); 21 22 /* new line after 10 values displayed */ 23 if ( count % 10 == 0 ) { 24 printf( "\n" ); 25 } /* end if */ 26 27 } /* end if */ 28 29 } /* end for */ 30 31 return 0; /* indicate successful termination */ 32 33 } /* end main */ 34 35 /* prime returns 1 if n is prime */ 36 int prime( int n ) 37 { 38 int i; /* loop counter */ 39 40 /* loop through possible factors */ 41 for ( i = 2; i <= ( int ) sqrt( n ); i++ ) { 42 43 /* if factor found, not prime */ 44 if ( n % i == 0 ) { 45 return 0; 46 } /* end if */ 47 48 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 49 50 return 1; 51 52 } /* end function prime */ C Functions: Solutions 119 © 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 /* Exercise 5.28 Solution */ 2 #include 3 4 int reverseDigits( int n ); 5 6 int main() 7{ 8 int number; /* input number */ 9 10 printf( "Enter a number between 1 and 9999: " ); 11 scanf( "%d", &number ); 12 13 /* find number with digits reversed */ 14 printf( "The number with its digits reversed is: %d\n", 15 reverseDigits( number ) ); 16 17 return 0; /* indicate successful termination */ 18 19 } /* end main */ 20 21 /* reverseDigits returns number obtained by 22 reversing digits of n */ 23 int reverseDigits( int n ) 24 { 25 int reverse = 0; /* reversed number */ 26 int divisor = 1000; /* current divisor */ 27 int multiplier = 1; /* current multiplier */ 28 29 /* loop until single-digit number */ 30 while ( n > 9 ) { 31 32 /* if n >= current divisor, determine digit */ 33 if ( n >= divisor ) { 34 35 /* update reversed number with current digit */ 36 reverse += n / divisor * multiplier; 37 38 n %= divisor; /* update n */ 39 divisor /= 10; /* update divisor */ 40 multiplier *= 10; /* update multiplier */ 41 } /* end if */ 42 else { /* else, no digit */ 43 divisor /= 10; /* update divisor */ 44 } /* end else */ 45 46 } /* end while */ 47 48 reverse += n * multiplier; 49 50 return reverse; /* return reversed number */ 51 52 } /* 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. Chapter 5 Enter a number between 1 and 9999: 9273 The number with its digits reversed is: 3729 C Functions: Solutions 121 © 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 /* Exercise 5.29 Solution */ 2 #include 3 4 int gcd( int x, int y ); /* function prototype */ 5 6 int main() 7{ 8 int j; /* loop counter */ 9 int a; /* first number */ 10 int b; /* second number */ 11 12 /* loop for 5 pairs of inputs */ 13 for ( j = 1; j <= 5; j++ ) { 14 printf( "Enter two integers: " ); 15 scanf( "%d%d", &a, &b ); 16 17 /* find greatest common divisor of a and b */ 18 printf( "The greatest common divisor " 19 "of %d and %d is %d\n\n", a, b, gcd( a, b ) ); 20 } /* end for */ 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ 25 26 /* gcd find greatest common divisor of x and y */ 27 int gcd( int x, int y ) 28 { 29 int i; 30 int greatest = 1; /* current gcd, 1 is minimum */ 31 32 /* loop from 2 to smaller of x and y */ 33 for ( i = 2; i <= ( ( x < y ) ? x : y ); i++ ) { 34 35 /* if current i divides both x and y */ 36 if ( x % i == 0 && y % i == 0 ) { 37 greatest = i; /* update greatest common divisor */ 38 } /* end if */ 39 40 } /* end for */ 41 42 return greatest; /* return greatest common divisor found */ 43 44 } /* end function gcd */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 C Functions: Solutions 123 © 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 /* Exercise 5.30 Solution */ 2 #include 3 4 int qualityPoints( int average ); /* function prototype */ 5 6 int main() 7{ 8 int average; /* current average */ 9 int loop; /* loop counter */ 10 11 /* loop for 5 inputs */ 12 for ( loop = 1; loop <= 5; loop++ ) { 13 printf( "\nEnter the student's average: " ); 14 scanf( "%d", &average ); 15 16 /* determine and display corresponding quality points */ 17 printf( "%d on a 4 point scale is %d\n", 18 average, qualityPoints( average ) ); 19 } /* end for */ 20 21 return 0; /* indicate successful termination */ 22 23 } /* end main */ 24 25 /* qualityPoints takes average in range 0 to 100 and 26 returns corresponding quality points on 0 to 4 scale */ 27 int qualityPoints( int average ) 28 { 29 30 /* 90 <= average <= 100 */ 31 if ( average >= 90 ) { 32 return 4; 33 } /* end if */ 34 else if ( average >= 80 ) { /* 80 <= average <= 89 */ 35 return 3; 36 } /* end else if */ 37 else if ( average >= 70 ) { /* 70 <= average <= 79 */ 38 return 2; 39 } /* end else if */ 40 else if ( average >= 60 ) { /* 60 <= average <= 69 */ 41 return 1; 42 } /* end else if */ 43 else { /* 0 <= average < 60 */ 44 return 0; 45 } /* end else */ 46 47 } /* end function qualityPoints */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 C Functions: Solutions 125 © 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 /* Exercise 5.31 Solution */ 2 #include 3 #include 4 #include 5 6 int flip(); /* function prototype */ 7 8 int main() 9{ 10 int loop; /* loop counter */ 11 int headCount = 0; /* total Heads count */ 12 int tailCount = 0; /* total Tails count */ 13 14 srand( time( NULL ) ); /* seed random number generator */ 15 16 /* simulate coin toss 100 times */ 17 for ( loop = 1; loop <= 100; loop++ ) { 18 19 /* simulate coin toss, 0 refers to tails */ 20 if ( flip() == 0 ) { 21 tailCount++; /* update Tails count */ 22 } /* end if */ 23 else { 24 headCount++; /* update Heads count */ 25 } /* end else */ 26 27 if ( loop % 10 == 0 ) { 28 printf( "\n" ); 29 } /* end if */ 30 31 } /* end for */ 32 33 /* display totals */ 34 printf( "\nThe total number of Heads was %d\n", headCount ); 35 printf( "The total number of Tails was %d\n", tailCount ); 36 37 return 0; /* indicate successful termination */ 38 39 } /* end main */ 40 41 /* flip uses random number to simulate coin toss */ 42 int flip() { 43 int HorT = rand() %2; /* scale by 2 for binary result */ 44 45 /* display result of flip */ 46 if ( HorT == 0 ) { 47 printf( "Tails " ); 48 } /* end if */ 49 else { 50 printf( "Heads " ); 51 } /* end else */ 52 53 return HorT; /* return result of coin toss */ 54 55 } /* end function flip */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 Tails Heads Tails Tails Tails Tails Heads Tails Tails Tails Tails Tails Tails Heads Tails Heads Tails Tails Heads Tails Tails Heads Heads Tails Tails Heads Tails Tails Tails Tails Tails Tails Heads Heads Heads Heads Heads Heads Tails Tails Heads Heads Heads Heads Heads Tails Tails Tails Tails Tails Tails Tails Tails Heads Heads Tails Tails Tails Tails Heads Tails Tails Tails Heads Heads Tails Tails Heads Tails Tails Heads Tails Tails Heads Tails Tails Tails Tails Heads Tails Tails Tails Tails Tails Heads Tails Heads Heads Tails Tails Heads Tails Tails Heads Tails Tails Heads Tails Tails Tails The total number of Heads was 34 The total number of Tails was 66 C Functions: Solutions 127 © 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 /* Exercise 5.32 solution */ 2 #include 3 #include 4 #include 5 6 void multiplication( void ); /* function prototype */ 7 8 int main( void ) 9{ 10 srand( time( NULL ) ); /* seed random number generator */ 11 multiplication(); /* begin multiplication practice */ 12 13 return 0; /* indicate successful termination */ 14 15 } /* end main */ 16 17 /* multiplication produces pairs of random numbers and 18 prompts user for product */ 19 void multiplication( void ) 20 { 21 int x; /* first factor */ 22 int y; /* second factor */ 23 int response = 0; /* user response for product */ 24 25 /* use sentinel-controlled repetition */ 26 printf( "Enter -1 to end.\n" ); 27 28 /* loop while sentinel value not read from user */ 29 while ( response != -1 ) { 30 x = rand() % 10; /* generate 1-digit random number */ 31 y = rand() % 10; /* generate another 1-digit random number */ 32 33 printf( "How much is %d times %d? ", x, y ); 34 scanf( "%d", &response ); 35 36 /* loop while not sentinel value or correct response */ 37 while ( response != -1 && response != x * y ) { 38 printf( "No. Please try again.\n? " ); 39 scanf( "%d", &response ); 40 } /* end while */ 41 42 /* correct response */ 43 if ( response != -1 ) { 44 printf( "Very good!\n\n" ); 45 } /* end if */ 46 47 } /* end while */ 48 49 printf( "That's all for now. Bye.\n" ); 50 51 } /* end function multiplication */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. C Functions: Solutions 129 © 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 /* Exercise 5.33 Solution */ 2 #include 3 #include 4 #include 5 6 void correctMessage( void ); /* function prototype */ 7 void incorrectMessage( void ); /* function prototype */ 8 void multiplication( void ); /* function prototype */ 9 10 int main() 11 { 12 srand( time( NULL ) ); /* seed random number generator */ 13 multiplication(); /* begin multiplication practice */ 14 15 return 0; /* indicate successful termination */ 16 17 } /* end main */ 18 19 /* correctMessage randomly chooses response to correct answer */ 20 void correctMessage( void ) 21 { 22 23 /* generate random number between 0 and 3 */ 24 switch ( rand() % 4 ) { 25 26 /* display a random response */ 27 case 0: 28 printf( "Very good!\n\n" ); 29 break; /* exit switch */ 30 31 case 1: 32 printf( "Excellent!\n\n" ); 33 break; /* exit switch */ 34 35 case 2: 36 printf( "Nice work!\n\n" ); 37 break; /* exit switch */ 38 39 case 3: 40 printf( "Keep up the good work!\n\n" ); 41 break; /* exit switch */ 42 } /* end switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 131 43 44 } /* end function correctMessage */ 45 46 /* incorrectMessage randomly chooses response to incorrect answer */ 47 void incorrectMessage( void ) 48 { 49 50 /* generate random number between 0 and 3 */ 51 switch ( rand() % 4 ) { 52 53 /* display random response */ 54 case 0: 55 printf( "No. Please try again.\n? " ); 56 break; /* exit switch */ 57 58 case 1: 59 printf( "Wrong. Try once more.\n? " ); 60 break; /* exit switch */ 61 62 case 2: 63 printf( "Don't give up!\n? " ); 64 break; /* exit switch */ 65 66 case 3: 67 printf( "No. Keep trying.\n? " ); 68 break; /* exit switch */ 69 } /* end switch */ 70 71 } /* end function incorrectMessage */ 72 73 /* multiplication produces pairs of random numbers and 74 prompts user for product */ 75 void multiplication( void ) 76 { 77 int x; /* first factor */ 78 int y; /* second factor */ 79 int response = 0; /* user response for product */ 80 81 /* use sentinel-controlled repetition */ 82 printf( "Enter -1 to end.\n" ); 83 84 /* loop while sentinel value not read from user */ 85 while ( response != -1 ) { 86 x = rand() % 10; /* generate 1-digit random number */ 87 y = rand() % 10; /* generate another 1-digit random number */ 88 89 printf( "How much is %d times %d? ", x, y ); 90 scanf( "%d", &response ); 91 92 /* loop while not sentinel value or correct response */ 93 while ( response != -1 && response != x * y ) { 94 incorrectMessage(); 95 scanf( "%d", &response ); 96 } /* end while */ 97 98 /* correct response */ 99 if ( response != -1 ) { 100 correctMessage(); 101 } /* end if */ 102 103 } /* 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. Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 133 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 /* Exercise 5.34 Solution */ 2 #include 3 #include 4 #include 5 6 void multiplication( void ); /* function prototype */ 7 void correctMessage( void ); /* function prototype */ 8 void incorrectMessage( void ); /* function prototype */ 9 10 int main() 11 { 12 srand( time( NULL ) ); /* seed random number generator */ 13 multiplication(); /* begin multiplication practice */ 14 15 return 0; /* indicate successful termination */ 16 17 } /* end main */ 18 19 /* multiplication produces pairs of random numbers and 20 prompts user for product */ 21 void multiplication( void ) 22 { 23 int i; /* loop counter */ 24 int x; /* first factor */ 25 int y; /* second factor */ 26 int response; /* user response for product */ 27 int right = 0; /* total number of right responses */ 28 int wrong = 0; /* total number of wrong responses */ 29 30 /* loop 10 times */ 31 for ( i = 1; i <= 10; i++ ) { 32 x = rand() % 10; /* generate 1-digit random number */ 33 y = rand() % 10; /* generate another 1-digit random number */ 34 35 printf( "How much is %d times %d? ", x, y ); 36 scanf( "%d", &response ); 37 38 /* loop while not correct response */ 39 while ( response != x * y ) { 40 wrong++; /* update total number of wrong responses */ 41 incorrectMessage(); 42 scanf( "%d", &response ); 43 } /* end while */ 44 45 right++; /* update total number of correct responses */ 46 correctMessage(); 47 } /* end for */ 48 49 /* determine if help is needed */ 50 if ( ( double ) right / ( right + wrong ) < .75 ) { 51 printf( "Please ask your instructor for extra help.\n" ); 52 } /* end if */ 53 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 134 C Functions: Solutions 54 printf( "That's all for now. Bye.\n" ); 55 } /* end function multiplication */ 56 57 /* correctMessage randomly chooses response to correct answer */ 58 void correctMessage( void ) 59 { 60 61 /* generate random number between 0 and 3 */ 62 switch ( rand() % 4 ) { 63 64 /* display random response */ 65 case 0: 66 printf( "Very good!\n\n" ); 67 break; /* exit switch */ 68 69 case 1: 70 printf( "Excellent!\n\n" ); 71 break; /* exit switch */ 72 73 case 2: 74 printf( "Nice work!\n\n" ); 75 break; /* exit switch */ 76 77 case 3: 78 printf( "Keep up the good work!\n\n" ); 79 break; /* exit switch */ 80 } /* end switch */ 81 82 } /* end function correctMessage */ 83 84 /* incorrectMessage randomly chooses response to incorrect answer */ 85 void incorrectMessage( void ) 86 { 87 88 /* generate random number between 0 and 3 */ 89 switch ( rand() % 4 ) { 90 91 /* display random response */ 92 case 0: 93 printf( "No. Please try again.\n? " ); 94 break; /* exit switch */ 95 96 case 1: 97 printf( "Wrong. Try once more.\n? " ); 98 break; /* exit switch */ 99 100 case 2: 101 printf( "Don't give up!\n? " ); 102 break; /* exit switch */ 103 104 case 3: 105 printf( "No. Keep trying.\n? " ); 106 break; /* exit switch */ 107 } /* end switch */ 108 109 } /* end function incorrectMessage */ Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. C Functions: Solutions 135 © 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 /* Exercise 5.35 solution */ 2 #include 3 #include 4 #include 5 6 void guessGame( void ); /* function prototype */ 7 8 int main() 9{ 10 srand( time( NULL ) ); /* seed random number generator */ 11 guessGame(); 12 13 return 0; /* indicate successful termination */ 14 15 } /* end main */ 16 17 /* guessGame generates numbers between 1 and 1000 18 and checks user's guess */ 19 void guessGame( void ) 20 { 21 int x; /* randomly generated number */ 22 int guess; /* user's guess */ 23 int response; /* response to continue game, 1=yes, 2=no */ 24 25 /* loop until user types 2 to quit game */ 26 do { 27 28 /* generate random number between 1 and 1000 29 1 is shift, 1000 is scaling factor */ 30 x = 1 + rand() % 1000; 31 32 /* prompt for guess */ 33 printf( "\nI have a number between 1 and 1000.\n" ); 34 printf( "Can you guess my number?\n" ); 35 printf( "Please type your first guess.\n? " ); 36 scanf( "%d", &guess ); 37 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 38 /* loop until correct number */ 39 while ( guess != x ) { 40 41 /* if guess is too low */ 42 if ( guess < x ) { 43 printf( "Too low. Try again.\n? " ); 44 } /* end if */ 45 else { /* guess is too high */ 46 printf( "Too high. Try again.\n? " ); 47 } /* end else */ 48 49 scanf( "%d", &guess ); 50 } /* end while */ 51 52 /* prompt for another game */ 53 printf( "\nExcellent! You guessed the number!\n" ); 54 printf( "Would you like to play again?\n" ); 55 printf( "Please type ( 1=yes, 2=no )? " ); 56 scanf( "%d", &response ); 57 } while ( response == 1 ); /* end do...while */ 58 59 } /* 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 C Functions: Solutions 137 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 138 C Functions: Solutions Chapter 5 5.36 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 /* Exercise 5.36 Solution */ 2 #include 3 #include 4 #include 5 6 void guessGame( void ); /* function prototype */ 7 8 int main() 9{ 10 srand( time( NULL ) ); /* seed random number generator */ 11 guessGame(); 12 13 return 0; /* indicate successful termination */ 14 15 } /* end main */ 16 17 /* guessGame generates numbers between 1 and 1000 18 and checks user's guess */ 19 void guessGame( void ) 20 { 21 int x; /* randomly generated number */ 22 int guess; /* user's guess */ 23 int total = 1; /* number of guesses */ 24 int response; /* response to continue game, 1=yes, 0=no */ 25 26 /* loop until user enters 0 to quit game */ 27 do { 28 29 /* generate random number between 1 and 1000 30 1 is shift, 1000 is scaling factor */ 31 x = 1 + rand() % 1000; 32 33 /* prompt for guess */ 34 printf( "\nI have a number between 1 and 1000.\n" ); 35 printf( "Can you guess my number?\n" ); 36 printf( "Please type your first guess.\n? " ); 37 scanf( "%d", &guess ); 38 39 /* loop while not correct answer */ 40 while ( guess != x ) { 41 42 /* guess is incorrect; display hint */ 43 if ( guess < x ) { 44 printf( "Too low. Try again.\n? " ); 45 } /* end if */ 46 else { 47 printf( "Too high. Try again.\n? " ); 48 } /* end else */ 49 50 scanf( "%d", &guess ); 51 total++; 52 } /* end while */ 53 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 139 54 printf( "\nExcellent! You guessed the number!\n" ); 55 56 /* determine if user knows "secret" */ 57 if ( total < 10 ) { 58 printf( "Either you know the secret or you got lucky!\n" ); 59 } /* end if */ 60 else if ( total == 10 ) { 61 printf( "Ahah! You know the secret!\n" ); 62 } /* end else if */ 63 else { 64 printf( "You should be able to do better!\n\n" ); 65 } /* end else */ 66 67 /* prompt for another game */ 68 printf( "Would you like to play again?\n" ); 69 printf( "Please type ( 1=yes, 2=no )? " ); 70 scanf( "%d", &response ); 71 } while ( response == 1 ); /* end do...while */ 72 73 } /* 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 Chapter 5 5.37 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 /* Exercise 5.37 Solution */ 2 #include 3 4 long power( long base, long exponent ); /* function prototype */ 5 6 int main() 7{ 8 long b; /* base */ 9 long e; /* exponent */ 10 11 printf( "Enter a base and an exponent: " ); 12 scanf( "%ld%ld", &b, &e ); 13 14 /* calculate and display b raised to the e power */ 15 printf( "%ld raised to the %ld is %ld\n", b, e, power( b, e ) ); 16 17 return 0; /* indicate successful termination */ 18 19 } /* end main */ 20 21 /* power recursively calculates base raised to the exponent 22 assume exponent >= 1 */ 23 long power( long base, long exponent ) 24 { 25 26 /* base case: exponent equals 1, return base */ 27 if ( exponent == 1 ) { 28 return base; 29 } /* end if */ 30 else { /* recursive step */ 31 return base * power( base, exponent - 1 ); 32 } /* end else */ 33 34 } /* 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. Chapter 5 C Functions: Solutions 141 ANS: 1 /* Exercise 5.38 Part A Solution */ 2 #include 3 #define MAX 23 /* the maximum number for which the */ 4 /* fibonacci value can be calculated */ 5 /* on 2-byte integer systems */ 6 int fibonacci( int n ); 7 8 int main() 9{ 10 int loop; /* loop counter */ 11 12 /* calculate and display Fibonacci value for 0 to MAX */ 13 for ( loop = 0; loop <= MAX; loop++ ) { 14 printf( "fibonacci( %d ) = %d\n", loop, fibonacci( loop ) ); 15 } /* end for */ 16 17 return 0; /* indicate successful termination */ 18 19 } /* end main */ 20 21 /* fibonacci nonrecursively calculates nth Fibonacci number */ 22 int fibonacci( int n ) 23 { 24 int j; /* loop counter */ 25 int fib[ MAX ]; /* define array of size MAX */ 26 27 fib[ 0 ] = 0; 28 fib[ 1 ] = 1; 29 30 /* loop to find nth Fibonacci value */ 31 for ( j = 2; j <= n; j++ ) { 32 fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ]; 33 } /* end for */ 34 35 return fib[ n ]; /* return nth Fibonacci value */ 36 37 } /* end function fibonacci */ fibonacci( 0 ) = 0 fibonacci( 1 ) = 1 fibonacci( 2 ) = 1 fibonacci( 3 ) = 2 fibonacci( 4 ) = 3 fibonacci( 5 ) = 5 fibonacci( 6 ) = 8 fibonacci( 7 ) = 13 fibonacci( 8 ) = 21 fibonacci( 9 ) = 34 fibonacci( 10 ) = 55 fibonacci( 11 ) = 89 fibonacci( 12 ) = 144 fibonacci( 13 ) = 233 fibonacci( 14 ) = 377 fibonacci( 15 ) = 610 fibonacci( 16 ) = 987 fibonacci( 17 ) = 1597 fibonacci( 18 ) = 2584 fibonacci( 19 ) = 4181 fibonacci( 20 ) = 6765 fibonacci( 21 ) = 10946 fibonacci( 22 ) = 17711 fibonacci( 23 ) = 28658 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 142 C Functions: Solutions 1 /* Exercise 5.38 Part B Solution */ 2 #include 3 #define SIZE 100 4 5 double fibonacci( int n ); /* function prototype */ 6 7 int main() 8{ 9 int loop; /* loop counter */ 10 11 /* loop SIZE times and calculate Fibonacci values */ 12 for ( loop = 0; loop < SIZE; loop++ ) { 13 printf( "fibonacci( %d ) = %.1f\n", loop, fibonacci( loop ) ); 14 } /* end for */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* fibonacci nonrecursively calculates nth Fibonacci number */ 21 double fibonacci( int n ) 22 { 23 int j; /* loop counter */ 24 double fib[ SIZE ]; /* define double array of size SIZE */ 25 26 fib[ 0 ] = 0.0; 27 fib[ 1 ] = 1.0; 28 29 /* loop to find nth Fibonacci value */ 30 for ( j = 2; j <= n; j++ ) { 31 fib[ j ] = fib[ j - 1 ] + fib[ j - 2 ]; 32 } /* end for */ 33 34 return fib[ n ]; /* return nth Fibonacci value */ 35 36 } /* end function fibonacci */ fibonacci( 0 ) = 0.0 fibonacci( 1 ) = 1.0 fibonacci( 2 ) = 1.0 fibonacci( 3 ) = 2.0 fibonacci( 4 ) = 3.0 fibonacci( 5 ) = 5.0 fibonacci( 6 ) = 8.0 fibonacci( 7 ) = 13.0 fibonacci( 8 ) = 21.0 fibonacci( 9 ) = 34.0 fibonacci( 10 ) = 55.0 fibonacci( 11 ) = 89.0 fibonacci( 12 ) = 144.0 . . . fibonacci( 96 ) = 51680708854858326000.0 fibonacci( 97 ) = 83621143489848426000.0 fibonacci( 98 ) = 135301852344706760000.0 fibonacci( 99 ) = 218922995834555200000.0 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 143 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 ANS: 1 /* Exercise 5.39 solution */ 2 #include 3 4 /* function prototype */ 5 void tower( int c, int start, int end, int temp ); 6 7 int main() 8{ 9 int n; /* number of disks */ 10 11 printf( "Enter the starting number of disks: " ); 12 scanf( "%d", &n ); 13 14 /* print instructions for moving disks from 15 peg 1 to peg 3 using peg 2 for temporary storage */ 16 tower( n, 1, 3, 2 ); 17 18 return 0; /* indicate successful termination */ 19 20 } /* end main */ 21 22 /* tower recursively prints instructions for moving disks 23 from start peg to end peg using temp peg for temporary storage */ 24 void tower( int c, int start, int end, int temp ) 25 { 26 27 /* base case */ 28 if ( c == 1 ) { 29 printf( "%d --> %d\n", start, end ); 30 return; 31 } /* end if */ 32 33 /* move c - 1 disks from start to temp */ 34 tower( c - 1, start, temp, end ); 35 36 /* move last disk from start to end */ 37 printf( "%d --> %d\n", start, end ); 38 39 /* move c - 1 disks from temp to end */ 40 tower( c - 1, temp, end, start ); 41 } /* end function tower */ Enter the starting number of disks: 4 1 --> 2 1 --> 3 2 --> 3 1 --> 2 3 --> 1 3 --> 2 1 --> 2 1 --> 3 2 --> 3 2 --> 1 3 --> 1 2 --> 3 1 --> 2 1 --> 3 2 --> 3 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 145 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 /* Exercise 5.41 Solution */ 2 #include 3 4 long factorial( long number ); /* function prototype */ 5 void printRecursion( int n ); /* function prototype */ 6 7 int main() 8{ 9 int i; /* loop counter */ 10 11 /* calculate factorial( i ) and display result */ 12 for ( i = 0; i <= 10; i++ ) { 13 printf( "%2d! = %ld\n", i, factorial( i ) ); 14 } /* end for */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* recursive definition of function factorial */ 21 long factorial( long number ) 22 { 23 24 /* base case */ 25 if ( number <= 1 ) { 26 return 1; 27 } /* end if */ 28 else { /* recursive step */ 29 printRecursion( number ); /* add outputs and indentation */ 30 return ( number * factorial( number - 1 ) ); 31 } /* end else */ 32 33 } /* end function factorial */ 34 35 /* printRecursion adds outputs and indentation to help 36 visualize recursion */ 37 void printRecursion( int n ) 38 { 39 printf( "number = %*d\n", n, n ); 40 } /* 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 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 147 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 /* Exercise 5.42 Solution */ 2 #include 3 4 /* function prototype */ 5 unsigned int gcd( unsigned int xMatch, unsigned int yMatch ); 6 7 int main() 8{ 9 unsigned int x; /* first integer */ 10 unsigned int y; /* second integer */ 11 unsigned int gcDiv; /* greatest common divisor of x and y */ 12 13 printf( "Enter two integers: " ); 14 scanf( "%u%u", &x, &y ); 15 16 gcDiv = gcd( x, y ); 17 18 printf( "Greatest common divisor of %u and %u is %u\n", 19 x, y, gcDiv ); 20 21 return 0; /* indicate successful termination */ 22 23 } /* end main */ 24 25 /* gcd recursively finds greatest common divisor 26 of xMatch and yMatch */ 27 unsigned int gcd( unsigned int xMatch, unsigned int yMatch ) 28 { 29 30 /* base case */ 31 if ( yMatch == 0 ) { 32 return xMatch; 33 } /* end if */ 34 else { /* recursive step */ 35 return gcd( yMatch, xMatch % yMatch ); 36 } /* end else */ 37 38 } /* 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 /* Exercise 5.43 Solution */ 2 #include 3 4 int main() 5{ 6 static int count = 1; /* static local variable count */ 7 8 printf( "%d\n", count ); 9 count++; 10 11 main(); /* recursively call int main() */ 12 13 return 0; /* indicate successful termination */ 14 15 } /* 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. Chapter 5 C Functions: Solutions 149 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 /* Exercise 5.44 Part A Solution */ 2 #include 3 #include 4 #include 5 6 int randValue( int level ); /* function prototype */ 7 void multiplication( void ); /* function prototype */ 8 void correctMessage( void ); /* function prototype */ 9 void incorrectMessage( void ); /* function prototype */ 10 11 int main() 12 { 13 srand( time( NULL ) ); /* seed random number generator */ 14 multiplication(); /* being multiplication practice */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* randValue generates random numbers based on grade level */ 21 int randValue( int level ) 22 { 23 24 /* level determines size of random number */ 25 switch ( level ) { 26 27 case 1: 28 return rand() % 10; 29 30 case 2: 31 return rand() % 100; 32 33 case 3: 34 return rand() % 1000; 35 36 default: 37 return rand() % 10; 38 } /* end switch */ 39 40 } /* end function randValue */ 41 42 /* multiplication produces pairs of random numbers and 43 prompts user for product; level determines size of numbers */ 44 void multiplication( void ) 45 { 46 int i; /* loop counter */ 47 int x; /* first factor */ 48 int y; /* second factor */ 49 int gradeLevel; /* grade-level capability */ 50 int right = 0; /* total number of right responses */ 51 int wrong = 0; /* total number of wrong responses */ 52 unsigned int response; /* user response for product */ 53 54 printf( "Enter the grade-level ( 1 to 3 ): " ); 55 scanf( "%d", &gradeLevel ); 56 57 /* loop 10 times */ 58 for ( i = 1; i <= 10; i++ ) { 59 60 /* generate random numbers depending on level */ 61 x = randValue( gradeLevel ); © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 150 C Functions: Solutions Chapter 5 62 y = randValue( gradeLevel ); 63 64 printf( "How much is %d times %d? ", x, y ); 65 scanf( "%u", &response ); 66 67 /* loop while response is incorrect */ 68 while ( response != x * y ) { 69 ++wrong; /* update total number of wrong answers */ 70 incorrectMessage(); 71 scanf( "%u", &response ); 72 } /* end while */ 73 74 ++right; /* update total number of right answers */ 75 correctMessage(); 76 } /* end for */ 77 78 /* if < 75% right */ 79 if ( ( double ) right / ( right + wrong) < .75 ) { 80 printf( "Please ask your instructor for extra help.\n" ); 81 } /* end if */ 82 83 printf( "That's all for now. Bye.\n" ); 84 } /* end function multiplication */ 85 86 /* correctMessage randomly chooses response to correct answer */ 87 void correctMessage( void ) 88 { 89 90 /* generate random number between 0 and 3 */ 91 switch ( rand() % 4 ) { 92 93 case 0: 94 printf( "Very good!\n\n" ); 95 break; /* exit switch */ 96 97 case 1: 98 printf( "Excellent!\n\n" ); 99 break; /* exit switch */ 100 101 case 2: 102 printf( "Nice work!\n\n" ); 103 break; /* exit switch */ 104 105 case 3: 106 printf( "Keep up the good work!\n\n" ); 107 break; /* exit switch */ 108 } /* end switch */ 109 110 } /* end function correctMessage */ 111 112 /* incorrectMessage randomly chooses response to incorrect answer */ 113 void incorrectMessage( void ) 114 { 115 116 /* generate random number between 0 and 3 */ 117 switch ( rand() % 4 ) { 118 119 case 0: 120 printf( "No. Please try again.\n? " ); 121 break; /* exit switch */ 122 123 case 1: 124 printf( "Wrong. Try once more.\n? " ); 125 break; /* exit switch */ 126 127 case 2: 128 printf( "Don't give up!\n? " ); 129 break; /* exit switch */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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! ... C Functions: Solutions 151 © 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 /* Exercise 5.44 Part B Solution */ 2 #include 3 #include 4 #include 5 6 int menu( void ); /* function prototype */ 7 void arithmetic( void ); /* function prototype */ 8 void correctMessage( void ); /* function prototype */ 9 void incorrectMessage( void ); /* function prototype */ 10 11 int main() 12 { 13 srand( time( NULL ) ); /* seed random number generator */ 14 arithmetic(); /* begin arithmetic process */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* menu displays user menu of choices */ 21 int menu( void ) 22 { 23 int choice; /* user's choice */ 24 25 /* display menu and read user's choice */ 26 do { 27 printf( "Choose type of problem to study.\n" ); 28 printf( "Enter: 1 for addition, 2 for subtraction\n" ); 29 printf( "Enter: 3 for multiplication, 4 for division\n" ); 30 printf( "Enter: 5 for a combination of 1 through 4\n " ); 31 printf( "? " ); 32 scanf( "%d", &choice ); 33 } while ( choice < 1 || choice > 5 ); /* end do...while */ 34 35 return choice; /* return user's choice */ 36 37 } /* end function menu */ 38 39 /* incorrectMessage randomly chooses response to incorrect answer */ 40 void incorrectMessage( void ) 41 { 42 43 /* generate random number between 0 and 3 */ 44 switch ( rand() % 4 ) { 45 46 case 0: 47 printf( "No. Please try again.\n? " ); 48 break; /* exit switch */ 49 50 case 1: 51 printf( "Wrong. Try once more.\n? " ); 52 break; /* exit switch */ 53 54 case 2: 55 printf( "Don't give up!\n? " ); 56 break; /* exit switch */ 57 58 case 3: 59 printf( "No. Keep trying.\n? " ); 60 break; /* exit switch */ 61 } /* end switch */ 62 63 } /* end function incorrectMessage */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 153 64 65 /* correctMessage randomly chooses response to correct answer */ 66 void correctMessage( void ) 67 { 68 69 /* generate random number between 0 and 3 */ 70 switch ( rand() % 4 ) { 71 72 case 0: 73 printf( "Very good!\n\n" ); 74 break; /* exit switch */ 75 76 case 1: 77 printf( "Excellent!\n\n" ); 78 break; /* exit switch */ 79 80 case 2: 81 printf( "Nice work!\n\n" ); 82 break; /* exit switch */ 83 84 case 3: 85 printf( "Keep up the good work!\n\n" ); 86 break; /* exit switch */ 87 } /* end switch */ 88 89 } /* end function correctMessage */ 90 91 92 void arithmetic( void ) 93 { 94 int i; /* loop counter */ 95 int x; /* first number */ 96 int y; /* second number */ 97 int response; /* user response for product */ 98 int answer; /* correct answer */ 99 int selection; /* menu selection */ 100 int right = 0; /* total correct responses */ 101 int wrong = 0; /* total incorrect responses */ 102 int type; /* type of problems chosen */ 103 int problemMix; /* random choice of type of problem */ 104 char operator; /* arithmetic operator */ 105 106 selection = menu(); 107 type = selection; 108 109 /* loop 10 times */ 110 for ( i = 1; i <= 10; i++ ) { 111 x = rand() % 10; /* generate first random number */ 112 y = rand() % 10; /* generate second random number */ 113 114 /* if option 5, randomly select type */ 115 if ( selection == 5 ) { 116 problemMix = 1 + rand() % 4; 117 type = problemMix; 118 } /* end if */ 119 120 /* generate answer and define operator depending on option */ 121 switch ( type ) { 122 123 /* option 1: addition */ 124 case 1: 125 operator = '+'; 126 answer = x + y; 127 break; /* exit switch */ 128 129 /* option 2: subtraction */ 130 case 2: 131 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 */ Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. C Functions: Solutions 155 © 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 /* Exercise 5.45 Solution */ 2 #include 3 #include 4 5 /* function prototype */ 6 double distance( double xOne, double yOne, double xTwo, double yTwo ); 7 8 int main() 9{ 10 double x1; /* x coordinate of first point */ 11 double y1; /* y coordinate of first point */ 12 double x2; /* x coordinate of second point */ 13 double y2; /* y coordinate of second point */ 14 double dist; /* distance between two points */ 15 16 /* prompt for first point coordinates */ 17 printf( "Enter the first point: " ); 18 scanf( "%lf%lf", &x1, &y1 ); 19 20 /* prompt for second point coordinates */ 21 printf( "Enter the second point: " ); 22 scanf( "%lf%lf", &x2, &y2 ); 23 24 dist = distance( x1, y1, x2, y2 ); /* calculate distance */ 25 26 printf( "Distance between ( %.2f, %.2f )" 27 " and ( %.2f, %.2f ) is %.2f\n", 28 x1, y1, x2, y2, dist ); 29 30 return 0; /* indicate successful termination */ 31 32 } /* end main */ 33 34 /* distance calculates distance between 2 points 35 given by (xOne, yOne) and (xTwo, yTwo) */ 36 double distance( double xOne, double yOne, double xTwo, double yTwo ) 37 { 38 double distance; /* distance between two points */ 39 40 distance = sqrt( pow( xOne - xTwo, 2 ) + pow( yOne - yTwo, 2 ) ); 41 42 return distance; 43 44 } /* 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. Chapter 5 C Functions: Solutions 157 5.46 What does the following program do? 1 #include 2 3 /* function main begins program execution */ 4 int main() 5{ 6 int c; /* variable to hold character input by user */ 7 8 if ( ( c = getchar() ) != EOF ) { 9 main(); 10 printf( "%c", c ); 11 } /* end if */ 12 13 return 0; /* indicates successful termination */ 14 15 } /* 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. abc cba © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 158 C Functions: Solutions 5.47 What does the following program do? 1 #include 2 3 int mystery( int a, int b ); /* function prototype */ 4 5 /* function main begins program execution */ 6 int main() 7{ 8 int x; /* first integer */ 9 int y; /* second integer */ 10 11 printf( "Enter two integers: " ); 12 scanf( "%d%d", &x, &y ); 13 14 printf( "The result is %d\n", mystery( x, y ) ); 15 16 return 0; /* indicates successful termination */ 17 18 } /* end main */ 19 20 /* Parameter b must be a positive integer 21 to prevent infinite recursion */ 22 int mystery( int a, int b ) 23 { 24 /* base case */ 25 if ( b == 1 ) { 26 return a; 27 } /* end if */ 28 else { /* recursive step */ 29 return a + mystery( a, b - 1 ); 30 } /* end else */ 31 32 } /* end function mystery */ ANS: The problem mimics multiplication by adding up a, b times. Enter two integers: 87 6 The result is 522 Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 159 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 /* Exercise 5.48 Solution */ 2 #include 3 4 int mystery( int a, int b ); /* function prototype */ 5 6 int main() 7{ 8 int x; /* first integer */ 9 int y; /* second integer */ 10 11 printf( "Enter two integers: " ); 12 scanf( "%d%d", &x, &y ); 13 14 printf( "The result is %d\n", mystery( x, y ) ); 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* mystery multiplies a * b using recursion */ 21 int mystery( int a, int b ) 22 { 23 24 /* if a and b or just b are negative */ 25 if ( ( a < 0 && b < 0 ) || b < 0 ) { 26 a *= -1; /* multiply a and b by -1 to make positive */ 27 b *= -1; 28 } /* end if */ 29 30 /* base case */ 31 if ( b == 1 ) { 32 return a; 33 } /* end if */ 34 else { /* recursive step */ 35 return a + mystery( a, b - 1 ); 36 } /* end else */ 37 38 } /* 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 /* Exercise 5.49 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 int loop; /* integer loop counter */ 8 int count; /* loop counter */ 9 double loop2; /* double loop counter */ 10 11 /* loop and test each math function */ 12 for ( count = 1; count < 14; count++) { 13 14 /* test math function based on count */ 15 switch ( count ) { 16 17 /* print table headers */ 18 case 1: 19 printf( "funct " ); 20 21 for ( loop = 1; loop < 6; loop++ ) { 22 printf( "%10d ", loop ); 23 } /* end for */ 24 25 break; /* exit switch */ 26 27 /* display sqrt for range of values */ 28 case 2: 29 printf( "\nsqrt() " ); 30 31 for ( loop = 1; loop < 6; loop++ ) { 32 printf( "%10.2lf ", sqrt( loop ) ); 33 } /* end for */ 34 35 break; /* exit switch */ 36 37 /* display exp for range of values */ 38 case 3: 39 printf( "exp() " ); 40 41 for ( loop = 1; loop < 6; loop++ ) { 42 printf( "%10.2lf ", exp( loop ) ); 43 } /* end for */ 44 45 break; /* exit switch */ 46 47 /* display natural log for range of values */ 48 case 4: 49 printf( "log() " ); 50 51 for ( loop = 1; loop < 6; loop++ ) { 52 printf( "%10.2lf ", log( loop ) ); 53 } /* end for */ 54 55 break; /* exit switch */ 56 57 /* display log base 10 for range of values */ 58 case 5: 59 printf( "log10() " ); 60 61 for ( loop = 1; loop < 6; loop++ ) { 62 printf( "%10.2lf ", log10( loop ) ); 63 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 161 64 65 break; /* exit switch */ 66 67 /* display pow function, test with 2 as base */ 68 case 6: 69 printf( "pow( 2,x )" ); 70 71 for ( loop = 1; loop < 6; loop++ ) { 72 printf( "%10.2lf ", pow( 2, loop ) ); 73 } /* end for */ 74 75 break; /* exit switch */ 76 77 /* display table headers */ 78 case 7: 79 printf( "\n\nfunct " ); 80 81 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 82 printf( "%10.2lf ", loop2 ); 83 } /* end for */ 84 85 break; /* exit switch */ 86 87 /* display fabs for range of values */ 88 case 8: 89 printf( "\nfabs() " ); 90 91 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 92 printf( "%10.2lf ", fabs( loop2 ) ); 93 } /* end for */ 94 95 break; /* exit switch */ 96 97 /* display ceil for range of values */ 98 case 9: 99 printf( "ceil() " ); 100 101 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 102 printf( "%10.2lf ", ceil( loop2 ) ); 103 } /* end for */ 104 105 break; /* exit switch */ 106 107 /* display floor for range of values */ 108 case 10: 109 printf( "floor() " ); 110 111 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 112 printf( "%10.2lf ", floor( loop2 ) ); 113 } /* end for */ 114 115 break; /* exit switch */ 116 117 /* display sin for range of values */ 118 case 11: 119 printf( "sin() " ); 120 121 for ( loop2 = -1.5; loop2 < 3.0; loop2 += 1.1 ) { 122 printf( "%10.2lf ", sin( loop2 ) ); 123 } /* end for */ 124 125 break; /* exit switch */ 126 127 /* display cos for range of values */ 128 case 12: 129 printf( "cos() " ); 130 © 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 sqrt() exp() log() log10() pow( 2,x ) 1 1.00 2.72 0.00 0.00 2.00 2 1.41 7.39 0.69 0.30 4.00 3 1.73 20.09 1.10 0.48 8.00 4 2.00 54.60 1.39 0.60 16.00 5 2.24 148.41 1.61 0.70 32.00 funct fabs() ceil() floor() sin() cos() tan() -1.50 1.50 -1.00 -2.00 -1.00 0.07 -14.10 -0.40 0.40 0.00 -1.00 -0.39 0.92 -0.42 0.70 0.70 1.00 0.00 0.64 0.76 0.84 1.80 1.80 2.00 1.00 0.97 -0.23 -4.29 2.90 2.90 3.00 2.00 0.24 -0.97 -0.25 5.50 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. Chapter 5 C Functions: Solutions 163 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 n ) { if ( n == 0 ) return 0; else return 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 /* Exercise 5.51 Solution */ 2 #include 3 #include 4 #include 5 6 /* enumeration constants represent game status */ 7 enum Status { CONTINUE, WON, LOST }; 8 9 int rollDice( void ); /* function prototype */ 10 enum Status craps( void ); /* function prototype */ 11 void chatter( void ); /* function prototype */ 12 13 int main() 14 { 15 enum Status result; /* result of current game */ 16 int wager = 0; /* wager for current game */ 17 int bankBalance = 1000; /* current bank balance */ 18 19 srand( time( NULL ) ); /* seed random number generator */ 20 21 /* display current balance and prompt for wager */ 22 printf( "You have $%d in the bank.\n", bankBalance ); 23 printf( "Place your wager: " ); 24 scanf( "%d", &wager ); 25 26 /* loop while not valid wager */ 27 while( wager <= 0 || wager > 1000 ) { 28 printf( "Please bet a valid amount.\n" ); 29 scanf( "%d", &wager ); 30 } /* end while */ 31 32 result = craps(); /* play game of craps */ 33 34 /* if player lost current game */ 35 if ( result == LOST ) { 36 37 /* decrease balance by wager and display new balance */ 38 bankBalance -= wager; 39 printf( "Your new bank balance is $%d\n", bankBalance ); 40 41 /* if balance is 0 */ 42 if ( bankBalance == 0 ) { 43 printf( "Sorry. You are Busted! Thank You For Playing.\n" ); 44 } /* end if */ 45 46 } /* end if */ 47 else { /* player won game */ 48 49 /* increase balance by wager and display new balance */ 50 bankBalance += wager; 51 printf( "Your new bank balance is $%d\n", bankBalance ); 52 } /* end else */ 53 54 return 0; /* indicate successful termination */ 55 56 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 C Functions: Solutions 165 57 58 /* roll dice, calculate sum and display results */ 59 int rollDice( void ) 60 { 61 int die1; /* first die value */ 62 int die2; /* second die value */ 63 int workSum; /* sum of dice */ 64 65 die1 = 1 + rand() % 6; /* pick random die1 value */ 66 die2 = 1 + rand() % 6; /* pick random die2 value */ 67 workSum = die1 + die2; /* sum die1 and die2 */ 68 69 /* display results of this roll */ 70 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum ); 71 72 return workSum; /* return sum of dice */ 73 74 } /* end function rollDice */ 75 76 /* craps plays one game of craps, returns result of game */ 77 enum Status craps( void ) 78 { 79 enum Status gameStatus; /* can contain CONTINUE, WON or LOST */ 80 int sum; /* current roll of dice */ 81 int myPoint; /* point value */ 82 83 sum = rollDice(); /* first roll of dice */ 84 85 /* determine game status and point based on sum of dice */ 86 switch ( sum ) { 87 88 /* win on first roll */ 89 case 7: 90 case 11: 91 gameStatus = WON; 92 chatter(); 93 break; /* exit switch */ 94 95 /* lose on first roll */ 96 case 2: 97 case 3: 98 case 12: 99 gameStatus = LOST; 100 chatter(); 101 break; /* exit switch */ 102 103 /* remember point */ 104 default: 105 gameStatus = CONTINUE; 106 myPoint = sum; 107 printf( "Point is %d\n", myPoint ); 108 chatter(); 109 break; /* exit switch */ 110 } /* end switch */ 111 112 /* while game not complete */ 113 while ( gameStatus == CONTINUE ) { 114 chatter(); 115 sum = rollDice(); /* roll dice again */ 116 117 /* determine game status */ 118 if ( sum == myPoint ) { 119 gameStatus = WON; /* win by making point */ 120 } /* end if */ 121 else { 122 123 if ( sum == 7 ) { 124 gameStatus = LOST; /* lose by rolling 7 */ 125 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 166 C Functions: Solutions 126 127 } /* end else */ 128 129 } /* end while */ 130 131 /* display won or lost message and return status */ 132 if ( gameStatus == WON ) { 133 printf( "Player wins\n" ); 134 return WON; 135 } /* end if */ 136 else { 137 printf( "Player loses\n" ); 138 return LOST; 139 } /* end else */ 140 141 } /* end function craps */ 142 143 /* chatter displays messages at random to create "chatter" */ 144 void chatter( void ) 145 { 146 int select; /* random number */ 147 148 select = 1 + rand() % 6; 149 150 /* choose message at random */ 151 switch ( select ) { 152 153 case 1: 154 printf( "Oh, you're going for broke, huh?\n" ); 155 break; /* exit switch */ 156 157 case 2: 158 printf( "Aw cmon, take a chance!\n" ); 159 break; /* exit switch */ 160 161 case 3: 162 printf( "Hey, I think this guy is going to break the bank!!\n" ); 163 break; /* exit switch */ 164 165 case 4: 166 printf( "You're up big. Now's the time to cash in your chips!\n" ); 167 break; /* exit switch */ 168 169 case 5: 170 printf( "Way too lucky! Those dice have to be loaded!\n" ); 171 break; /* exit switch */ 172 173 case 6: 174 printf( "Bet it all! Bet it all!\n" ); 175 break; /* exit switch */ 176 177 default: 178 break; /* exit switch */ 179 } /* end switch */ 180 181 } /* end function chatter */ Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 C Functions: Solutions 167 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 168 C Functions: Solutions Chapter 5 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 subscript (by convention) identifies the of an element. 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[ 0 ][ 0 ] = 0; t[ 0 ][ 1 ] = 0; t[ 0 ][ 2 ] = 0; t[ 0 ][ 3 ] = 0; t[ 0 ][ 4 ] = 0; t[ 1 ][ 0 ] = 0; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 171 t[ 1 ][ 1 ] = 0; t[ 1 ][ 2 ] = 0; t[ 1 ][ 3 ] = 0; t[ 1 ][ 4 ] = 0; i) Write a nested for statement that initializes each element of t to zero. 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 /* Exercise 6.10 Solution */ 2 #include 3 4 int main() 5{ 6 int salaries[ 11 ] = { 0 }; /* array to hold salary counts */ 7 int sales; /* current employee's sales */ 8 double salary; /* current employee's salary */ 9 double i = 0.09; /* commission percentage */ 10 11 /* prompt user for gross sales */ 12 printf( "Enter employee gross sales ( -1 to end ): " ); 13 scanf( "%d", &sales ); 14 15 /* while sentinel value not read from user */ 16 while ( sales != -1 ) { 17 18 /* calculate salary based on sales */ 19 salary = 200.0 + sales * i; 20 printf( "Employee Commission is $%.2f\n", salary ); 21 22 /* update appropriate salary range */ 23 if ( salary >= 200 && salary < 1000 ) { 24 ++salaries[ ( int ) salary / 100 ]; 25 } /* end if */ 26 else if ( salary >= 1000 ) { 27 ++salaries[ 10 ]; 28 } /* end else if */ 29 30 /* prompt user for another employee sales amount */ 31 printf( "\nEnter employee gross sales ( -1 to end ): " ); 32 scanf( "%d", &sales ); 33 } /* end while */ 34 35 /* display table of ranges and employees in each range */ 36 printf( "\nEmployees in the range:\n" ); 37 printf( "$200-$299 : %d\n", salaries[ 2 ] ); 38 printf( "$300-$399 : %d\n", salaries[ 3 ] ); 39 printf( "$400-$499 : %d\n", salaries[ 4 ] ); 40 printf( "$500-$599 : %d\n", salaries[ 5 ] ); 41 printf( "$600-$699 : %d\n", salaries[ 6 ] ); 42 printf( "$700-$799 : %d\n", salaries[ 7 ] ); 43 printf( "$800-$899 : %d\n", salaries[ 8 ] ); 44 printf( "$900-$999 : %d\n", salaries[ 9 ] ); 45 printf( "Over $1000: %d\n", salaries[ 10 ] ); 46 47 return 0; /* indicate successful termination */ 48 49 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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 C Arrays: Solutions 173 © 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 /* Exercise 6.11 Solution */ 2 #include 3 #define MAX 10 4 5 int main() 6{ 7 8 /* initialize array a with initializer list */ 9 int a[ MAX ] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; 10 int i; /* loop counter */ 11 int pass; /* loop counter */ 12 int hold; /* temporary variable for swapping */ 13 int swap; /* flag to break loop if elements are sorted */ 14 15 printf( "Data items in original order\n" ); 16 17 /* display original, unsorted array */ 18 for ( i = 0; i < MAX; i++ ) { 19 printf( "%4d", a[ i ] ); 20 } /* end for */ 21 22 printf( "\n\n" ); 23 24 /* begin sorting the array */ 25 for ( pass = 1; pass < MAX; pass++ ) { 26 swap = 0; 27 28 /* traverse and compare unsorted part of array */ 29 for ( i = 0; i < MAX - pass; i++ ) { 30 31 /* compare adjacent array elements */ 32 if ( a[ i ] > a[ i + 1 ] ) { 33 swap = 1; /* raise flag if any elements are swapped */ 34 hold = a[ i ]; 35 a[ i ] = a[ i + 1 ]; 36 a[ i + 1 ] = hold; 37 } /* end if */ 38 39 } /* end for */ 40 41 printf( "After Pass %d: ", pass ); 42 43 /* display array after each pass */ 44 for ( i = 0; i <= MAX-pass; i++ ) { 45 printf( " %d", a[ i ] ); 46 } /* end for */ 47 48 printf( "\n" ); 49 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 175 50 /* break loop if array is sorted */ 51 if ( !swap ) { 52 break; 53 } /* end if */ 54 55 } /* end for */ 56 57 printf( "\nData items in ascending order\n" ); 58 59 /* display array in sorted order */ 60 for ( i = 0; i < 10; i++ ) { 61 printf( "%4d", a[ i ] ); 62 } /* end for */ 63 64 printf( "\n" ); 65 66 return 0; /* indicate successful termination */ 67 68 } /* end main */ Data items in original order 10 9 8 7 6 5 4 3 2 1 After Pass 1: After Pass 2: After Pass 3: After Pass 4: After Pass 5: After Pass 6: After Pass 7: After Pass 8: After Pass 9: 9 8 7 6 5 4 3 2 1 10 876543219 76543218 6543217 543216 43215 3214 213 12 Data items in ascending order 1 2 3 4 5 6 7 8 9 10 6.12 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 Chapter 6 6.13 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. Chapter 6 C Arrays: Solutions 177 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 /* Exercise 6.14 Solution */ 2 #include 3 #define SIZE 100 4 5 void mean( int answer[] ); /* function prototype */ 6 void median( int answer[] ); /* function prototype */ 7 void mode( int freq[], int answer[] ); /* function prototype */ 8 9 int main() 10 { 11 12 /* array of responses */ 13 int response[ SIZE ] = { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 14 7, 8, 9, 5, 9, 8, 7, 8, 7, 1, 15 6, 7, 8, 9, 3, 9, 8, 7, 1, 7, 16 7, 8, 9, 8, 9, 8, 9, 7, 1, 9, 17 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 18 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 19 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 20 7, 8, 9, 6, 8, 7, 8, 9, 7, 1, 21 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 22 4, 5, 6, 1, 6, 5, 7, 8, 7, 9}; 23 int frequency[ 10 ] = { 0}; /* array of response frequencies */ 24 25 mean( response ); /* process mean */ 26 median( response ); /* process median */ 27 mode( frequency, response ); /* process mode */ 28 29 return 0; /* indicates successful termination */ 30 31 } /* end main */ 32 33 /* calculate average of all response values */ 34 void mean( int answer[] ) 35 { 36 int j; /* loop counter */ 37 int total = 0; /* total of all response values */ 38 39 printf( "%s\n%s\n%s\n", "******", " Mean", "******" ); 40 41 /* total response values */ 42 for ( j = 0; j <= SIZE - 1; j++ ) { 43 total += answer[ j ]; 44 } /* end for */ 45 46 /* output results */ 47 printf( "The mean is the average value of the data\n" ); 48 printf( "items. The mean is equal to the total of\n" ); 49 printf( "all the data items divided by the number\n" ); 50 printf( "of data items ( %d ). ,", SIZE ); 51 printf( "The mean value for this run is: " ); 52 printf( "%d / %d = %.4f\n\n", total, SIZE, ( double ) total / SIZE ); 53 } /* end function mean */ 54 55 /*sort an array and determine median element's value */ 56 void median( int answer[] ) 57 { 58 int loop; /* loop counter */ 59 int pass; /* loop counter */ 60 int hold; /* temporary variable for swapping */ 61 int firstRow; /* flag to indicate first row of array */ 62 63 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 Chapter 6 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 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 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 array of responses is 67898789897895987871 67893987177898989719 67878798927898989753 56725394647896878971 74425387564561657879 The sorted array is 11111222333344444555 55555666666666777777 77777777777777777888 88888888888888888888 99999999999999999999 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 1122 50505 1 5 2 3 3 4 4 5 5 8 6 9 7 23 8 23 9 20 ***** *** **** ***** ******** ********* *********************** *********************** ******************** The modes are: 7 with a frequency of 23 8 with a frequency of 23 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 181 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 /* Exercise 6.15 Solution */ 2 #include 3 #define MAX 20 4 5 int main() 6{ 7 int a[ MAX ] = { 0 }; /* array for user input */ 8 int i; /* loop counter */ 9 int j; /* loop counter */ 10 int k = 0; /* number of values currently entered */ 11 int duplicate; /* flag for duplicate values */ 12 int value; /* current value */ 13 14 printf( "Enter 20 integers between 10 and 100:\n" ); 15 16 /* get 20 integers from user */ 17 for ( i = 0; i <= MAX - 1; i++ ) { 18 duplicate = 0; 19 scanf( "%d", &value ); 20 21 /* test if integer is a duplicate */ 22 for ( j = 0; j < k; j++ ) { 23 24 /* if duplicate, raise flag and break loop */ 25 if ( value == a[ j ] ) { 26 duplicate = 1; 27 break; 28 } /* end if */ 29 30 } /* end for */ 31 32 /* if number is not a duplicate enter it in array */ 33 if ( !duplicate ) { 34 a[ k++ ] = value; 35 } /* end if */ 36 37 } /* end for */ 38 39 printf( "\nThe nonduplicate values are:\n" ); 40 41 /* display array of nonduplicates */ 42 for ( i = 0; a[ i ] != 0; i++ ) { 43 printf( "%d ", a[ i ] ); 44 } /* end for */ 45 46 printf( "\n" ); 47 48 return 0; /* indicate successful termination */ 49 50 } /* 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) sales[ 0 ][ 0 ] 2) sales[ 0 ][ 1 ] 3) sales[ 0 ][ 2 ] 4) sales[ 0 ][ 3 ] 5) sales[ 0 ][ 4 ] 6) sales[ 1 ][ 0 ] 7) sales[ 1 ][ 1 ] 8) sales[ 1 ][ 2 ] 9) sales[ 1 ][ 3 ] 10) sales[ 1 ][ 4 ] 11) sales[ 2 ][ 0 ] 12) sales[ 2 ][ 1 ] 13) sales[ 2 ][ 2 ] 14) sales[ 2 ][ 3 ] 15) sales[ 2 ][ 4 ] © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 6.17 What does the following program do? 1 /* ex06_17.c */ 2 /* What does this program do? */ 3 #include 4 #define SIZE 10 5 6 int whatIsThis( const int b[], int p ); /* function prototype */ 7 8 /* function main begins program execution */ 9 int main() 10 { 11 int x; /* holds return value of function whatIsThis */ 12 13 /* initialize array a */ 14 int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 15 16 x = whatIsThis( a, SIZE ); 17 18 printf( "Result is %d\n", x ); 19 20 return 0; /* indicates successful termination */ 21 22 } /* end main */ 23 24 /* what does this function do? */ 25 int whatIsThis( const int b[], int p ) 26 { 27 /* base case */ 28 if ( p == 1 ) { 29 return b[ 0 ]; 30 } /* end if */ 31 else { /* recursion step */ 32 33 return b[ p - 1 ] + whatIsThis( b, p - 1 ); 34 } /* end else */ 35 36 } /* end function whatIsThis */ ANS: The program recursively sums the elements in a. Result is 55 C Arrays: Solutions 183 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 184 C Arrays: Solutions 6.18 What does the following program do? 1 /* ex06_18.c */ 2 /* What does this program do? */ 3 #include 4 #define SIZE 10 5 6 /* function prototype */ 7 void someFunction( const int b[], int startIndex, int size ); 8 9 /* function main begins program execution */ 10 int main() 11 { 12 int a[ SIZE ] = { 8, 3, 1, 2, 6, 0, 9, 7, 4, 5 }; /* initialize a */ 13 14 printf( "Answer is:\n" ); 15 someFunction( a, 0, SIZE ); 16 printf( "\n" ); 17 18 return 0; /* indicates successful termination */ 19 20 } /* end main */ 21 22 /* What does this function do? */ 23 void someFunction( const int b[], int startIndex, int size ) 24 { 25 if ( startIndex < size ) { 26 someFunction( b, startIndex + 1, size ); 27 printf( "%d ", b[ startIndex ] ); 28 } /* end if */ 29 30 } /* end function someFunction */ ANS: The program recursively outputs the values of a in reverse order. Answer is: 5479062138 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 185 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. 123456 123456 7 234567 8 345678 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 /* Exercise 6.19 Solution */ 2 #include 3 #include 4 #include 5 6 int main() 7{ 8 long i; /* loop counter */ 9 int j; /* loop counter */ 10 int x; /* first die */ 11 int y; /* second die */ 12 int sum[ 13 ] = { 0 }; /* count occurrences of each combination */ 13 14 /* array expected contains counts for the expected 15 number of times each sum occurs in 36 rolls of the dice */ 16 int expected[ 13 ] = { 0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; 17 18 srand( time( NULL ) ); /* seed random number generator */ 19 20 /* roll dice 36,000 times */ 21 for ( i = 1; i <= 36000; i++ ) { 22 x = 1 + rand() % 6; 23 y = 1 + rand() % 6; 24 ++sum[ x + y ]; 25 } /* end for */ 26 27 printf( "%10s%10s%10s%10s\n", "Sum", "Total", "Expected", "Actual" ); 28 29 /* display results of rolling dice */ 30 for ( j = 2; j <= 12; j++ ) { 31 printf( "%10d%10d%9.3f%%%9.3f%%\n", j, sum[ j ], 32 100.0 * expected[ j ] / 36, 100.0 * sum[ j ] / 36000 ); 33 } /* end for */ 34 35 return 0; /* indicate successful termination */ 36 37 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 186 C Arrays: Solutions Sum Total Expected Actual 2 1018 2.778% 2.828% 3 2008 5.556% 5.578% 4 3020 8.333% 8.389% 5 4024 11.111% 11.178% 6 4891 13.889% 13.586% 7 6011 16.667% 16.697% 8 5065 13.889% 14.069% 9 3984 11.111% 11.067% 10 2970 8.333% 8.250% 11 1989 5.556% 5.525% 12 1020 2.778% 2.833% Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 187 6.20 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: 1 /* Exercise 6.20 Solution */ 2 #include 3 #include 4 #include 5 6 enum Outcome { CONTINUE, WIN, LOSE }; 7 8 int rollDice( void ); /* function prototype */ 9 10 int main() 11 { 12 enum Outcome gameStatus; /* game status indicator */ 13 int sum; /* sum of rolled dice */ 14 int myPoint; /* current point */ 15 int i; /* game counter */ 16 int roll; /* roll counter */ 17 int length = 0; /* average length of game */ 18 int wins[ 22 ] = { 0 }; /* wins per roll */ 19 int losses[ 22 ] = { 0 }; /* losses per roll */ 20 int winSum = 0; /* total wins */ 21 int loseSum = 0; /* total losses */ 22 23 srand( time( NULL ) ); 24 25 /* play 1000 times */ 26 for ( i = 1; i <= 1000; i++ ) { 27 sum = rollDice(); 28 roll = 1; 29 30 /* test if game won or lost on first roll */ 31 switch ( sum ) { 32 33 case 7: 34 case 11: 35 gameStatus = WIN; 36 break; /* exit switch */ 37 38 case 2: 39 case 3: 40 case 12: 41 gameStatus = LOSE; 42 break; /* exit switch */ 43 44 default: 45 gameStatus = CONTINUE; 46 myPoint = sum; 47 break; /* exit switch */ 48 } /* end switch */ 49 50 /* continue while game not won or lost */ 51 while ( gameStatus == 0 ) { 52 sum = rollDice(); 53 roll++; 54 55 /* win on next roll */ 56 if ( sum == myPoint ) { 57 gameStatus = WIN; 58 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 188 C Arrays: Solutions Chapter 6 59 else { /* lose on next roll */ 60 61 if ( sum == 7 ) { 62 gameStatus = LOSE; 63 } /* end if */ 64 65 } /* end else */ 66 67 } /* end while */ 68 69 /* if more than 21 rolls taken, set number of rolls to 21 */ 70 if ( roll > 21 ) { 71 roll = 21; 72 } /* end if */ 73 74 /* determine how many rolls were taken and increment 75 corresponding counter in wins or losses array */ 76 if ( gameStatus == WIN ) { 77 wins[ roll ]++; 78 winSum++; 79 } /* end if */ 80 else { 81 losses[ roll ]++; 82 loseSum++; 83 } /* end else */ 84 85 } /* end for */ 86 87 printf( "Games won or lost after the 20th roll\n" 88 "are displayed as the 21st roll.\n\n" ); 89 90 /* display number of games won and lost for each number of rolls */ 91 for ( i = 1; i <= 21; i++ ) { 92 printf( "%3d games won and %3d games lost on roll %d.\n", 93 wins[ i ], losses[ i ], i ); 94 } /* end for */ 95 96 /* calculate chances of winning */ 97 printf( "\nThe chances of winning are %d/%d = %.2f%%\n", winSum, 98 winSum + loseSum, 100.0 * winSum / ( winSum + loseSum ) ); 99 100 /* calculate average length of game */ 101 for ( i = 1; i <= 21; i++ ) { 102 length += wins[ i ] * i + losses[ i ] * i; 103 } /* end for */ 104 105 printf( "The average game length is %.2f rolls.\n", 106 length / 1000.0 ); 107 108 return 0; /* indicate successful termination */ 109 110 } /* end main */ 111 112 /* function to simulate dice rolling */ 113 int rollDice( void ) 114 { 115 int die1; /* first die */ 116 int die2; /* second die */ 117 int workSum; /* dice sum */ 118 119 die1 = 1 + rand() % 6; 120 die2 = 1 + rand() % 6; 121 workSum = die1 + die2; 122 123 return workSum; /* return total of two dice */ 124 125 } /* end function rollDice */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 Games won or lost after the 20th roll are displayed as the 21st roll. 212 games won and 102 games lost on roll 1. 63 games won and 109 games lost on roll 2. 54 games won and 92 games lost on roll 3. 45 games won and 70 games lost on roll 4. 40 games won and 54 games lost on roll 5. 17 games won and 34 games lost on roll 6. 9 games won and 21 games lost on roll 7. 10 games won and 11 games lost on roll 8. 7 games won and 9 games lost on roll 9. 3 games won and 2 games lost on roll 10. 6 games won and 12 games lost on roll 11. 4 games won and 4 games lost on roll 12. 1 games won and 1 games lost on roll 13. 1 games won and 0 games lost on roll 14. 0 games won and 1 games lost on roll 15. 1 games won and 1 games lost on roll 16. 0 games won and 0 games lost on roll 17. 0 games won and 1 games lost on roll 18. 1 games won and 1 games lost on roll 19. 0 games won and 0 games lost on roll 20. 0 games won and 1 games lost on roll 21. The chances of winning are 474/1000 = 47.40% The average game length is 3.36 rolls. C Arrays: Solutions 189 © 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 /* Exercise 6.21 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 int plane[ 11 ] = { 0 }; /* seats on the plane */ 8 int i = 0; /* counter */ 9 int firstClass= 1; /* first class seats start at 1 */ 10 int economy = 6; /* economy seats start at 6 */ 11 int choice; /* user's choice */ 12 char response[ 2 ]; /* user's response */ 13 14 /* loop 10 times */ 15 while ( i < 10 ) { 16 printf( "\n%s\n%s\n? ", "Please type 1 for \"first class\"", 17 "Please type 2 for \"economy\"" ); 18 scanf( "%d", &choice ); 19 20 /* if user selects first class */ 21 if ( choice == 1 ) { 22 23 /* if seat are available in first class */ 24 if ( !plane[ firstClass ] && firstClass <= 5 ) { 25 printf( "Your seat assignment is %d\n", firstClass ); 26 plane[ firstClass++ ] = 1; 27 i++; 28 } /* end if */ 29 /* if no first class seats, but economy seats available */ 30 else if ( firstClass > 5 && economy <= 10 ) { 31 32 /* ask if passenger would like to sit in economy */ 33 printf( "The first class section is full.\n" ); 34 printf( "Would you like to sit in the economy" ); 35 printf( " section ( Y or N )? " ); 36 scanf( "%s", response ); 37 38 /* if response is yes, then assign seat */ 39 if ( toupper( response[ 0 ] ) == 'Y' ) { 40 printf( "Your seat assignment is %d\n", economy ); 41 plane[ economy++ ] = 1; 42 i++; 43 } /* end if */ 44 else { /* print next departure */ 45 printf( "Next flight leaves in 3 hours.\n" ); 46 } /* end else */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 191 47 48 } /* end else if */ 49 else { /* print next departure */ 50 printf( "Next flight leaves in 3 hours.\n" ); 51 } /* end else */ 52 53 } /* end if */ 54 else { /* if user selects economy */ 55 56 /* if seats available, assign seat */ 57 if ( !plane[ economy ] && economy <= 10 ) { 58 printf( "Your seat assignment is %d\n", economy ); 59 plane[ economy++ ] = 1; 60 i++; 61 } /* end if */ 62 /* if only first class seats are available */ 63 else if ( economy > 10 && firstClass <= 5 ) { 64 65 /* ask if first class is suitable */ 66 printf( "The economy section is full.\n" ); 67 printf( "Would you like to sit in first class" ); 68 printf( " section ( Y or N )? " ); 69 scanf( "%s", response ); 70 71 /* if response is yes, assign seat */ 72 if ( toupper( response[ 0 ] ) == 'Y' ) { 73 printf( "Your seat assignment is %d\n", firstClass ); 74 plane[ firstClass++ ] = 1; 75 i++; 76 } /* end if */ 77 else { /* print next departure */ 78 printf( "Next flight leaves in 3 hours.\n" ); 79 } /* end else */ 80 81 } /* end else if */ 82 else { /* print next departure */ 83 printf( "Next flight leaves in 3 hours.\n" ); 84 } /* end else */ 85 86 } /* end else */ 87 88 } /* end while */ 89 90 printf( "\nAll seats for this flight are sold.\n" ); 91 92 return 0; /* indicate successful termination */ 93 94 } /* 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. Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 193 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 /* Exercise 6.22 Solution */ 2 #include 3 4 int main() 5{ 6 7 /* total sales for each salesperson and each product */ 8 double sales[ 4 ][ 5 ] = { 0.0 }; 9 double productSales[ 5 ] = { 0.0 }; /* total product sales */ 10 double value; /* current sales */ 11 double totalSales; /* total overall sales */ 12 int salesPerson; /* current salesperson */ 13 int product; /* current product */ 14 int i; /* loop counter */ 15 int j; /* loop counter */ 16 17 printf( "Enter the salesperson, product, and total sales.\n" ); 18 printf( "Enter -1 for the salesperon to end input.\n" ); 19 scanf( "%d", &salesPerson ); 20 21 /* continue receiving input for each salesperson 22 while -1 is not entered */ 23 while ( salesPerson != -1 ) { 24 scanf( "%d%lf", &product, &value ); 25 sales[ salesPerson ][ product ] = value; 26 scanf( "%d", &salesPerson ); 27 } /* end while */ 28 29 /* display table */ 30 printf( "\n%s\n%s\n%s\n%s\n%s\n", "The total sales for each salesperson", 31 "are displayed at the end of each", "row, and the total sales for each", 32 "product are displayed at the bottom ", "of each column.\n" ); 33 printf( " %8d%8d%8d%8d%8d\n", 1, 2, 3, 4, 5 ); 34 35 /* display salespeople and sales */ 36 for ( i = 0; i <= 3; i++ ) { 37 totalSales = 0.0; 38 printf( "%d", i); 39 40 /* add total sales and display individual sales */ 41 for ( j = 0; j <= 4; j++ ) { 42 totalSales += sales[ i][ j ]; 43 printf( "%8.2f", sales[ i ][ j ] ); 44 productSales[ j ] += sales[ i ][ j ]; 45 } /* end for */ 46 47 printf( "%8.2f\n", totalSales ); 48 } /* end for */ 49 50 printf( " " ); 51 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 194 C Arrays: Solutions 52 /* display total product sales */ 53 for ( j = 0; j <= 4; j++ ) { 54 printf( "%8.2f", productSales[ j ] ); 55 } /* end for */ 56 57 return 0; /* indicate successful termination */ 58 59 } /* 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 salesperson are displayed at the end of each row, and the total sales for each product are displayed at the bottom of each column. 1 2 3 4 5 0 1.00 2.00 3.00 4.00 5.00 15.00 1 1.00 2.00 3.00 4.00 5.00 15.00 2 1.00 2.00 3.00 4.00 5.00 15.00 3 1.00 2.00 3.00 4.00 5.00 15.00 4.00 8.00 12.00 16.00 20.00 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 195 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 2 3 4 5,10 6 9 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) 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 /* Exercise 6.23 Solution */ 2 #include 3 4 #define TRUE 1 5 #define FALSE 0 6 #define MAX 100 /* the maximum number of commands */ 7 8 /* function prototypes */ 9 void getCommands( int commands[][ 2 ] ); 10 int turnRight( int d ); 11 int turnLeft( int d ); 12 void movePen( int down, int a[][ 50 ], int dir, int dist ); 13 void printArray( int a[][ 50 ] ); 14 15 int main() 16 { 17 int floor[ 50 ][ 50 ] = { 0 }; /* floor grid */ 18 int penDown = FALSE; /* pen down flag */ 19 int command; /* current command */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 196 C Arrays: Solutions Chapter 6 20 int direction = 0; /* direction indicator */ 21 int commandArray[ MAX ][ 2 ] = { 0 }; /* array of commands */ 22 int distance; /* distance to move */ 23 int count = 0; /* command counter */ 24 25 getCommands( commandArray ); 26 command = commandArray[ count ][ 0 ]; 27 28 /* continue receiving input while -9 is not entered */ 29 while ( command != 9 ) { 30 31 /* determine what command was entered and perform action */ 32 switch ( command ) { 33 34 case 1: 35 penDown = FALSE; 36 break; /* exit switch */ 37 38 case 2: 39 penDown = TRUE; 40 break; /* exit switch */ 41 42 case 3: 43 direction = turnRight( direction ); 44 break; /* exit switch */ 45 46 case 4: 47 direction = turnLeft( direction ); 48 break; /* exit switch */ 49 50 case 5: 51 distance = commandArray[ count ][ 1 ]; 52 movePen( penDown, floor, direction, distance ); 53 break; /* exit switch */ 54 55 case 6: 56 printf( "\nThe drawing is:\n\n" ); 57 printArray( floor ); 58 break; /* exit switch */ 59 } /* end switch */ 60 61 command = commandArray[ ++count ][ 0 ]; 62 } /* end while */ 63 64 return 0; /* indicate successful termination */ 65 66 } /* end main */ 67 68 /* getCommands prompts user for commands */ 69 void getCommands( int commands[][ 2 ] ) 70 { 71 int i; /* counter */ 72 int tempCommand; /* temporary command holder */ 73 74 printf( "Enter command ( 9 to end input ): " ); 75 scanf( "%d", &tempCommand ); 76 77 /* recieve commands until -9 or 100 commands are entered */ 78 for ( i = 0; tempCommand != 9 && i < MAX; i++ ) { 79 commands[ i ][ 0 ] = tempCommand; 80 81 /* ignore comma after 5 is entered */ 82 if ( tempCommand == 5 ) { 83 scanf( ",%d", &commands[ i ][ 1 ] ); 84 } /* end if */ 85 86 printf( "Enter command ( 9 to end input ): " ); 87 scanf( "%d", &tempCommand ); 88 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 197 89 90 commands[ i ][ 0 ] = 9; /* last command */ 91 } /* end function getCommands */ 92 93 /* turnRight turns turtle to the right */ 94 int turnRight( int d ) 95 { 96 return ++d > 3 ? 0 : d; 97 98 } /* end function turnRight */ 99 100 /* turnLeft turns turtle to the left */ 101 int turnLeft( int d ) 102 { 103 return --d < 0 ? 3 : d; 104 105 } /* end function turnLeft */ 106 107 /* movePen moves the pen */ 108 void movePen( int down, int a[][ 50 ], int dir, int dist ) 109 { 110 int i; /* loop counter */ 111 int j; /* loop counter */ 112 static int xPos = 0; /* x coordinate */ 113 static int yPos = 0; /* y coordinate */ 114 115 /* determine which way to move pen */ 116 switch ( dir ) { 117 118 case 0: /* move to the right */ 119 120 /* move dist spaces or until edge of floor */ 121 for ( j = 1; j <= dist && yPos + j < 50; j++ ) { 122 123 /* draw 1 if pen is down */ 124 if ( down ) { 125 a[ xPos ][ yPos + j ] = 1; 126 } /* end if */ 127 128 } /* end for */ 129 130 yPos += j - 1; 131 break; /* exit switch */ 132 133 case 1: /* move down */ 134 135 /* move dist spaces or until edge of floor */ 136 for ( i = 1; i <= dist && xPos + i < 50; i++ ) { 137 138 /* draw 1 if pen is down */ 139 if ( down ) { 140 a[ xPos + i ][ yPos ] = 1; 141 } /* end if */ 142 143 } /* end for */ 144 145 xPos += i - 1; 146 break; /* exit switch */ 147 148 case 2: /* move to the left */ 149 150 /* move dist spaces or until edge of floor */ 151 for ( j = 1; j <= dist && yPos - j >= 0; j++ ) { 152 153 /* draw 1 if pen is down */ 154 if ( down ) { 155 a[ xPos ][ yPos - j ] = 1; 156 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 198 C Arrays: Solutions Chapter 6 157 158 } /* end for */ 159 160 yPos -= j - 1; 161 break; /* exit switch */ 162 163 case 3: /* move up */ 164 165 /* move dist spaces or until edge of floor */ 166 for ( i = 1; i <= dist && xPos - i >= 0; i++ ) { 167 168 /* draw 1 if pen is down */ 169 if ( down ) { 170 a[ xPos - i ][ yPos ] = 1; 171 } /* end if */ 172 173 } /* end for */ 174 175 xPos -= i - 1; 176 break; /* exit switch */ 177 } /* end switch */ 178 179 } /* end function movePen */ 180 181 /* printArray prints array drawing */ 182 void printArray( int a[][ 50 ] ) 183 { 184 int i; /* counter */ 185 int j; /* counter */ 186 187 /* loop through array */ 188 for ( i = 0; i < 50; i++ ) { 189 190 /* loop through array */ 191 for ( j = 0; j < 50; j++ ) { 192 putchar( a[ i ][ j ] ? '*' : ' ' ); 193 } /* end for */ 194 195 putchar( '\n' ); 196 } /* end for */ 197 198 } /* end function printArray */ Enter command ( 9 to end input ): 2 Enter command ( 9 to end input ): 5,12 Enter command ( 9 to end input ): 3 Enter command ( 9 to end input ): 5,12 Enter command ( 9 to end input ): 3 Enter command ( 9 to end input ): 5,12 Enter command ( 9 to end input ): 3 Enter command ( 9 to end input ): 5,12 Enter command ( 9 to end input ): 1 Enter command ( 9 to end input ): 6 Enter command ( 9 to end input ): 9 The drawing is: ************* * * * * * * * * * * * * * * * * * * * * * * ************* © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 199 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: 01234567 0 1 2 1 2 3 0 3 K 4 4 7 5 5 6 6 7 horizontal[ 0 ] = 2 horizontal[ 1 ] = 1 horizontal[ 2 ] = -1 horizontal[ 3 ] = -2 horizontal[ 4 ] = -2 horizontal[ 5 ] = -1 horizontal[ 6 ] = 1 horizontal[ 7 ] = 2 vertical[ 0 ] = -1 vertical[ 1 ] = -2 vertical[ 2 ] = -2 vertical[ 3 ] = -1 vertical[ 4 ] = 1 vertical[ 5 ] = 2 vertical[ 6 ] = 2 vertical[ 7 ] = 1 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: 23444432 34666643 46888864 46888864 46888864 46888864 34666643 23444432 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 /* Exercise 6.24 Part C Solution */ 2 /* Knight's Tour - access version */ 3 /* runs one tour */ 4 5 #include 6 #include 7 #include 8 9 #define TRUE 1 10 #define FALSE 0 11 12 /* function prototypes */ 13 void clearBoard( int workBoard[][ 8 ] ); 14 void printBoard( int workBoard[][ 8 ] ); 15 int validMove( int row, int column, int workBoard[][ 8 ] ); 16 17 int main() 18 { 19 int board[ 8 ][ 8 ]; /* chess board */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 201 20 21 /* array of accesibility */ 22 int access[ 8 ][ 8 ] = { 2, 3, 4, 4, 4, 4, 3, 2, 23 3, 4, 6, 6, 6, 6, 4, 3, 24 4, 6, 8, 8, 8, 8, 6, 4, 25 4, 6, 8, 8, 8, 8, 6, 4, 26 4, 6, 8, 8, 8, 8, 6, 4, 27 4, 6, 8, 8, 8, 8, 6, 4, 28 3, 4, 6, 6, 6, 6, 4, 3, 29 2, 3, 4, 4, 4, 4, 3, 2 }; 30 31 /* eight horizontal and vertical moves for the knight */ 32 int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 33 int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 34 int currentRow; /* current row */ 35 int currentColumn; /* current column */ 36 int moveNumber = 0; /* move counter */ 37 int testRow; /* possible next row */ 38 int testColumn; /* possible next column */ 39 int minRow; /* row with minimum access number */ 40 int minColumn; /* column with minimum access number */ 41 int minAccess = 9; /* impossible access number */ 42 int accessNumber; /* current access number */ 43 int moveType; /* current move type */ 44 int done; /* flag to indicate end */ 45 46 srand( time( NULL ) ); 47 48 clearBoard( board ); /* initialize array board */ 49 currentRow = rand() % 8; 50 currentColumn = rand() % 8; 51 board[ currentRow ][ currentColumn ] = ++moveNumber; 52 done = FALSE; 53 54 /* continue while knight still has valid moves */ 55 while ( !done ) { 56 accessNumber = minAccess; 57 58 /* loop through all move types */ 59 for ( moveType = 0; moveType < 8; moveType++ ) { 60 testRow = currentRow + vertical[ moveType ]; 61 testColumn = currentColumn + horizontal[ moveType ]; 62 63 /* make sure move is valid */ 64 if ( validMove( testRow, testColumn, board ) ) { 65 66 /* if move is valid and has lowest accessNumber, 67 set square to accessNumber */ 68 if ( access[ testRow ][ testColumn ] < accessNumber ) { 69 accessNumber = access[ testRow ][ testColumn ]; 70 minRow = testRow; 71 minColumn = testColumn; 72 } /* end if */ 73 74 --access[ testRow ][ testColumn ]; 75 } /* end if */ 76 77 } /* end for */ 78 79 /* end if knight has no moves */ 80 if ( accessNumber == minAccess ) { 81 done = TRUE; 82 } /* end if */ 83 else { 84 currentRow = minRow; 85 currentColumn = minColumn; 86 board[ currentRow ][ currentColumn ] = ++moveNumber; 87 } /* end else */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 202 C Arrays: Solutions Chapter 6 88 89 } /* end while */ 90 91 printf( "The tour ended with %d moves.\n", moveNumber ); 92 93 /* determine and print if a full tour was made */ 94 if ( moveNumber == 64 ) { 95 printf( "This was a full tour!\n\n" ); 96 } /* end if */ 97 else { 98 printf( "This was not a full tour.\n\n" ); 99 } /* end else */ 100 101 printf( "The board for this test is:\n\n" ); 102 printBoard( board ); 103 104 return 0; /* indicate successful termination */ 105 106 } /* end main */ 107 108 /* function to clear chess board */ 109 void clearBoard( int workBoard[][ 8 ] ) 110 { 111 int row; /* row counter */ 112 int col; /* column counter */ 113 114 /* set all squares to zero */ 115 for ( row = 0; row < 8; row++ ) { 116 117 for ( col = 0; col < 8; col++ ) { 118 workBoard[ row ][ col ] = 0; 119 } /* end for */ 120 121 } /* end for */ 122 123 } /* end function clearBoard */ 124 125 /* function to print chess board */ 126 void printBoard( int workBoard[][ 8 ] ) 127 { 128 int row; /* row counter */ 129 int col; /* column counter */ 130 131 printf( " 0 1 2 3 4 5 6 7\n" ); 132 133 /* print squares */ 134 for ( row = 0; row < 8; row++ ) { 135 printf( "%d", row ); 136 137 for ( col = 0; col < 8; col++ ) { 138 printf( "%3d", workBoard[ row ][ col ] ); 139 } /* end for */ 140 141 printf( "\n" ); 142 } /* end for */ 143 144 printf( "\n" ); 145 } /* end function printBoard */ 146 147 /* function to determine if move is legal */ 148 int validMove( int row, int column, int workBoard[][ 8 ] ) 149 { 150 151 /* NOTE: This test stops as soon as it becomes false */ 152 return ( row >= 0 && row <= 7 && column >= 0 && 153 column <= 7 && workBoard[ row ][ column ] == 0 ); 154 155 } /* end function validMove */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 203 The tour ended with 64 moves. This was a full tour! The board for this test is: 01234567 0 33 30 19 4 23 28 17 2 1 20 5 32 29 18 3 24 27 2 31 34 49 22 37 26 1 16 3 6 21 36 59 50 47 38 25 4 35 60 51 48 39 58 15 46 5 10 7 62 57 54 45 40 43 6 61 52 9 12 63 42 55 14 7 8 11 64 53 56 13 44 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 /* Exercise 6.25 Part A Solution */ 2 #include 3 #include 4 #include 5 6 #define NO 0 7 #define YES 1 8 9 /* function prototypes */ 10 int validMove( int row, int column, int workBoard[][ 8 ] ); 11 void printBoard( int board[][ 8 ] ); 12 13 int main() 14 { 15 int currentRow; /* current row */ 16 int currentColumn; /* current column */ 17 int moveType; /* current move type */ 18 int moveNumber = 0; /* move counter */ 19 int testRow; /* possible next row */ 20 int testColumn; /* possible next column */ 21 int count; /* counter */ 22 int done; /* flag to indicate end */ 23 int goodMove; /* result of call to validMove */ 24 25 /* horizontal and vertical moves for the knight, and board */ 26 int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 27 int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 28 int board[ 8 ][ 8 ] = { 0 }; 29 30 srand( time( NULL ) ); 31 32 currentRow = rand() % 8; 33 currentColumn = rand() % 8; 34 board[ currentRow ][ currentColumn ] = ++moveNumber; 35 done = NO; 36 37 /* continue while knight can still move */ 38 while ( !done ) { 39 moveType = rand() % 8; 40 testRow = currentRow + vertical[ moveType ]; 41 testColumn = currentColumn + horizontal[ moveType ]; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 204 C Arrays: Solutions Chapter 6 42 goodMove = validMove( testRow, testColumn, board ); 43 44 /* test if desired move is valid */ 45 if ( goodMove ) { 46 currentRow = testRow; 47 currentColumn = testColumn; 48 board[ currentRow ][ currentColumn ] = ++moveNumber; 49 } /* end if */ 50 else { 51 52 /* if move is not legal try another random move */ 53 for ( count = 0; count < 7 && !goodMove; count++ ) { 54 moveType = ++moveType % 8; 55 testRow = currentRow + vertical[ moveType ]; 56 testColumn = currentColumn + horizontal[ moveType ]; 57 goodMove = validMove( testRow, testColumn, board ); 58 59 /* test if new move is good */ 60 if ( goodMove ) { 61 currentRow = testRow; 62 currentColumn = testColumn; 63 board[ currentRow ][ currentColumn ] = ++moveNumber; 64 } /* end if */ 65 66 } /* end for */ 67 68 /* if no valid moves, knight can no longer move */ 69 if ( !goodMove ) { 70 done = YES; 71 } /* end if */ 72 73 } /* end else */ 74 75 /* if 64 moves have been made, a full tour is complete */ 76 if ( moveNumber == 64 ) { 77 done = YES; 78 } /* end if */ 79 80 } /* end while */ 81 82 printf( "The tour has ended with %d moves.\n", moveNumber ); 83 84 /* test if full tour was made */ 85 if ( moveNumber == 64 ) { 86 printf( "This was a full tour!\n" ); 87 } /* end if */ 88 else { 89 printf( "This was not a full tour.\n" ); 90 } /* end else */ 91 92 printf( "The board for this random test was:\n\n" ); 93 printBoard( board ); /* print the board */ 94 95 return 0; /* indicate successful termination */ 96 97 } /* end main */ 98 99 /* function to test whether a square is on the board 100 and has not been visited yet */ 101 int validMove( int row, int column, int workBoard[][ 8 ] ) 102 { 103 /* NOTE: This test stops as soon as it becomes false */ 104 return ( row >= 0 && row < 8 && column >= 0 && 105 column < 8 && workBoard[ row ][ column ] == 0 ); 106 107 } /* end function validMove */ 108 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 205 109 /* function to print the chess board */ 110 void printBoard( int board[][ 8 ] ) 111 { 112 int row; /* row counter */ 113 int col; /* column counter */ 114 115 printf( " 0 1 2 3 4 5 6 7\n" ); 116 117 118 /* print the rows and columns of the chess board */ 119 for ( row = 0; row < 8; row++ ) { 120 printf( "%d", row ); 121 122 for ( col = 0; col < 8; col++ ) { 123 printf( "%3d", board[ row ][ col ] ); 124 } /* end for */ 125 126 printf( "\n" ); 127 } /* end for */ 128 129 printf( "\n" ); 130 } /* end function printBoard */ The tour has ended with 32 moves. This was not a full tour. The board for this random test was: 01234567 0 13 0 0 0 11 28 0 32 1 0 0 12 29 24 31 8 0 2 0 14 0 0 27 10 25 6 3 18 0 16 23 30 7 0 9 4 15 0 19 0 0 26 5 0 5 20 17 0 0 22 0 2 0 6 0 0 21 0 0 0 0 4 700000301 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 /* Exercise 6.25 Part B Solution */ 2 #include 3 #include 4 #include 5 6 #define NO 0 7 #define YES 1 8 9 int validMove( int, int, int [][ 8 ] ); 10 11 int main() 12 { 13 int currentRow; /* current row */ 14 int currentColumn; /* current column */ 15 int moveType; /* current move type */ 16 int moveNumber; /* move counter */ 17 int testRow; /* possible next row */ 18 int testColumn; /* possible next column */ 19 int count; /* counter */ 20 int i; /* counter */ 21 int row; /* row */ 22 int col; /* column */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 206 C Arrays: Solutions Chapter 6 23 int done; /* flag to indicate end */ 24 int goodMove; /* result of call to validMove */ 25 int board[ 8 ][ 8 ]; /* chess board */ 26 int moveTotal[ 65 ] = { 0 }; /* array of tour totals */ 27 28 /* horizontal and vertical moves for the knight */ 29 int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 30 int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 31 32 srand( time( NULL ) ); 33 34 /* attempt 1000 tours */ 35 for ( i = 0; i < 1000; i++ ) { 36 37 /* set all squares equal to 0 */ 38 for ( row = 0; row < 8; row++ ) { 39 40 for ( col = 0; col < 8; col++ ) { 41 board[ row ][ col ] = 0; 42 } /* end for */ 43 44 } /* end for */ 45 46 moveNumber = 0; 47 48 currentRow = rand() % 8; 49 currentColumn = rand() % 8; 50 board[ currentRow ][ currentColumn ] = ++moveNumber; 51 done = NO; 52 53 /* continue while knight still has valid moves */ 54 while ( !done ) { 55 moveType = rand() % 8; 56 testRow = currentRow + vertical[ moveType ]; 57 testColumn = currentColumn + horizontal[ moveType ]; 58 goodMove = validMove( testRow, testColumn, board ); 59 60 /* if desired move is valid, move knight to square */ 61 if ( goodMove ) { 62 currentRow = testRow; 63 currentColumn = testColumn; 64 board[ currentRow ][ currentColumn ] = ++moveNumber; 65 } /* end if */ 66 else { 67 68 /* if move is invalid, test other possible moves */ 69 for ( count = 0; count < 7 && !goodMove; count++ ) { 70 moveType = ++moveType % 8; 71 testRow = currentRow + vertical[ moveType ]; 72 testColumn = currentColumn + horizontal[ moveType ]; 73 goodMove = validMove( testRow, testColumn, board ); 74 75 /* if move is valid, move knight to square */ 76 if ( goodMove ) { 77 currentRow = testRow; 78 currentColumn = testColumn; 79 board[ currentRow ][ currentColumn ] = ++moveNumber; 80 } /* end if */ 81 82 } /* end for */ 83 84 /* if no valid moves, while loop exits */ 85 if ( !goodMove ) { 86 done = YES; 87 } /* end if */ 88 89 } /* end else */ 90 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 91 /* if full tour is made, while loop exits */ 92 if ( moveNumber == 64 ) { 93 done = YES; 94 } /* end if */ 95 96 } /* end while */ 97 98 ++moveTotal[ moveNumber ]; 99 } /* end for */ 100 101 /* dislay how many tours of each move number were made */ 102 for ( i = 1; i < 65; i++ ) { 103 104 if ( moveTotal[ i ] ) { 105 printf( "There were %d tours of %d moves.\n", 106 moveTotal[ i ], i ); 107 } /* end if */ 108 109 } /* end for */ 110 111 return 0; /* indicate successful termination */ 112 113 } /* end main */ 114 115 /* function to determine if a move is legal */ 116 int validMove( int testRow, int testColumn, int board[][ 8 ] ) 117 { 118 119 /* test if square is on board and if knight has previously 120 visited it */ 121 if ( testRow >= 0 && testRow < 8 && testColumn >= 0 && 122 testColumn < 8 ) { 123 return board[ testRow ][ testColumn ] != 0 ? NO : YES; 124 125 } /* end if */ 126 else { 127 return NO; 128 } /* end else */ 129 130 } /* end function validMove */ C Arrays: Solutions 207 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 208 C Arrays: Solutions Chapter 6 There were 1 tours of 4 moves. There were 3 tours of 5 moves. There were 2 tours of 6 moves. There were 3 tours of 7 moves. There were 2 tours of 8 moves. There were 4 tours of 10 moves. There were 5 tours of 11 moves. There were 4 tours of 12 moves. There were 5 tours of 13 moves. There were 7 tours of 14 moves. There were 7 tours of 15 moves. There were 9 tours of 16 moves. There were 8 tours of 17 moves. There were 10 tours of 18 moves. There were 9 tours of 19 moves. There were 9 tours of 20 moves. There were 11 tours of 21 moves. There were 19 tours of 22 moves. There were 17 tours of 23 moves. There were 18 tours of 24 moves. There were 12 tours of 25 moves. There were 20 tours of 26 moves. There were 14 tours of 27 moves. There were 18 tours of 28 moves. There were 22 tours of 29 moves. There were 21 tours of 30 moves. There were 31 tours of 31 moves. There were 28 tours of 32 moves. There were 25 tours of 33 moves. There were 32 tours of 34 moves. There were 26 tours of 35 moves. There were 40 tours of 36 moves. There were 38 tours of 37 moves. There were 38 tours of 38 moves. There were 37 tours of 39 moves. There were 33 tours of 40 moves. There were 35 tours of 41 moves. There were 34 tours of 42 moves. There were 33 tours of 43 moves. There were 36 tours of 44 moves. There were 30 tours of 45 moves. There were 35 tours of 46 moves. There were 26 tours of 47 moves. There were 37 tours of 48 moves. There were 22 tours of 49 moves. There were 17 tours of 50 moves. There were 20 tours of 51 moves. There were 21 tours of 52 moves. There were 17 tours of 53 moves. There were 19 tours of 54 moves. There were 14 tours of 55 moves. There were 3 tours of 56 moves. There were 7 tours of 57 moves. There were 3 tours of 59 moves. There were 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. Chapter 6 C Arrays: Solutions 209 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 prob- lem? 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 /* Exercise 6.28 Solution */ 2 #include 3 #include 4 #include 5 6 #define SIZE 20 7 8 int main() 9{ 10 int loop; /* loop counter */ 11 int randNumber; /* current random number */ 12 int loop2; /* loop counter */ 13 int subscript = 0; /* array subscript counter */ 14 int duplicate; /* duplicate flag */ 15 int array[ SIZE ] = { 0 }; /* array of random numbers */ 16 17 srand( time( NULL ) ); 18 19 /* loop 20 times */ 20 for ( loop = 0; loop <= SIZE - 1; loop++ ) { 21 duplicate = 0; 22 randNumber = 1 + rand() % 20; /* generate random number */ 23 24 /* loop through current numbers in array */ 25 for ( loop2 = 0; loop2 <= subscript; loop2++ ) { 26 27 /* compare randNumber with previous numbers */ 28 if ( randNumber == array[ loop2 ] ) { 29 duplicate = 1; 30 break; 31 } /* end if */ 32 33 } /* end for */ 34 35 /* if not a duplicate */ 36 if ( !duplicate ) { 37 array[ subscript++ ] = randNumber; 38 } /* end if */ 39 40 } /* end while */ 41 42 printf( "Non-repetitive array values are:\n" ); 43 44 /* display array */ 45 for ( loop = 0; array[ loop ] != 0; loop++ ) { 46 printf( "\t\t\t\tArray[ %d ] = %d\n", loop, array[ loop ] ); 47 } /* end for */ 48 49 return 0; /* indicate successful termination */ 50 51 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 Non-repetitive array values are: Array[ 0 ] = 11 Array[ 1 ] = 17 Array[ 2 ] = 3 Array[ 3 ] = 18 Array[ 4 ] = 9 Array[ 5 ] = 2 Array[ 6 ] = 20 Array[ 7 ] = 4 Array[ 8 ] = 1 Array[ 9 ] = 10 Array[ 10 ] = 7 Array[ 11 ] = 13 Array[ 12 ] = 19 Array[ 13 ] = 6 Array[ 14 ] = 8 Array[ 15 ] = 16 C Arrays: Solutions 211 © 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 /* Exercise 6.29 Solution */ 2 #include 3 #include 4 #include 5 6 #define TRUE 1 7 #define FALSE 0 8 9 /* function prototypes */ 10 void clearBoard( int workBoard[][ 8 ] ); 11 void printBoard( int workBoard[][ 8 ] ); 12 int validMove( int row, int column, int workBoard[][ 8 ] ); 13 14 int main( void ) 15 { 16 17 int firstMoveRow; /* starting row */ 18 int firstMoveCol; /* starting column */ 19 int closedTour = 0; /* closed tour flag */ 20 int currentRow; /* current row */ 21 int currentColumn; /* current column */ 22 int moveNumber = 0; /* move counter */ 23 int testRow; /* possible next row */ 24 int testColumn; /* possible next column */ 25 int minRow; /* minimum row access number */ 26 int minColumn; /* minimum column access number */ 27 int minAccess = 9; /* access number reset */ 28 int accessNumber; /* current access number */ 29 int moveType; /* current move type */ 30 int done; /* flag to indicate end */ 31 int board[ 8 ][ 8 ]; /* chess board */ 32 33 /* horizontal and vertical moves for the knight */ 34 int horizontal[ 8 ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 35 int vertical[ 8 ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 36 37 /* access grid */ 38 int access[ 8 ][ 8 ] = { 2, 3, 4, 4, 4, 4, 3, 2, 39 3, 4, 6, 6, 6, 6, 4, 3, 40 4, 6, 8, 8, 8, 8, 6, 4, 41 4, 6, 8, 8, 8, 8, 6, 4, 42 4, 6, 8, 8, 8, 8, 6, 4, 43 4, 6, 8, 8, 8, 8, 6, 4, 44 3, 4, 6, 6, 6, 6, 4, 3, 45 2, 3, 4, 4, 4, 4, 3, 2 }; 46 47 48 srand( time( NULL ) ); 49 50 clearBoard( board ); /* initialize array board */ 51 currentRow = rand() % 8; 52 currentColumn = rand() % 8; 53 firstMoveRow = currentRow; /* store first moves row */ 54 firstMoveCol = currentColumn; /* store first moves col */ 55 56 board[ currentRow ][ currentColumn ] = ++moveNumber; 57 done = FALSE; 58 59 /* loop while knight can still move */ 60 while ( !done ) { 61 accessNumber = minAccess; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 213 62 63 /* test what moves knight can make */ 64 for ( moveType = 0; moveType < 8; moveType++ ) { 65 testRow = currentRow + vertical[ moveType ]; 66 testColumn = currentColumn + horizontal[ moveType ]; 67 68 /* if the knight can make a valid move */ 69 if ( validMove( testRow, testColumn, board ) ) { 70 71 /* if move has lowest accessNumber, move to that space */ 72 if ( access[ testRow ][ testColumn ] < accessNumber ) { 73 accessNumber = access[ testRow ][ testColumn ]; 74 minRow = testRow; 75 minColumn = testColumn; 76 } /* end if */ 77 78 --access[ testRow ][ testColumn ]; 79 } /* end if */ 80 81 } /* end for */ 82 83 /* if knight cannot access any more squares, loop terminates */ 84 if ( accessNumber == minAccess ) { 85 done = TRUE; 86 } /* end if */ 87 else { 88 currentRow = minRow; 89 currentColumn = minColumn; 90 board[ currentRow ][ currentColumn ] = ++moveNumber; 91 92 /* check for closed tour */ 93 if ( moveNumber == 64 ) { 94 95 /* loop through possible next moves */ 96 for ( moveType = 0; moveType < 8; moveType++ ) { 97 testRow = currentRow + vertical[ moveType ]; 98 testColumn = currentColumn + horizontal[ moveType ]; 99 100 /* test if knight is one move away from start */ 101 if ( testRow == firstMoveRow && testColumn == 102 firstMoveCol ) { 103 closedTour = 1; 104 } /* end if */ 105 106 } /* end for */ 107 108 } /* end if */ 109 110 } /* end else */ 111 112 } /* end while */ 113 114 printf( "The tour ended with %d moves.\n", moveNumber ); 115 116 /* display results of tour */ 117 if ( moveNumber == 64 && closedTour == 1 ) { 118 printf( "This was a closed tour!\n\n" ); 119 } /* end if */ 120 else if ( moveNumber == 64 ) { 121 printf( "This was a full tour!\n\n" ); 122 } /* end else if */ 123 else { 124 printf( "This was not a full tour.\n\n" ); 125 } /* end else */ 126 127 printf( "The board for this test is:\n\n" ); 128 printBoard( board ); 129 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 214 C Arrays: Solutions Chapter 6 130 return 0; /* indicate successful termination */ 131 132 } /* end main */ 133 134 /* function to clear the chess board */ 135 void clearBoard( int workBoard[][ 8 ] ) 136 { 137 int row; /* row counter */ 138 int col; /* col counter */ 139 140 /* set all values on board to 0 */ 141 for ( row = 0; row < 8; row++ ) { 142 143 for ( col = 0; col < 8; col++ ) { 144 workBoard[ row ][ col ] = 0; 145 } /* end for */ 146 147 } /* end for */ 148 149 } /* end function clearBoard */ 150 151 /* function to print the chesboard */ 152 void printBoard( int workBoard[][ 8 ] ) 153 { 154 int row; /* row counter */ 155 int col; /* column counter */ 156 157 printf( " 0 1 2 3 4 5 6 7\n" ); 158 159 /* print rows of chessboard */ 160 for ( row = 0; row < 8; row++ ) { 161 printf( "%d", row ); 162 163 /* print columns of chess board */ 164 for ( col = 0; col < 8; col++ ) { 165 printf( "%3d", workBoard[ row ][ col ] ); 166 } /* end for */ 167 168 printf( "\n" ); 169 } /* end for */ 170 171 printf( "\n" ); 172 } /* end function printBoard */ 173 174 /* function to determine if a move is valid */ 175 int validMove( int row, int column, int workBoard[][ 8 ] ) 176 { 177 178 /* NOTE: This test stops as soon as it becomes false */ 179 return ( row >= 0 && row < 8 && column >= 0 && 180 column < 8 && workBoard[ row ][ column ] == 0 ); 181 182 } /* end function validMove */ The tour ended with 64 moves. This was a full tour! The board for this test is: 01234567 0 32 13 34 57 30 15 42 19 1 35 58 31 14 47 18 29 16 2 12 33 60 49 56 41 20 43 3 59 36 55 46 25 48 17 28 4 54 11 50 61 40 27 44 21 5 37 62 53 26 45 24 3 6 6 10 51 64 39 8 5 22 1 7 63 38 9 52 23 2 7 4 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 215 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 /* Exercise 6.30 Solution */ 2 #include 3 #define SIZE 1000 4 5 int main() 6{ 7 int array[ SIZE ]; /* array to indicate prime numbers */ 8 int loop; /* loop counter */ 9 int loop2; /* loop counter */ 10 int count = 0; /* total prime numbers */ 11 12 /* set all array elements to 1 */ 13 for ( loop = 0; loop < SIZE; loop++ ) { 14 array[ loop ] = 1; 15 } /* end for */ 16 17 /* test for multiples of current subscript */ 18 for ( loop = 1; loop < SIZE; loop++ ) { 19 20 /* start with array subscript two */ 21 if ( array[ loop ] == 1 && loop != 1 ) { 22 23 /* loop through remainder of array */ 24 for ( loop2 = loop; loop2 <= SIZE; loop2++ ) { 25 26 /* set to zero all multiples of loop */ 27 if ( loop2 % loop == 0 && loop2 != loop ) { 28 array[ loop2 ] = 0; 29 } /* end if */ 30 31 } /* end for */ 32 33 } /* end if */ 34 35 } /* end for */ 36 37 /* display prime numbers in the range 2 - 197 */ 38 for ( loop = 2; loop < SIZE; loop++ ) { 39 40 if ( array[ loop ] == 1 ) { 41 printf( "%3d is a prime number.\n", loop ); 42 ++count; 43 } /* end if */ 44 45 } /* end for */ 46 47 printf( "A total of %d prime numbers were found.\n", count ); 48 49 return 0; /* indicate successful termination */ 50 51 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 216 C Arrays: Solutions Chapter 6 2 is a prime number. 3 is a prime number. 5 is a prime number. 7 is a prime number. 11 is a prime number. 13 is a prime number. 17 is a prime number. 19 is a prime number. . . . 971 is a prime number. 977 is a prime number. 983 is a prime number. 991 is a prime number. 997 is a prime number. A total of 168 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 /* Exercise 6.31 Solution */ 2 #include 3 4 /* symbolic constant SIZE must be defined as the array size 5 for bucketSort to work */ 6 #define SIZE 12 7 8 /* function prototypes */ 9 void bucketSort( int a[] ); 10 void distributeElements( int a[], int buckets[][ SIZE ], int digit ); 11 void collectElements( int a[], int buckets[][ SIZE ] ); 12 int numberOfDigits( int b[], int arraySize ); 13 void zeroBucket( int buckets[][ SIZE ] ); 14 15 int main() 16 { 17 18 /* array to be sorted */ 19 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. Chapter 6 C Arrays: Solutions 217 20 int i; /* loop counter */ 21 22 printf( "Array elements in original order:\n" ); 23 24 /* display the unsorted array */ 25 for ( i = 0; i < SIZE; i++ ) { 26 printf( "%3d", array[ i ] ); 27 } /* end for */ 28 29 putchar( '\n' ); 30 bucketSort( array ); /* sort the array */ 31 32 printf( "\nArray elements in sorted order:\n" ); 33 34 /* display sorted array */ 35 for ( i = 0; i < SIZE; i++ ) { 36 printf( "%3d", array[ i ] ); 37 } /* end for */ 38 39 putchar( '\n' ); 40 41 return 0; /* indicate successful termination */ 42 43 } /* end main */ 44 45 /* Perform the bucket sort algorithm */ 46 void bucketSort( int a[] ) 47 { 48 int totalDigits; /* largest # of digits in array */ 49 int i; /* loop counter */ 50 int bucket[ 10 ][ SIZE ] = { 0 }; /* initialize bucket array */ 51 52 totalDigits = numberOfDigits( a, SIZE ); 53 54 /* put elements in buckets for sorting 55 one sorted, get elements from buckets */ 56 for ( i = 1; i <= totalDigits; i++ ) { 57 distributeElements( a, bucket, i ); 58 collectElements( a, bucket ); 59 60 /* set all bucket contents to zero */ 61 if ( i != totalDigits ) { 62 zeroBucket( bucket ); 63 } /* end if */ 64 65 } /* end for */ 66 67 } /* end function bucketSort */ 68 69 /* Determine the number of digits in the largest number */ 70 int numberOfDigits( int b[], int arraySize ) 71 { 72 int largest = b[ 0 ]; /* assume first element is largest */ 73 int i; /* loop counter */ 74 int digits = 0; /* total number of digits */ 75 76 /* find largest array element */ 77 for ( i = 1; i < arraySize; i++ ) { 78 79 if ( b[ i ] > largest ) { 80 largest = b[ i ]; 81 } /* end if */ 82 83 } /* end for */ 84 85 /* find number of digits of largest element */ 86 while ( largest != 0 ) { 87 ++digits; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 218 C Arrays: Solutions Chapter 6 88 largest /= 10; 89 } /* end while */ 90 91 return digits; /* return number of digits */ 92 93 } /* end function numberOfDigits */ 94 95 /* Distribute elements into buckets based on specified digit */ 96 void distributeElements( int a[], int buckets[][ SIZE ], int digit ) 97 { 98 int divisor = 10; /* used to get specific digit */ 99 int i; /* loop counter */ 100 int bucketNumber; /* current bucket number */ 101 int elementNumber; /* current element number */ 102 103 /* determine the divisor */ 104 for ( i = 1; i < digit; i++ ) { 105 divisor *= 10; 106 } /* end for */ 107 108 /* bucketNumber example for hundreds digit: */ 109 /* ( 1234 % 1000 - 1234 % 100 ) / 100 --> 2 */ 110 for ( i = 0; i < SIZE; i++ ) { 111 bucketNumber = ( a[ i ] % divisor - a[ i ] % ( divisor / 10 ) ) / 112 ( divisor / 10 ); 113 114 /* retrieve value in buckets[ bucketNumber ][ 0 ] to determine */ 115 /* which element of the row to store a[ i ] in. */ 116 elementNumber = ++buckets[ bucketNumber ][ 0 ]; 117 buckets[ bucketNumber ][ elementNumber ] = a[ i ]; 118 } /* end for */ 119 120 } /* end function distributeElements */ 121 122 /* Return elements to original array */ 123 void collectElements( int a[], int buckets[][ SIZE ] ) 124 { 125 int i; /* loop counter */ 126 int j; /* loop counter */ 127 int subscript = 0; /* current subscript */ 128 129 /* retrieve elements from buckets */ 130 for ( i = 0; i < 10; i++ ) { 131 132 for ( j = 1; j <= buckets[ i ][ 0 ]; j++ ) { 133 a[ subscript++ ] = buckets[ i ][ j ]; 134 } /* end for */ 135 136 } /* end for */ 137 138 } /* end function collectElements */ 139 140 /* Set all buckets to zero */ 141 void zeroBucket( int buckets[][ SIZE ] ) 142 { 143 int i; /* loop counter */ 144 int j; /* loop counter */ 145 146 for ( i = 0; i < 10; i++ ) { 147 148 for ( j = 0; j < SIZE; j++ ) { 149 buckets[ i ][ j ] = 0; 150 } /* end for */ 151 152 } /* end for */ 153 154 } /* end function zeroBucket */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 219 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 /* Exercise 6.32 Solution */ 2 #include 3 #include 4 #include 5 6 #define MAXRANGE 1000 7 #define SIZE 10 8 9 void selectionSort( int array[], int size ); /* function prototype */ 10 11 int main() 12 { 13 int sortThisArray[ SIZE ] = { 0 }; /* array to be sorted */ 14 int loop; /* loop counter */ 15 16 srand( time( NULL ) ); /* seed random number generator */ 17 18 /* fill array with random numbers between 1-1000 */ 19 for ( loop = 0; loop < SIZE; loop++ ) { 20 sortThisArray[ loop ] = 1 + rand() % MAXRANGE; 21 } /* end for */ 22 23 printf( "\nUnsorted array is:\n" ); 24 25 /* display unsorted array */ 26 for ( loop = 0; loop < SIZE; loop++ ) { 27 printf( " %d ", sortThisArray[ loop ] ); 28 } /* end for */ 29 30 selectionSort( sortThisArray, SIZE ); /* sort array */ 31 32 printf( "\n\nSorted array is:\n" ); 33 34 /* display sorted array */ 35 for ( loop = 0; loop < SIZE; loop++ ) { 36 printf( " %d ", sortThisArray[ loop ] ); 37 } /* end for */ 38 39 printf( "\n\n" ); 40 41 return 0; /* indicate successful termination */ 42 43 } /* end main */ 44 45 /* function to sort an array */ 46 void selectionSort( int array[], int size ) 47 { 48 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 int loop; /* loop counter */ 50 51 /* sort array until only one element is left */ 52 if ( size >= 1 ) { 53 54 /* find smallest element and put it in first position */ 55 for ( loop = 0; loop <= size - 1; loop++ ) { 56 57 /* swap elements */ 58 if ( array[ loop ] < array[ 0 ] ) { 59 temp = array[ loop ]; 60 array[ loop ] = array[ 0 ]; 61 array[ 0 ] = temp; 62 } /* end if */ 63 64 } /* end for */ 65 66 /* recursive call to selectionSort */ 67 selectionSort( &array[ 1 ], size - 1 ); 68 } /* end for */ 69 70 } /* end function selectionSort */ Unsorted array is: 629 748 87 955 484 505 799 377 11 287 Sorted array is: 11 87 287 377 484 505 629 748 799 955 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 221 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 /* Exercise 6.33 solution */ 2 #include 3 #define SIZE 80 4 5 /* function prototype */ 6 int testPalindrome( char array[], int left, int right ); 7 8 int main() 9{ 10 char c; /* temporarily holds keyboard input */ 11 char string[ SIZE ]; /* original string */ 12 char copy[ SIZE ]; /* copy of string without spaces */ 13 int count = 0; /* length of string */ 14 int copyCount; /* length of copy */ 15 int i; /* counter */ 16 17 printf( "Enter a sentence:\n" ); 18 19 /* get sentence to test from user */ 20 while ( ( c = getchar() ) != '\n' && count < SIZE ) { 21 string[ count++ ] = c; 22 } /* end while */ 23 24 string[ count ] = '\0'; /* terminate string */ 25 26 /* make a copy of string without spaces */ 27 for ( copyCount = 0, i = 0; string[ i ] != '\0'; i++ ) { 28 29 if ( string[ i ] != ' ' ) { 30 copy[ copyCount++ ] = string[ i ]; 31 } /* end if */ 32 33 } /* end for */ 34 35 /* print whether or not the sentence is a palindrome */ 36 if ( testPalindrome( copy, 0, copyCount - 1 ) ) { 37 printf( "\"%s\" is a palindrome\n", string ); 38 } /* end if */ 39 else { 40 printf( "\"%s\" is not a palindrome\n", string ); 41 } /* end else */ 42 43 return 0; /* indicate successful termination */ 44 45 } /* end main */ 46 47 /* function to see if the sentence is a palindrome */ 48 int testPalindrome( char array[], int left, int right ) 49 { 50 51 /* test array to see if a palindrome */ 52 if ( left == right || left > right ) { 53 return 1; 54 } /* end if */ 55 else if ( array[ left ] != array[ right ] ) { 56 return 0; 57 } /* end else if */ 58 else { 59 return testPalindrome( array, left + 1, right - 1 ); 60 } /* end else */ 61 62 } /* 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 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 223 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 /* Exercise 6.34 Solution */ 2 #include 3 #define SIZE 100 4 5 /* function prototypes */ 6 int linearSearch( int array[], int key, int low, int high ); 7 8 int main() 9{ 10 int array[ SIZE ]; /* array to be searched */ 11 int loop; /* loop counter */ 12 int searchKey; /* element to search for */ 13 int element; /* result of linear search */ 14 15 /* initialize array elements */ 16 for ( loop = 0; loop < SIZE; loop++ ) { 17 array[ loop ] = 2 * loop; 18 } /* end for */ 19 20 /* obtain search key from user */ 21 printf( "Enter the integer search key: " ); 22 scanf( "%d", &searchKey ); 23 24 /* search array for search key */ 25 element = linearSearch( array, searchKey, 0, SIZE - 1 ); 26 27 /* display message if search key was found */ 28 if ( element != -1 ) { 29 printf( "Found value in element %d\n", element ); 30 } /* end if */ 31 else { 32 printf( "Value not found\n" ); 33 } /* end else */ 34 35 return 0; /* indicate successful termination */ 36 37 } /* end main */ 38 39 /* function to search array for specified key */ 40 int linearSearch( int array[], int key, int low, int high ) 41 { 42 43 /* recursively search array */ 44 if ( array[ low ] == key ) { 45 return low; 46 } /* end if */ 47 else if ( low == high ) { 48 return -1; 49 } /* end else if */ 50 else { /* recursive call */ 51 return linearSearch( array, key, low + 1, high ); 52 } /* end else */ 53 54 } /* 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 Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 C Arrays: Solutions 225 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 /* Exercise 6.35 Solution */ 2 #include 3 #define SIZE 15 4 5 /* function prototypes */ 6 int binarySearch( int b[], int searchKey, int low, int high ); 7 void printHeader( void ); 8 void printRow( int b[], int low, int mid, int high ); 9 10 int main() 11 { 12 int a[ SIZE ]; /* array to be searched */ 13 int i; /* loop counter */ 14 int key; /* search key */ 15 int result; /* result of search */ 16 17 /* initialize array elements */ 18 for ( i = 0; i < SIZE; i++ ) { 19 a[ i ] = 2 * i; 20 } /* end for */ 21 22 /* obtain key from user */ 23 printf( "Enter a number between 0 and 28: " ); 24 scanf( "%d", &key ); 25 26 printHeader(); 27 28 /* search array for key */ 29 result = binarySearch( a, key, 0, SIZE - 1 ); 30 31 /* display results of the search */ 32 if ( result != -1 ) { 33 printf( "\n%d found in array element %d\n", key, result ); 34 } /* end if */ 35 else { 36 printf( "\n%d not found\n", key ); 37 } /* end else */ 38 39 return 0; /* indicate successful termination */ 40 41 } /* end main */ 42 43 /* function to search array for specified key */ 44 int binarySearch( int b[], int searchKey, int low, int high ) 45 { 46 int middle; /* middle of array */ 47 48 /* find middle of array and print current subarray */ 49 if ( low <= high ) { 50 middle = ( low + high ) / 2; 51 printRow( b, low, middle, high ); 52 53 /* determine if middle element is the key and if not, 54 recursively call binarySearch */ 55 if ( searchKey == b[ middle ] ) { 56 return middle; 57 } /* end if */ 58 else if ( searchKey < b[ middle ] ) { 59 /* recursive call on bottom half of array */ 60 return binarySearch( b, searchKey, low, middle - 1 ); 61 } /* end else if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 226 C Arrays: Solutions Chapter 6 62 else { 63 /* recursive call on upper half of array */ 64 return binarySearch( b, searchKey, middle + 1, high ); 65 } /* end else */ 66 67 } /* end if */ 68 69 return -1; /* searchKey not found */ 70 71 } /* end function binarySearch */ 72 73 /* Print a header for the output */ 74 void printHeader( void ) 75 { 76 int i; /* loop counter */ 77 78 printf( "\nSubscripts:\n" ); 79 80 /* print subscripts of array */ 81 for ( i = 0; i < SIZE; i++ ) { 82 printf( "%3d ", i ); 83 } /* end for */ 84 85 printf( "\n" ); 86 87 /* print dividing line */ 88 for ( i = 1; i <= 4 * SIZE; i++ ) { 89 printf( "-" ); 90 } /* end for */ 91 92 printf( "\n" ); 93 } /* end function printHeader */ 94 95 /* print one row of output showing the current 96 part of the array being processed. */ 97 void printRow( int b[], int low, int mid, int high ) 98 { 99 int i; /* loop counter */ 100 101 /* print subarray currently being processed */ 102 for ( i = 0; i < SIZE; i++ ) { 103 104 if ( i < low || i > high ) { 105 printf( " " ); 106 } /* end if */ 107 else if ( i == mid ) { /* mark middle value */ 108 printf( "%3d*", b[ i ] ); 109 } /* end else if */ 110 else { 111 printf( "%3d ", b[ i ] ); 112 } /* end else */ 113 114 } /* end for */ 115 116 printf( "\n" ); 117 } /* 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 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 C Arrays: Solutions 227 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 228 C Arrays: Solutions Chapter 6 6.36 (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 /* Exercise 6.37 Solution */ 2 #include 3 #include 4 #include 5 6 #define SIZE 10 7 8 /* function prototype */ 9 void printArray( int array[], int low, int high ); 10 11 int main() 12 { 13 int array[ SIZE ]; /* array to be printed */ 14 int loop; /* loop counter */ 15 16 srand( time( NULL ) ); 17 18 /* initialize array elements to random numbers */ 19 for ( loop = 0; loop < SIZE; loop++ ) { 20 array[ loop ] = 1 + rand() % 500; 21 } /* end for */ 22 23 printf( "Array values printed in main:\n" ); 24 25 /* print array elements */ 26 for ( loop = 0; loop < SIZE; loop++ ) { 27 printf( "%d ", array[ loop ] ); 28 } /* end for */ 29 30 printf( "\n\nArray values printed in printArray:\n" ); 31 printArray( array, 0, SIZE - 1 ); 32 printf( "\n" ); 33 34 return 0; /* indicate successful termination */ 35 36 } /* end main */ 37 38 /* function to recursively print an array */ 39 void printArray( int array[], int low, int high ) 40 { 41 /* print first element of array passed */ 42 printf( "%d ", array[ low ] ); 43 44 /* return if array only has 1 element */ 45 if ( low == high ) { 46 return; 47 } /* end if */ 48 else { /* call printArray with new subarray */ 49 printArray( array, low + 1, high ); 50 } /* end else */ 51 52 } /* 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. Chapter 6 C Arrays: Solutions 229 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 /* Exercise 6.38 Solution */ 2 #include 3 #define SIZE 30 4 5 void stringReverse( char strArray[] ); /* function prototype */ 6 7 int main() 8{ 9 int loop; /* loop counter */ 10 11 /* initialize string strArray */ 12 char strArray[ SIZE ] = "Print this string backwards."; 13 14 /* display original string */ 15 for ( loop = 0; loop < SIZE; loop++ ) { 16 printf( "%c", strArray[ loop ] ); 17 } /* end for */ 18 19 printf( "\n" ); 20 stringReverse( strArray ); /* reverse the string */ 21 printf( "\n" ); 22 23 return 0; /* indicate successful termination */ 24 25 } /* end main */ 26 27 /* function to reverse a string */ 28 void stringReverse( char strArray[] ) 29 { 30 31 /* return when null character is encountered */ 32 if ( strArray[ 0 ] == '\0' ) { 33 return; 34 } /* end if */ 35 36 /* recursively call stringReverse with new substring */ 37 stringReverse( &strArray[ 1 ] ); 38 printf( "%c", strArray[ 0 ] ); /* output string elements */ 39 } /* 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 /* Exercise 6.39 Solution */ 2 #include 3 #include 4 #include 5 #define SIZE 10 6 #define MAXRANGE 1000 7 8 /* function prototype */ 9 int recursiveMinimum( int array[], int low, int high ); 10 11 int main() 12 { 13 int array[ SIZE ]; /* array to be searched */ 14 int loop; /* loop counter */ 15 int smallest; /* smallest element */ 16 17 srand( time( NULL ) ); 18 19 /* initialize elements of array to random numbers */ 20 for ( loop = 0; loop < SIZE; loop++ ) { 21 array[ loop ] = 1 + rand() % MAXRANGE; 22 } /* end for */ 23 24 printf( "Array members are:\n" ); 25 26 /* display array */ 27 for ( loop = 0; loop < SIZE; loop++ ) { 28 printf( " %d ", array[ loop ] ); 29 } /* end for */ 30 31 /* find and display smallest array element */ 32 printf( "\n" ); 33 smallest = recursiveMinimum( array, 0, SIZE - 1 ); 34 printf( "\nSmallest element is: %d\n", smallest ); 35 36 return 0; /* indicate successful termination */ 37 38 } /* end main */ 39 40 /* function to recursively find minimum array element */ 41 int recursiveMinimum( int array[], int low, int high ) 42 { 43 static int smallest = MAXRANGE; /* largest possible value */ 44 45 /* if first element of array is smallest so far, 46 set smallest equal to that element */ 47 if ( array[ low ] < smallest ) { 48 smallest = array[ low ]; 49 } /* end if */ 50 51 /* if only one element in array, return smallest */ 52 if ( low == high ) { 53 return smallest; 54 } /* end if */ 55 else { /* recursively call recursiveMinimum with new subarray */ 56 return recursiveMinimum( array, low + 1, high ); 57 } /* end else */ 58 59 } /* end function recursiveMinimum */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 6 Array members are: 666 251 624 359 577 837 992 197 249 492 Smallest element is: 197 C Arrays: Solutions 231 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 232 C Arrays: Solutions Chapter 6 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7 Pointers: Solutions SOLUTIONS 7.7 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 of the variable to the function. ANS: address. 7.8 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 vari- able 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. Chapter 7 Pointers: Solutions 235 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 /* Exercise 7.16 Solution */ 2 #include 3 #include 4 #include 5 6 /* function prototypes */ 7 void shuffle( int workDeck[][ 13 ] ); 8 void deal( int workDeck[][ 13 ], char *workFace[], char *workSuit[] ); 9 10 int main() 11 { 12 int card = 1; /* card counter */ 13 int row; /* loop counter */ 14 int column; /* loop counter */ 15 int deck[ 4 ][ 13 ]; /* array of cards */ 16 17 /* define arrays of card suits and faces */ 18 char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"}; 19 char *face[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", 20 "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; 21 22 srand( time( NULL ) ); 23 24 /* initialize deck */ 25 for ( row = 0; row <= 3; row++ ) { 26 27 for ( column = 0; column <= 12; column++ ) { 28 deck[ row ][ column ] = card++; 29 } /* end for */ 30 31 } /* end for */ 32 33 shuffle( deck ); 34 deal( deck, face, suit ); 35 36 return 0; /* indicate successful termination */ 37 38 } /* end main */ 39 40 /* introduce another way to shuffle */ 41 void shuffle( int workDeck[][ 13 ] ) 42 { 43 int temp; /* temporary holder */ 44 int row; /* loop counter */ 45 int column; /* loop counter */ 46 int randRow; /* random suit */ 47 int randColumn; /* random face */ 48 49 /* run through the loop and touch every element once */ 50 for ( row = 0; row <= 3; row++ ) { 51 52 for ( column = 0; column <= 12; column++ ) { 53 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 237 54 /* generate a random card */ 55 randRow = rand() % 4; 56 randColumn = rand() % 13; 57 58 /* swap random card with current card */ 59 temp = workDeck[ row ][ column ]; 60 workDeck[ row ][ column ] = workDeck[ randRow ][ randColumn ]; 61 workDeck[ randRow ][ randColumn ] = temp; 62 } /* end for */ 63 64 } /* end for */ 65 66 } /* end function shuffle */ 67 68 /* deal the cards */ 69 void deal( int workDeck2[][ 13 ], char *workFace[], char *workSuit[] ) 70 { 71 int card; /* card counter */ 72 int row; /* loop counter */ 73 int column; /* loop counter */ 74 75 /* loop through and print the cards */ 76 for ( card = 1; card <= 52; card++ ) { 77 78 /* loop through rows */ 79 for ( row = 0; row <= 3; row++ ) { 80 81 /* loop through columns */ 82 for ( column = 0; column <= 12; column++ ) { 83 84 /* if current card equals card then deal */ 85 if ( workDeck2[ row ][ column ] == card ) { 86 printf( "%5s of %-8s", workFace[ column ], workSuit[ row ] ); 87 card % 2 == 0 ? putchar( '\n' ) : putchar( '\t' ); 88 break; /* break loop */ 89 } /* end if */ 90 91 } /* end for */ 92 93 } /* end for */ 94 95 } /* end for */ 96 97 } /* end function deal */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 238 Pointers: Solutions Eight of Spades Five of Hearts Eight of Diamonds Deuce of Hearts Seven of Clubs Four of Clubs Six of Spades Ten of Hearts Four of Diamonds Jack of Diamonds Deuce of Spades Three of Hearts Nine of Hearts King of Spades Five of Spades Four of Spades King of Diamonds Deuce of Clubs Ace of Diamonds Eight of Hearts Nine of Clubs Three of Clubs Queen of Hearts Queen of Diamonds Five of Clubs Jack of Spades Ace of Spades Ace of Hearts Queen of Spades Seven of Hearts Six of Hearts Ace of Clubs Ten of Diamonds King of Hearts Four of Hearts Three of Diamonds Queen of Clubs Six of Clubs Nine of Diamonds Seven of Diamonds Seven of Spades Ten of Spades Nine of Spades Jack of Hearts Ten of Clubs Six of Diamonds Five of Diamonds Deuce of Diamonds King of Clubs Jack of Clubs Three of Spades Eight of Clubs Chapter 7 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 239 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 50% Slip 20% Slow plod 30% Hare Sleep 20% Big hop 20% Big slip 10% Small hop 30% Small slip 20% 3 squares to the right 6 squares to the left 1 square to the right 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 /* Exercise 7.17 Solution */ 2 #include 3 #include 4 #include 5 6 /* function prototypes */ 7 void moveTortoise( int *turtlePtr ); 8 void moveHare( int *rabbitPtr ); 9 void printCurrentPositions( int *snapperPtr, int *bunnyPtr ); 10 11 int main() 12 { 13 int tortoise = 1; /* tortoise current position */ 14 int hare = 1; /* hare current position */ 15 int timer = 0; /* time elapsed during race */ 16 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 240 Pointers: Solutions Chapter 7 17 srand( time( NULL ) ); 18 19 printf( "ON YOUR MARK, GET SET\n" ); 20 printf( "BANG !!!!\n" ); 21 printf( "AND THEY'RE OFF !!!!\n" ); 22 23 /* loop through the events */ 24 while ( tortoise != 70 && hare != 70 ) { 25 moveTortoise( &tortoise ); 26 moveHare( &hare ); 27 printCurrentPositions( &tortoise, &hare ); 28 ++timer; 29 } /* end while */ 30 31 /* determine the winner and print message */ 32 if ( tortoise >= hare ) { 33 printf( "\nTORTOISE WINS!!! YAY!!!\n" ); 34 } /* end if */ 35 else { 36 printf( "Hare wins. Yuch.\n" ); 37 } /* end else */ 38 39 printf( "TIME ELAPSED = %d seconds", timer ); 40 41 return 0; /* indicate successful termination */ 42 43 } /* end main */ 44 45 /* progress for the tortoise */ 46 void moveTortoise( int *turtlePtr ) 47 { 48 int x; /* random number */ 49 50 x = rand() % 10 + 1; /* generate random number from 1-10 */ 51 52 /* determine progress */ 53 if ( x >= 1 && x <= 5 ) { /* fast plod */ 54 *turtlePtr += 3; 55 } /* end if */ 56 else if ( x == 6 || x == 7 ) { /* slip */ 57 *turtlePtr -= 6; 58 } /* end else if */ 59 else { /* slow plod */ 60 ++( *turtlePtr ); 61 } /* end else */ 62 63 /* check boundaries */ 64 if ( *turtlePtr < 1 ) { 65 *turtlePtr = 1; 66 } /* end if */ 67 if ( *turtlePtr > 70 ) { 68 *turtlePtr = 70; 69 } /* end if */ 70 71 } /* end function moveTortoise */ 72 73 /* progress for the hare */ 74 void moveHare( int *rabbitPtr ) 75 { 76 int y; /* random number */ 77 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 78 y = rand() % 10 + 1; /* generate random number from 1-10 */ 79 80 /* determine progress */ 81 if ( y == 3 || y == 4 ) { /* big hop */ 82 *rabbitPtr += 9; 83 } /* end if */ 84 else if ( y == 5 ) { /* big slip */ 85 *rabbitPtr -= 12; 86 } /* end else if */ 87 else if ( y >= 6 && y <= 8 ) { /* small hop */ 88 ++( *rabbitPtr ); 89 } /* end else if */ 90 else if ( y == 10 ) { /* small slip */ 91 *rabbitPtr -= 2; 92 } /* end else if */ 93 94 /* check boundaries */ 95 if ( *rabbitPtr < 1 ) { 96 *rabbitPtr = 1; 97 } /* end if */ 98 99 if ( *rabbitPtr > 70 ) { 100 *rabbitPtr = 70; 101 } /* end if */ 102 103 } /* end function moveHare */ 104 105 /* display new position */ 106 void printCurrentPositions( int *snapperPtr, int *bunnyPtr ) 107 { 108 int count; /* counter */ 109 110 /* loop through race */ 111 for ( count = 1; count <= 70; count++ ) 112 113 /* print current leader */ 114 if ( count == *snapperPtr && count == *bunnyPtr ) { 115 printf( "OUCH!!!" ); 116 } /* end if */ 117 else if ( count == *bunnyPtr ) { 118 printf( "H" ); 119 } /* end else if */ 120 else if ( count == *snapperPtr ) { 121 printf( "T" ); 122 } /* end else if */ 123 else { 124 printf( " " ); 125 } /* end else */ 126 127 printf( "\n" ); 128 } /* end function printCurrentPositions */ Pointers: Solutions 241 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 242 Pointers: Solutions ON YOUR MARK, GET SET BANG !!!! AND THEY'RE OFF !!!! OUCH!!! HT HT 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 HT 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 Hare wins. Yuch. TIME ELAPSED = 88 seconds T TH T H T H T H T H T H T H T T H H Chapter 7 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 243 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 Read a word from the terminal into a specific location in memory. #define WRITE 11 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). #define DIVIDE 32 Divide a word from a specific location in memory into the word in the accumulator (leave result in accumulator). #define MULTIPLY 33 Multiply a word from a specific location in memory by the word in the accumulator (leave result in accumulator). 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 00 01 02 03 04 05 06 07 08 09 10 Number +1009 +1010 +2009 +3110 +4107 +1109 +4300 +1110 +4300 +0000 +0000 Instruction (Read A) (Read B) (Load A) (Subtract B) (Branch negative to 07) (Write A) (Halt) (Write B) (Halt) (Variable A) (Variable B) © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 245 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 +1009 (Read Value) 01 +2009 (Load Value) 02 +4106 (Branch negative to 06) 03 +3008 (Add Sum) 04 +2108 (Store Sum) 05 +4000 (Branch 00) 06 +1108 (Write Sum) 07 +4300 (Halt) 08 +0000 (Variable Sum) 09 +0000 (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 +2018 (Load Counter) 01 +3121 (Subtract Termination) 02 +4211 (Branch zero to 11) 03 +2018 (Load Counter) 04 +3019 (Add Increment) 05 +2118 (Store Counter) 06 +1017 (Read Value) 07 +2016 (Load Sum) 08 +3017 (Add Value) 09 +2116 (Store Sum) 10 +4000 (Branch 00) 11 +2016 (Load Sum) 12 +3218 (Divide Counter) 13 +2120 (Store Result) 14 +1120 (Write Result) 15 +4300 (Halt) 16 +0000 (Variable Sum) 17 +0000 (Variable Value) 18 +0000 (Variable Counter) 19 +0001 (Variable Increment) 20 +0000 (Variable Result) 21 +0007 (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 +1017 (Read Endvalue) 01 +2018 (Load Counter) 02 +3117 (Subtract Endvalue) 03 +4215 (Branch zero to 15) 04 +2018 (Load Counter) 05 +3021 (Add Increment) 06 +2118 (Store Counter) 07 +1019 (Read Value) 08 +2020 (Load Largest) 09 +3119 (Subtract Value) 10 +4112 (Branch negative to 12) 11 +4001 (Branch 01) 12 +2019 (Load Value) 13 +2120 (Store Largest) 14 +4001 (Branch 01) 15 +1120 (Write Largest) 16 +4300 (Halt) 17 +0000 (Variable Endvalue) 18 +0000 (Variable Counter) 19 +0000 (Variable Value) 20 +0000 (Variable Largest) 21 +0001 (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. Chapter 7 Pointers: Solutions 247 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 0 +0000 10 +0000 20 +0000 30 +0000 40 +0000 50 +0000 60 +0000 70 +0000 80 +0000 90 +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 /* Exercise 7.19 Solution */ 2 #include 3 4 /* define commands */ 5 #define SIZE 100 6 #define SENTINEL -99999 7 #define TRUE 1 8 #define FALSE 0 9 #define READ 10 10 #define WRITE 11 11 #define LOAD 20 12 #define STORE 21 13 #define ADD 30 14 #define SUBTRACT 31 15 #define DIVIDE 32 16 #define MULTIPLY 33 17 #define BRANCH 40 18 #define BRANCHNEG 41 19 #define BRANCHZERO 42 20 #define HALT 43 21 22 /* function prototypes */ 23 void load( int *loadMemory ); 24 void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, 25 int *opCodePtr, int *opPtr ); 26 void dump( int *memory, int accumulator, int instructionCounter, 27 int instructionRegister, int operationCode, 28 int operand ); 29 int validWord( int word ); 30 31 int main() 32 { 33 int memory[ SIZE ]; /* define memory array */ 34 int ac = 0; /* accumulator */ 35 int ic = 0; /* instruction counter */ 36 int opCode = 0; /* operation code */ 37 int op = 0; /* operand */ 38 int ir = 0; /* instruction register */ 39 int i; /* counter */ 40 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 249 41 /* clear memory */ 42 for ( i = 0; i < SIZE; i++ ) { 43 memory[ i ] = 0; 44 } /* end for */ 45 46 load( memory ); 47 execute( memory, &ac, &ic, &ir, &opCode, &op ); 48 dump( memory, ac, ic, ir, opCode, op ); 49 50 return 0; /* indicate successful termination */ 51 52 } /* end main */ 53 54 /* function loads instructions */ 55 void load( int *loadMemory ) 56 { 57 long int instruction; /* current instruction */ 58 int i = 0; /* indexing variable */ 59 60 printf( "%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n\n", 61 "*** Welcome to Simpletron ***", 62 "*** Please enter your program one instruction ***", 63 "*** ( or data word ) at a time. I will type the ***", 64 "*** location number and a question mark ( ? ). ***", 65 "*** You then type the word for that location. ***", 66 "*** Type the sentinel -99999 to stop entering ***", 67 "*** your program. ***" ); 68 69 printf( "00 ? " ); 70 scanf( "%ld", &instruction ); /* read instruction */ 71 72 /* while sentinel is not read from user */ 73 while ( instruction != SENTINEL ) { 74 75 /* test instruction for validity */ 76 if ( !validWord( instruction ) ) { 77 printf( "Number out of range. Please enter again.\n" ); 78 } /* end if */ 79 else { /* load instruction */ 80 loadMemory[ i++ ] = instruction; 81 } /* end else */ 82 83 printf( "%02d ? ", i ); 84 scanf( "%ld", &instruction ); 85 } /* end while */ 86 87 } /* end function load */ 88 89 /* carry out the commands */ 90 void execute( int *memory, int *acPtr, int *icPtr, int *irPtr, 91 int *opCodePtr, int *opPtr ) 92 { 93 int fatal = FALSE; /* fatal error flag */ 94 int temp; /* temporary holding space */ 95 96 printf( "\n************START SIMPLETRON EXECUTION************\n\n" ); 97 98 /* separate operation code and operand */ 99 *irPtr = memory[ *icPtr ]; 100 *opCodePtr = *irPtr / 100; 101 *opPtr = *irPtr % 100; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 250 Pointers: Solutions Chapter 7 102 103 /* loop while command is not HALT or fatal */ 104 while ( *opCodePtr != HALT && !fatal ) { 105 106 /* determine appropriate action */ 107 switch ( *opCodePtr ) { 108 109 /* read data into location in memory */ 110 case READ: 111 printf( "Enter an integer: " ); 112 scanf( "%d", &temp ); 113 114 /* check for validity */ 115 while ( !validWord( temp ) ) { 116 printf( "Number out of range. Please enter again: " ); 117 scanf( "%d", &temp ); 118 } /* end while */ 119 120 memory[ *opPtr ] = temp; /* write to memory */ 121 ++( *icPtr ); 122 break; /* exit switch */ 123 124 /* write data from memory to screen */ 125 case WRITE: 126 printf( "Contents of %02d: %d\n", *opPtr, memory[ *opPtr ] ); 127 ++( *icPtr ); 128 break; /* exit switch */ 129 130 /* load data from memory into accumulator */ 131 case LOAD: 132 *acPtr = memory[ *opPtr ]; 133 ++( *icPtr ); 134 break; /* exit switch */ 135 136 /* store data from accumulator into memory */ 137 case STORE: 138 memory[ *opPtr ] = *acPtr; 139 ++( *icPtr ); 140 break; /* exit switch */ 141 142 /* add data from memory to data in accumulator */ 143 case ADD: 144 temp = *acPtr + memory[ *opPtr ]; 145 146 /* check validity */ 147 if ( !validWord( temp ) ) { 148 printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); 149 printf( "*** Simpletron execution abnormally terminated ***\n" ); 150 fatal = TRUE; 151 } /* end if */ 152 else { 153 *acPtr = temp; 154 ++( *icPtr ); 155 } /* end else */ 156 157 break; /* exit switch */ 158 159 /* subtract data in memory from data in accumulator */ 160 case SUBTRACT: 161 temp = *acPtr - memory[ *opPtr ]; 162 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 251 163 /* check validity */ 164 if ( !validWord( temp ) ) { 165 printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); 166 printf( "*** Simpletron execution abnormally terminated ***\n" ); 167 fatal = TRUE; 168 } /* end if */ 169 else { 170 *acPtr = temp; 171 ++( *icPtr ); 172 } /* end else */ 173 174 break; /* exit switch */ 175 176 /* divide data in memory into data in accumulator */ 177 case DIVIDE: 178 179 /* check for divide by zero error */ 180 if ( memory[ *opPtr ] == 0 ) { 181 printf( "*** FATAL ERROR: Attempt to divide by zero ***\n" ); 182 printf( "*** Simpletron execution abnormally terminated ***\n" ); 183 fatal = TRUE; 184 } /* end if */ 185 else { 186 *acPtr /= memory[ *opPtr ]; 187 ++( *icPtr ); 188 } /* end else */ 189 190 break; /* exit switch */ 191 192 /* multiple data in memory by data in accumulator */ 193 case MULTIPLY: 194 temp = *acPtr * memory[ *opPtr ]; 195 196 /* check validity */ 197 if ( !validWord( temp ) ) { 198 printf( "*** FATAL ERROR: Accumulator overflow ***\n" ); 199 printf( "*** Simpletron execution abnormally terminated ***\n" ); 200 fatal = TRUE; 201 } /* end if */ 202 else { 203 *acPtr = temp; 204 ++( *icPtr ); 205 } /* end else */ 206 207 break; /* exit switch */ 208 209 /* branch to specific location in memory */ 210 case BRANCH: 211 *icPtr = *opPtr; 212 break; /* exit switch */ 213 214 /* branch to location in memory if accumulator is negative */ 215 case BRANCHNEG: 216 217 /* if accumulator is negative */ 218 if ( *acPtr < 0 ) { 219 *icPtr = *opPtr; 220 } /* end if */ 221 else { 222 ++( *icPtr ); 223 } /* end else */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 252 Pointers: Solutions Chapter 7 224 225 break; /* exit switch */ 226 227 /* branch to location in memory if accumulator is zero */ 228 case BRANCHZERO: 229 230 /* if accumulator is zero */ 231 if ( *acPtr == 0 ) { 232 *icPtr = *opPtr; 233 } /* end if */ 234 else { 235 ++( *icPtr ); 236 } /* end else */ 237 238 break; /* exit switch */ 239 240 default: 241 printf( "*** FATAL ERROR: Invalid opcode detected ***\n" ); 242 printf( "*** Simpletron execution abnormally terminated ***\n" ); 243 fatal = TRUE; 244 break; /* exit switch */ 245 } /* end switch */ 246 247 /* separate next operation code and operand */ 248 *irPtr = memory[ *icPtr ]; 249 *opCodePtr = *irPtr / 100; 250 *opPtr = *irPtr % 100; 251 } /* end while */ 252 253 printf( "\n*************END SIMPLETRON EXECUTION*************\n" ); 254 } /* end function execute */ 255 256 /* print out name and content of each register and memory */ 257 void dump( int *memory, int accumulator, int instructionCounter, 258 int instructionRegister, int operationCode, 259 int operand ) 260 { 261 int i; /* counter */ 262 263 printf( "\n%s\n%-23s%+05d\n%-23s%5.2d\n%-23s%+05d\n%-23s%5.2d\n%-23s%5.2d", 264 "REGISTERS:", "accumulator", accumulator, "instructioncounter", 265 instructionCounter, "instructionregister", instructionRegister, 266 "operationcode", operationCode, "operand", operand ); 267 268 printf( "\n\nMEMORY:\n " ); 269 270 /* print column headers */ 271 for ( i = 0; i <= 9; i++ ) { 272 printf( "%5d ", i ); 273 } /* end for */ 274 275 /* print row headers and memory contents */ 276 for ( i = 0; i < SIZE; i++ ) { 277 278 /* print in increments of 10 */ 279 if ( i % 10 == 0 ) { 280 printf( "\n%2d ", i ); 281 } /* end if */ 282 283 printf( "%+05d ", memory[ i ] ); 284 } /* end for */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 285 286 printf( "\n" ); 287 } /* end function dump */ 288 289 /* function tests validity of word */ 290 int validWord( int word ) 291 { 292 return word >= -9999 && word <= 9999; 293 294 } /* end function validWord */ 295 *** 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. *** 00 ? 1007 01 ? 1008 02 ? 2007 03 ? 3008 04 ? 2109 05 ? 1109 06 ? 4300 07 ? 0000 08 ? 0000 09 ? 0000 10 ? -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 1 2 3 4 5 6 7 8 9 0 +1007 +1008 +2007 +3008 +2109 +1109 +4300 +0023 +0017 +0040 10 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 20 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 30 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 40 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 50 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 60 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 70 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 80 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 90 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 Pointers: Solutions 253 © 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 /* Exercise 7.20 Solution */ 2 #include 3 #include 4 #include 5 6 /* function prototype */ 7 void shuffleAndDeal( int workdeck[][ 13 ], char *workface[], 8 char *worksuit[] ); 9 10 int main() 11 { 12 13 /* define card suit array and card face array */ 14 char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades"}; 15 char *face[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", 16 "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; 17 int deck[ 4 ][ 13 ] = { 0 }; /* array of cards */ 18 19 srand( time( NULL ) ); 20 21 shuffleAndDeal( deck, face, suit ); 22 23 return 0; /* indicate successful termination */ 24 25 } /* end main */ 26 27 /* integrate shuffling and dealing operation */ 28 void shuffleAndDeal( int workdeck[][ 13 ], char *workface[], 29 char *worksuit[] ) 30 { 31 int card; /* card loop counter */ 32 int row; /* current suit */ 33 int column; /* current face */ 34 35 /* loop through the deck of cards, shuffle and print */ 36 for ( card = 1; card <= 52; card++ ) { 37 38 /* choose random card until not equal to zero */ 39 do { 40 row = rand() % 4; 41 column = rand() % 13; 42 } while( workdeck[ row ][ column ] != 0 ); /* end do...while */ 43 44 workdeck[ row ][ column ] = card; 45 46 /* deal card */ 47 printf( "%5s of %-8s", workface[ column ], worksuit[ row ] ); 48 49 card % 2 == 0 ? printf( "\n" ) : printf( "\t" ); 50 } /* end for */ 51 52 } /* end function shuffleAndDeal */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Seven of Spades Six of Spades Three of Clubs Jack of Diamonds Queen of Clubs Four of Hearts Six of Clubs Three of Hearts Seven of Clubs Ten of Hearts Queen of Hearts Five of Clubs Deuce of Spades Ace of Clubs Five of Spades Deuce of Hearts Nine of Hearts King of Clubs Seven of Diamonds Six of Hearts Nine of Spades Three of Spades Four of Diamonds Ten of Spades Four of Clubs Six of Diamonds King of Diamonds King of Hearts Three of Diamonds Jack of Spades Eight of Hearts Deuce of Clubs Eight of Spades Five of Hearts Ace of Hearts Five of Diamonds Eight of Clubs Deuce of Diamonds Jack of Hearts Nine of Diamonds Nine of Clubs King of Spades Queen of Spades Four of Spades Ace of Diamonds Ten of Diamonds Queen of Diamonds Jack of Clubs Ace of Spades Ten of Clubs Eight of Diamonds Seven of Hearts Pointers: Solutions 255 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 256 Pointers: Solutions 7.21 What does this program do? 1 /* ex07_21.c */ 2 /* What does this program do? */ 3 #include 4 5 void mystery1( char *s1, const char *s2 ); /* prototype */ 6 7 int main() 8{ 9 char string1[ 80 ]; /* create char array */ 10 char string2[ 80 ]; /* create char array */ 11 12 printf( "Enter two strings: " ); 13 scanf( "%s%s" , string1, string2 ); 14 15 mystery1( string1, string2 ); 16 17 printf("%s", string1 ); 18 19 return 0; /* indicates successful termination */ 20 21 } /* end main */ 22 23 /* What does this function do? */ 24 void mystery1( char *s1, const char *s2 ) 25 { 26 while ( *s1 != '\0' ) { 27 s1++; 28 } /* end while */ 29 30 for ( ; *s1 = *s2; s1++, s2++ ) { 31 ; /* empty statement */ 32 } /* end for */ 33 34 } /* end function mystery1 */ ANS: Concatenates strings. Enter two strings: string1 string2 string1string2 Chapter 7 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 7.22 What does this program do? 1 /* ex07_22.c */ 2 /* what does this program do? */ 3 #include 4 5 int mystery2( const char *s ); /* prototype */ 6 7 int main() 8{ 9 char string[ 80 ]; /* create char array */ 10 11 printf( "Enter a string: "); 12 scanf( "%s", string ); 13 14 printf( "%d\n", mystery2( string ) ); 15 16 return 0; /* indicates successful termination */ 17 18 } /* end main */ 19 20 /* What does this function do? */ 21 int mystery2( const char *s ) 22 { 23 int x; /* counter */ 24 25 /* loop through string */ 26 for ( x = 0; *s != '\0'; s++ ) { 27 x++; 28 } /* end for */ 29 30 return x; 31 32 } /* end function mystery2 */ ANS: Determines the length of a string. Enter a string: string1 7 Pointers: Solutions 257 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 258 Pointers: Solutions Chapter 7 7.23 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. Chapter 7 Pointers: Solutions 259 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 ele- ment 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 /* Exercise 7.24 Solution */ 2 #include 3 #include 4 #include 5 6 #define MAX 10 7 8 /* function prototypes */ 9 void quicksort( int *array, int first, int last ); 10 int partition( int *array, int left, int right ); 11 void swap( int *ptr1, int *ptr2 ); 12 13 int main() 14 { 15 int loop; /* loop counter */ 16 int arrayToBeSorted[ MAX ] = { 0 }; /* array to sort */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 260 Pointers: Solutions Chapter 7 17 18 srand( time( NULL ) ); 19 20 /* randomly generate content */ 21 for ( loop = 0; loop < MAX; loop++ ) { 22 arrayToBeSorted[ loop ] = rand() % 1000; 23 } /* end for */ 24 25 printf( "Initial array values are: \n" ); 26 27 /* print out values of the array */ 28 for ( loop = 0; loop < MAX; loop++ ) { 29 printf( "%4d", arrayToBeSorted[ loop ] ); 30 } /* end for */ 31 32 printf( "\n\n" ); 33 34 /* if there is only one element */ 35 if ( MAX == 1 ) { 36 printf( "Array is sorted: %d\n", arrayToBeSorted[ 0 ] ); 37 } /* end if */ 38 else { /* call quicksort */ 39 quicksort( arrayToBeSorted, 0, MAX - 1 ); 40 printf( "The sorted array values are:\n" ); 41 42 /* display sorted array */ 43 for ( loop = 0; loop < MAX; loop++ ) { 44 printf( "%4d", arrayToBeSorted[ loop ] ); 45 } /* end for */ 46 47 printf( "\n" ); 48 } /* end else */ 49 50 return 0; /* indicate successful termination */ 51 52 } /* end main */ 53 54 /* recursive function to sort array */ 55 void quicksort( int array[], int first, int last ) 56 { 57 int currentLocation; /* current location in array */ 58 59 /* if array is sorted, return */ 60 if ( first >= last ) { 61 return; 62 } /* end if */ 63 64 currentLocation = partition( array, first, last ); /* place an element */ 65 quicksort( array, first, currentLocation - 1 ); /* sort left side */ 66 quicksort( array, currentLocation + 1, last ); /* sort right side */ 67 68 } /* end function quicksort */ 69 70 /* partition the array into multiple sections */ 71 int partition( int array[], int left, int right ) 72 { 73 int position = left; /* final location of first element */ 74 75 /* infinite loop */ 76 while ( 1 ) { 77 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 78 /* loop through the portion of the array */ 79 while ( array[ position ] <= array[ right ] && 80 position != right ) { 81 --right; 82 } /* end while */ 83 84 /* if correct position is found */ 85 if ( position == right ) { 86 return position ; 87 } /* end if */ 88 89 /* swap positions */ 90 if ( array[ position ] > array[ right ] ) { 91 swap( &array[ position ], &array[ right ] ); 92 position = right; 93 } /* end if */ 94 95 /* loop through the portion of the array */ 96 while ( array[ left ] <= array[ position ] && 97 left != position ) { 98 ++left; 99 } /* end while */ 100 101 /* if correct position is found */ 102 if ( position == left ) { 103 return position; 104 } /* end if */ 105 106 /* swap positions */ 107 if ( array[ left ] > array[ position ] ) { 108 swap( &array[ position ], &array[ left ] ); 109 position = left; 110 } /* end if */ 111 112 } /* end while */ 113 114 } /* end function partition */ 115 116 /* swap locations */ 117 void swap( int *ptr1, int *ptr2 ) 118 { 119 int temp; /* temporary holder */ 120 121 temp = *ptr1; 122 *ptr1 = *ptr2; 123 *ptr2 = temp; 124 } /* 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 Pointers: Solutions 261 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 262 Pointers: Solutions Chapter 7 7.25 (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 /* Exercise 7.25 Solution */ 2 /* This solution assumes that there is only one */ 3 /* entrance and one exit for a given maze, and */ 4 /* these are the only two zeroes on the borders.*/ 5 #include 6 #include 7 8 #define DOWN 0 /* move down */ 9 #define RIGHT 1 /* move right */ 10 #define UP 2 /* move up */ 11 #define LEFT 3 /* move left */ 12 13 #define X_START 2 /* starting X and Y coordinate for maze */ 14 #define Y_START 0 15 16 /* function prototypes */ 17 void mazeTraversal( char maze[ 12 ][ 12 ], int xCoord, int yCoord, 18 int direction ); 19 void printMaze( const char maze[][ 12 ] ); 20 int validMove( const char maze[][ 12 ], int r, int c ); 21 int coordsAreEdge( int x, int y ); 22 23 int main() 24 { 25 26 /* maze grid */ 27 char maze[ 12 ][ 12 ] = 28 { { '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'}, 29 { '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '1'}, 30 { '0', '0', '1', '0', '1', '0', '1', '1', '1', '1', '0', '1'}, 31 { '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. Chapter 7 Pointers: Solutions 263 32 { '1', '0', '0', '0', '0', '1', '1', '1', '0', '1', '0', '0'}, 33 { '1', '1', '1', '1', '0', '1', '0', '1', '0', '1', '0', '1'}, 34 { '1', '0', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1'}, 35 { '1', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1'}, 36 { '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '1'}, 37 { '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1'}, 38 { '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1'}, 39 { '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' } }; 40 41 mazeTraversal( maze, X_START, Y_START, RIGHT ); 42 43 return 0; /* indicate successful termination */ 44 45 } /* end main */ 46 47 /* Assume that there is exactly 1 entrance and 48 exactly 1 exit to the maze. */ 49 void mazeTraversal( char maze[ 12 ][ 12 ], int xCoord, int yCoord, 50 int direction ) 51 { 52 static int flag = 0; /* starting position flag */ 53 54 maze[ xCoord ][ yCoord ] = 'X'; /* mark current point */ 55 printMaze( maze ); 56 57 /* if maze completed */ 58 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != X_START && 59 yCoord != Y_START ) { 60 printf( "\nMaze successfully exited!\n\n" ); 61 return; 62 } /* end if */ 63 else if ( xCoord == X_START && yCoord == Y_START && flag == 1 ) { 64 printf( "\nArrived back at the starting location.\n\n" ); 65 return; 66 } /* end else if */ 67 else { /* make next move */ 68 int move; /* next move */ 69 int count; /* counter */ 70 71 flag = 1; 72 73 /* loop 4 times and find first valid move */ 74 for ( move = direction, count = 0; count < 4; ++count, 75 ++move, move %= 4 ) { 76 77 /* choose valid move */ 78 switch( move ) { 79 80 case DOWN: /* move down */ 81 82 /* if move is valid, call mazeTraversal */ 83 if ( validMove( maze, xCoord + 1, yCoord ) ) { 84 mazeTraversal( maze, xCoord + 1, yCoord, LEFT ); 85 return; 86 } /* end if */ 87 88 break; /* exit switch */ 89 90 case RIGHT: /* move right */ 91 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 264 Pointers: Solutions Chapter 7 92 /* if move is valid, call mazeTraversal */ 93 if ( validMove( maze, xCoord, yCoord + 1 ) ) { 94 mazeTraversal( maze, xCoord, yCoord + 1, DOWN ); 95 return; 96 } /* end if */ 97 98 break; /* exit switch */ 99 100 case UP: /* move up */ 101 102 /* if move is valid, call mazeTraversal */ 103 if ( validMove( maze, xCoord - 1, yCoord ) ) { 104 mazeTraversal( maze, xCoord - 1, yCoord, RIGHT ); 105 return; 106 } /* end if */ 107 108 break; /* exit switch */ 109 110 case LEFT: /* move left */ 111 112 /* if move is valid, call mazeTraversal */ 113 if ( validMove( maze, xCoord, yCoord - 1 ) ) { /* move left */ 114 mazeTraversal( maze, xCoord, yCoord - 1, UP ); 115 return; 116 } /* end if */ 117 118 break; /* exit switch */ 119 } /* end switch */ 120 121 } /* end for */ 122 123 } /* end else */ 124 125 } /* end function mazeTraversal */ 126 127 /* validate move */ 128 int validMove( const char maze[][ 12 ], int r, int c ) 129 { 130 return ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && 131 maze[ r ][ c ] != '1' ); 132 133 } /* end function validMove */ 134 135 /* function to check coordinates */ 136 int coordsAreEdge( int x, int y ) 137 { 138 139 /* if coordinate is not valid */ 140 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) ) { 141 return 1; 142 } /* end if */ 143 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) ) { 144 return 1; 145 } /* end else if */ 146 else { /* coordinate is valid */ 147 return 0; 148 } /* end else */ 149 150 } /* end function coordsAreEdge */ 151 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 152 /* print the current state of the maze */ 153 void printMaze( const char maze[][ 12 ] ) 154 { 155 int x; /* row counter */ 156 int y; /* column counter */ 157 158 /* iterate through the maze */ 159 for ( x = 0; x < 12; x++ ) { 160 161 for ( y = 0; y < 12; y++ ) { 162 printf( "%c ", maze[ x ][ y ] ); 163 } /* end for */ 164 165 printf( "\n" ); 166 } /* end for */ 167 168 printf( "\nHit return to see next move" ); 169 getchar(); 170 } /* end function printMaze */ Pointers: Solutions 265 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 266 Pointers: Solutions Hit return to see next move 111111111111 1XXX1XXXXXX1 XX1X1X111101 111X1XXXX101 1XXXX111X100 1111X101X101 1XX1X101X101 11X1X101X101 1XXXXXXXX101 111111X11101 1XXXXXX10001 111111111111 Hit return to see next move 111111111111 1XXX1XXXXXX1 XX1X1X1111X1 111X1XXXX101 1XXXX111X100 1111X101X101 1XX1X101X101 11X1X101X101 1XXXXXXXX101 111111X11101 1XXXXXX10001 111111111111 ... Hit return to see next move 111111111111 1XXX1XXXXXX1 XX1X1X1111X1 111X1XXXX1X1 1XXXX111X1XX 1111X101X1X1 1XX1X101X1X1 11X1X101X1X1 1XXXXXXXX1X1 111111X111X1 1XXXXXX1XXX1 111111111111 Hit return to see next move Maze successfully exited! Chapter 7 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 267 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 /* Exercise 7.26 Solution */ 2 #include 3 #include 4 #include 5 6 #define DOWN 0 /* move down */ 7 #define RIGHT 1 /* move right */ 8 #define UP 2 /* move up */ 9 #define LEFT 3 /* move left */ 10 #define POSSIBLE_ZEROS 100 /* maximum possible zeroes */ 11 12 /* function prototypes */ 13 void mazeTraversal( char maze[ 12 ][ 12 ], const int xCoord, 14 const int yCoord, int row, int col, int direction ); 15 void mazeGenerator( char maze[][ 12 ], int *xPtr, int *yPtr ); 16 void printMaze( const char maze[][ 12 ] ); 17 int validMove( const char maze[][ 12 ], int r, int c ); 18 int coordsAreEdge( int x, int y ); 19 20 int main() 21 { 22 char maze[ 12 ][ 12 ]; /* maze grid */ 23 int loop; /* row counter */ 24 int loop2; /* column counter */ 25 int xStart; /* starting x coordinate */ 26 int yStart; /* starting y coordinate */ 27 int x; /* current x coordinate */ 28 int y; /* current y coordinate */ 29 30 /* initialize maze grid to 1's */ 31 for ( loop = 0; loop < 12; loop++ ) { 32 33 for ( loop2 = 0; loop2 < 12; loop2++ ) { 34 maze[ loop ][ loop2 ] = '1'; 35 } /* end for */ 36 37 } /* end for */ 38 39 /* generate the maze */ 40 mazeGenerator( maze, &xStart, &yStart ); 41 42 x = xStart; /* starting row */ 43 y = yStart; /* starting col */ 44 45 mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); 46 47 return 0; /* indicate successful termination */ 48 49 } /* end main */ 50 51 /* Assume that there is exactly 1 entrance and 52 exactly 1 exit to the maze. */ 53 void mazeTraversal( char maze[ 12 ][ 12 ], const int xCoord, 54 const int yCoord, int row, int col, int direction ) 55 { 56 static int flag = 0; /* starting position flag */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 268 Pointers: Solutions Chapter 7 57 58 maze[ row ][ col ] = 'X'; /* insert X at current location */ 59 printMaze( maze ); 60 61 /* if maze completed */ 62 if ( coordsAreEdge( row, col ) && row != xCoord && col != yCoord ) { 63 printf( "\nMaze successfully exited!\n\n" ); 64 return; 65 } /* end if */ 66 else if ( row == xCoord && col == yCoord && flag == 1 ) { 67 printf( "\nArrived back at the starting location.\n\n" ); 68 return; 69 } /* end else if */ 70 else { /* make next move */ 71 int move; /* next move */ 72 int count; /* counter */ 73 74 flag = 1; 75 76 /* loop 4 times and find first valid move */ 77 for ( move = direction, count = 0; count < 4; ++count, 78 ++move, move %= 4 ) { 79 80 /* choose valid move */ 81 switch( move ) { 82 83 case DOWN: /* move down */ 84 85 /* if move is valid, call mazeTraversal */ 86 if ( validMove( maze, row + 1, col ) ) { 87 mazeTraversal( maze, xCoord, yCoord, row + 1, 88 col, LEFT ); 89 return; 90 } /* end if */ 91 92 break; /* exit switch */ 93 94 case RIGHT: /* move right */ 95 96 /* if move is valid, call mazeTraversal */ 97 if ( validMove( maze, row, col + 1 ) ) { 98 mazeTraversal( maze, xCoord, yCoord, row, 99 col + 1, DOWN ); 100 return; 101 } /* end if */ 102 103 break; /* exit switch */ 104 105 case UP: /* move up */ 106 107 /* if move is valid, call mazeTraversal */ 108 if ( validMove( maze, row - 1, col ) ) { 109 mazeTraversal( maze, xCoord, yCoord, row - 1, 110 col, RIGHT ); 111 return; 112 } /* end if */ 113 114 break; /* exit switch */ 115 116 case LEFT: /* move left */ 117 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 269 118 /* if move is valid, call mazeTraversal */ 119 if ( validMove( maze, row, col - 1 ) ) { 120 mazeTraversal( maze, xCoord, yCoord, row, 121 col - 1, UP ); 122 return; 123 } /* end if */ 124 125 break; /* exit switch */ 126 } /* end switch */ 127 128 } /* end for */ 129 130 } /* end else */ 131 132 } /* end function mazeTraversal */ 133 134 /* validate move */ 135 int validMove( const char maze[][ 12 ], int r, int c ) 136 { 137 return ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && 138 maze[ r ][ c ] != '1' ); 139 140 } /* end function validMove */ 141 142 /* check boundaries of coordinates */ 143 int coordsAreEdge( int x, int y ) 144 { 145 146 /* if coordinates not valid */ 147 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) ) { 148 return 1; 149 } /* end if */ 150 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) ) { 151 return 1; 152 } /* end else if */ 153 else { /* coordinates valid */ 154 return 0; 155 } /* end else */ 156 157 } /* end function coordsAreEdge */ 158 159 /* print the maze */ 160 void printMaze( const char maze[][ 12 ] ) 161 { 162 int x; /* row counter */ 163 int y; /* column counter */ 164 165 /* loop through maze grid */ 166 for ( x = 0; x < 12; x++ ) { 167 168 for ( y = 0; y < 12; y++ ) { 169 printf( "%c ", maze[ x ][ y ] ); 170 } /* end for */ 171 172 printf( "\n" ); 173 } /* end for */ 174 175 printf( "\nHit return to see next move" ); 176 getchar(); 177 } /* end function printMaze */ 178 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 270 Pointers: Solutions Chapter 7 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 240 y = 1 + rand() % 10; 241 maze[ x ][ y ] = '0'; 242 } /* end for */ 243 244 } /* end function mazeGenerator */ Hit return to see next move 111101111111 10110101XXX1 1110001111X1 XX1001XXXXX1 1XXX1XX1XX11 1X1XXX101X11 11X1XXX1XX11 11XXXX11X101 1XX00X1XXX11 11X01X1XX101 11XXXXX11001 111111111111 Hit return to see next move 111101111111 10110101XXX1 1110001111X1 XX1001XXXXX1 1XXX1XX1XX11 1X1XXX101X11 11X1XXX1XX11 11XXXX11X101 1XX00X1XXX11 11X01X1XX101 11XXXXX11001 111111111111 ... Hit return to see next move 1111X1111111 1011X101XXX1 1110XX1111X1 XX1XX1XXXXX1 1XXX1XX1XX11 1X1XXX101X11 11X1XXX1XX11 11XXXX11X101 1XX00X1XXX11 11X01X1XX101 11XXXXX11001 111111111111 Hit return to see next move Maze successfully exited! Pointers: Solutions 271 © 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 /* Exercise 7.27 Solution */ 2 #include 3 #include 4 #include 5 6 #define ROW 10 /* height */ 7 #define COL 10 /* width */ 8 #define DOWN 0 /* move down */ 9 #define RIGHT 1 /* move right */ 10 #define UP 2 /* move up */ 11 #define LEFT 3 /* move left */ 12 13 /* function prototypes */ 14 void mazeTraversal( char maze[ ROW ][ COL ], const int xCoord, 15 const int yCoord, int row, int col, int direction ); 16 void mazeGenerator( char maze[][ COL ], int *xPtr, int *yPtr ); 17 void printMaze( const char maze[][ COL ] ); 18 int validMove( const char maze[][ COL ], int r, int c ); 19 int coordsAreEdge( int x, int y ); 20 21 int main() 22 { 23 char maze[ ROW ][ COL ]; /* maze grid */ 24 int loop; /* row counter */ 25 int loop2; /* column counter */ 26 int xStart; /* starting x coordinate */ 27 int yStart; /* starting y coordinate */ 28 int x; /* current x coordinate */ 29 int y; /* current y coordinate */ 30 31 /* initialize maze grid to 1's */ 32 for ( loop = 0; loop < ROW; loop++ ) { 33 34 for ( loop2 = 0; loop2 < COL; loop2++ ) { 35 maze[ loop ][ loop2 ] = '1'; 36 } /* end for */ 37 38 } /* end for */ 39 40 /* generate the maze */ 41 mazeGenerator( maze, &xStart, &yStart ); 42 43 x = xStart; /* starting row */ 44 y = yStart; /* starting col */ 45 46 mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); 47 48 return 0; /* indicate successful termination */ 49 50 } /* end main */ 51 52 /* Assume that there is exactly 1 entrance and 53 exactly 1 exit to the maze. */ 54 void mazeTraversal( char maze[ ROW ][ COL ], const int xCoord, 55 const int yCoord, int row, int col, int direction ) 56 { 57 static int flag = 0; /* starting position flag */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 273 58 59 maze[ row ][ col ] = 'X'; /* insert X at current location */ 60 printMaze( maze ); 61 62 /* if maze completed */ 63 if ( coordsAreEdge( row, col ) && row != xCoord && col != yCoord ) { 64 printf( "\nMaze successfully exited!\n\n" ); 65 return; 66 } /* end if */ 67 else if ( row == xCoord && col == yCoord && flag == 1 ) { 68 printf( "\nArrived back at the starting location.\n\n" ); 69 return; 70 } /* end else if */ 71 else { /* make next move */ 72 int move; /* next move */ 73 int count; /* counter */ 74 75 flag = 1; 76 77 /* loop 4 times and find first valid move */ 78 for ( move = direction, count = 0; count < 4; ++count, 79 ++move, move %= 4 ) { 80 81 /* choose valid move */ 82 switch( move ) { 83 84 case DOWN: /* move down */ 85 86 /* if move is valid, call mazeTraversal */ 87 if ( validMove( maze, row + 1, col ) ) { 88 mazeTraversal( maze, xCoord, yCoord, row + 1, 89 col, LEFT ); 90 return; 91 } /* end if */ 92 93 break; /* exit switch */ 94 95 case RIGHT: /* move right */ 96 97 /* if move is valid, call mazeTraversal */ 98 if ( validMove( maze, row, col + 1 ) ) { 99 mazeTraversal( maze, xCoord, yCoord, row, 100 col + 1, DOWN ); 101 return; 102 } /* end if */ 103 104 break; /* exit switch */ 105 106 case UP: /* move up */ 107 108 /* if move is valid, call mazeTraversal */ 109 if ( validMove( maze, row - 1, col ) ) { 110 mazeTraversal( maze, xCoord, yCoord, row - 1, 111 col, RIGHT ); 112 return; 113 } /* end if */ 114 115 break; /* exit switch */ 116 117 case LEFT: /* move left */ 118 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 274 Pointers: Solutions Chapter 7 119 /* if move is valid, call mazeTraversal */ 120 if ( validMove( maze, row, col - 1 ) ) { 121 mazeTraversal( maze, xCoord, yCoord, row, 122 col - 1, UP ); 123 return; 124 } /* end if */ 125 126 break; /* exit switch */ 127 } /* end switch */ 128 129 } /* end for */ 130 131 } /* end else */ 132 133 } /* end function mazeTraversal */ 134 135 /* validate move */ 136 int validMove( const char maze[][ COL ], int r, int c ) 137 { 138 return ( r >= 0 && r <= ROW - 1 && c >= 0 && c <= COL - 1 && 139 maze[ r ][ c ] != '1' ); /* a valid move */ 140 141 } /* end function validMove */ 142 143 /* check boundaries of coordinates */ 144 int coordsAreEdge( int x, int y ) 145 { 146 147 /* if coordinates not valid */ 148 if ( ( x == 0 || x == ROW - 1 ) && ( y >= 0 && y <= COL - 1 ) ) { 149 return 1; 150 } /* end if */ 151 else if ( ( y == 0 || y == COL - 1 ) && ( x >= 0 && 152 x <= ROW - 1 ) ) { 153 return 1; 154 } /* end else if */ 155 else { /* coordinates valid */ 156 return 0; 157 } /* end else */ 158 159 } /* end function coordsAreEdge */ 160 161 /* print the maze */ 162 void printMaze( const char maze[][ COL ] ) 163 { 164 int x; /* row counter */ 165 int y; /* column counter */ 166 167 /* loop through maze grid */ 168 for ( x = 0; x < ROW; x++ ) { 169 170 for ( y = 0; y < COL; y++ ) { 171 printf( "%c ", maze[ x ][ y ] ); 172 } /* end for */ 173 174 printf( "\n" ); 175 } /* end for */ 176 177 printf( "\nHit return to see next move" ); 178 getchar(); 179 } /* end function printMaze */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 275 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 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 */ 11X1111111 1001101001 0001111101 1000001011 1110001001 1110101101 1000100101 1000110001 1000011001 1111111111 Hit return to see next move 11X1111111 10X1101001 0001111101 1000001011 1110001001 1110101101 1000100101 1000110001 1000011001 1111111111 ... Hit return to see next move 11X1111111 1XX1101001 XX01111101 1000001011 1110001001 1110101101 1000100101 1000110001 1000011001 1111111111 Hit return to see next move Maze successfully exited! Chapter 7 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 Pointers: Solutions 277 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 /* Exercise 7.28 Solution */ 2 #include 3 #define STUDENTS 3 4 #define EXAMS 4 5 6 /* function prototypes */ 7 void minimum( int grades[][ EXAMS ], int pupils, int tests ); 8 void maximum( int grades[][ EXAMS ], int pupils, int tests ); 9 void average( int grades[][ EXAMS ], int pupils, int tests ); 10 void printArray( int grades[][ EXAMS ], int pupils, int tests ); 11 void printMenu( void ); 12 13 int main() 14 { 15 16 /* pointer to a function that takes as parameters a 17 two-dimensional array and two integer values */ 18 void ( *processGrades[ 4 ] )( int [][ EXAMS ], int, int ) 19 = { printArray, minimum, maximum, average}; 20 21 int choice = 0; /* menu choice */ 22 23 /* array of student grades */ 24 int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, 25 { 96, 87, 89, 78 }, 26 { 70, 90, 86, 81 } }; 27 28 /* loop while user does not choose option 4 */ 29 while ( choice != 4 ) { 30 31 /* display menu and read user's choice */ 32 do { 33 printMenu(); 34 scanf( "%d", &choice ); 35 } while ( choice < 0 || choice > 4 ); /* end do...while */ 36 37 /* pass choice into the array */ 38 if ( choice != 4 ) { 39 ( *processGrades[ choice ] )( studentGrades, STUDENTS, EXAMS ); 40 } /* end if */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 278 Pointers: Solutions Chapter 7 41 else { 42 printf( "Program Ended.\n" ); 43 } /* end else */ 44 45 } /* end while */ 46 47 return 0; /* indicate successful termination */ 48 49 } /* end main */ 50 51 /* search for the minimum value */ 52 void minimum( int grades[][ EXAMS ], int pupils, int tests ) 53 { 54 int i; /* loop counter */ 55 int j; /* loop counter */ 56 int lowGrade = 100; /* set lowGrade to highest possible score */ 57 58 /* loop through rows */ 59 for ( i = 0; i <= pupils - 1; i++ ) { 60 61 /* loop through columns */ 62 for ( j = 0; j <= tests - 1; j++ ) { 63 64 /* if current grade is lower than lowGrade */ 65 if ( grades[ i ][ j ] < lowGrade ) { 66 lowGrade = grades[ i ][ j ]; 67 } /* end if */ 68 69 } /* end for */ 70 71 } /* end for */ 72 73 printf( "\n\tThe lowest grade is %d\n", lowGrade ); 74 } /* end function minimum */ 75 76 /* search for maximum value */ 77 void maximum( int grades[][ EXAMS ], int pupils, int tests ) 78 { 79 int i; /* loop counter */ 80 int j; /* loop counter */ 81 int highGrade = 0; /* set highGrade to lowest possible score */ 82 83 /* loop through rows */ 84 for ( i = 0; i <= pupils - 1; i++ ) { 85 86 /* loop through columns */ 87 for ( j = 0; j <= tests - 1; j++ ) { 88 89 /* if current grade is higher than highGrade */ 90 if ( grades[ i ][ j ] > highGrade ) { 91 highGrade = grades[ i ][ j ]; 92 } /* end if */ 93 94 } /* end for */ 95 96 } /* end for */ 97 98 printf( "\n\tThe highest grade is %d\n", highGrade ); 99 } /* end function maximum */ 100 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 101 /* calculate average */ 102 void average( int grades[][ EXAMS ], int pupils, int tests ) 103 { 104 int i; /* loop counter */ 105 int j; /* loop counter */ 106 int total; /* sum of all grades */ 107 108 printf( "\n" ); 109 110 /* loop through rows */ 111 for ( i = 0; i <= pupils - 1; i++ ) { 112 total = 0; 113 114 /* loop through columns */ 115 for ( j = 0; j <= tests - 1; j++ ) { 116 total += grades[ i ][ j ]; 117 } /* end for */ 118 119 printf( "\tThe average for student %d is %.1f\n", 120 i + 1, ( double ) total / tests ); 121 } /* end for */ 122 123 } /* end function average */ 124 125 /* print the contents of the array */ 126 void printArray( int grades[][ EXAMS ], int pupils, int tests ) 127 { 128 int i; /* loop counter */ 129 int j; /* loop counter */ 130 131 printf( "\n\t [ 0 ] [ 1 ] [ 2 ] [ 3 ]" ); 132 133 /* loop through rows */ 134 for ( i = 0; i <= pupils - 1; i++ ) { 135 printf( "\n\tstudentGrades[ %d ] ", i ); 136 137 /* loop through columns */ 138 for ( j = 0; j <= tests - 1; j++ ) { 139 printf( "%-7d", grades[ i ][ j ] ); 140 } /* end for */ 141 142 } /* end for */ 143 144 printf( "\n" ); 145 } /* end function printArray */ 146 147 /* display the menu */ 148 void printMenu( void ) 149 { 150 printf( "\n\tEnter a choice:\n" 151 "\t 0 Print the array of grades\n" 152 "\t 1 Find the minimum grade\n" 153 "\t 2 Find the maximum grade\n" 154 "\t 3 Print the average on all" 155 " tests for each student\n" 156 "\t 4 End program\n" 157 "\t? " ); 158 } /* end function printMenu */ Pointers: Solutions 279 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 280 Pointers: Solutions 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. Chapter 7 © 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 What does this program do? 1 /* ex07_30.c */ 2 /* What does this program do? */ 3 #include 4 5 int mystery3( const char *s1, const char *s2 ); /* prototype */ 6 7 int main() 8{ 9 char string1[ 80 ]; /* create char array */ 10 char string2[ 80 ]; /* create char array */ 11 12 printf( "Enter two strings: " ); 13 scanf( "%s%s", string1 , string2 ); 14 15 printf( "The result is %d\n", mystery3( string1, string2 ) ); 16 17 return 0; /* indicates successful termination */ 18 19 } /* end main */ 20 21 int mystery3( const char *s1, const char *s2 ) 22 { 23 for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) { 24 25 if ( *s1 != *s2 ) { 26 return 0; 27 } /* end if */ 28 29 } /* end for */ 30 31 return 1; 32 33 } /* end function mystery3 */ ANS: The Program compares two strings, element by element, for equality. Enter two strings: string1 string2 The result is 0 Enter two strings: string2 string2 The result is 1 Chapter 7 © 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 /* Exercise 8.5 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 int c; /* character input by user */ 8 9 printf( "Enter a character: " ); 10 c = getchar(); 11 12 /* test each function of the character handling library */ 13 printf( "isdigit( \'%c\' ) = %d\n", c, isdigit( c ) ); 14 printf( "isalpha( \'%c\' ) = %d\n", c, isalpha( c ) ); 15 printf( "isalnum( \'%c\' ) = %d\n", c, isalnum( c ) ); 16 printf( "isxdigit( \'%c\' ) = %d\n", c, isxdigit( c ) ); 17 printf( "islower( \'%c\' ) = %d\n", c, islower( c ) ); 18 printf( "isupper( \'%c\' ) = %d\n", c, isupper( c ) ); 19 printf( "tolower( \'%c\' ) = %d\n", c, tolower( c ) ); 20 printf( "toupper( \'%c\' ) = %d\n", c, toupper( c ) ); 21 printf( "isspace( \'%c\' ) = %d\n", c, isspace( c ) ); 22 printf( "iscntrl( \'%c\' ) = %d\n", c, iscntrl( c ) ); 23 printf( "ispunct( \'%c\' ) = %d\n", c, ispunct( c ) ); 24 printf( "isprint( \'%c\' ) = %d\n", c, isprint( c ) ); 25 printf( "isgraph( \'%c\' ) = %d\n", c, isgraph( c ) ); 26 27 return 0; /* indicate successful termination */ 28 29 } /* 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 /* Exercise 8.6 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 char s[ 100 ]; /* define character array of size 100 */ 8 int i; /* loop counter */ 9 10 /* use gets to get text from user */ 11 printf( "Enter a line of text:\n" ); 12 gets( s ); 13 printf( "\nThe line in uppercase is:\n" ); 14 15 /* convert each character to uppercase and output */ 16 for ( i = 0; s[ i ] != '\0'; i++ ) { 17 printf( "%c", toupper( s[ i ] ) ); 18 } /* end for */ 19 20 printf( "\n\nThe line in lowercase is:\n" ); 21 22 /* convert each character to lowercase and output */ 23 for ( i = 0; s[ i ] != '\0'; i++ ) { 24 printf( "%c", tolower( s[ i ] ) ); 25 } /* end for */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* 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. Chapter 8 C Characters and Strings: Solutions 285 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 /* Exercise 8.7 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 char stringValue[ 6 ]; /* integer string input by user */ 8 int sum = 0; /* result of four integers */ 9 int i; /* loop counter */ 10 11 /* loop 4 times */ 12 for ( i = 1; i <= 4; i++ ) { 13 printf( "Enter an integer string: " ); 14 scanf( "%s", stringValue ); 15 16 /* atoi converts stringValue to integer */ 17 sum += atoi( stringValue ); 18 } /* end for */ 19 20 printf( "\nThe total of the values is %d\n", sum ); 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ Enter an integer string: 43 Enter an integer string: 77 Enter an integer string: 120 Enter an integer string: 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 /* Exercise 8.8 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 char stringValue[ 15 ]; /* string input by user */ 8 double sum = 0.0; /* sum of all four values */ 9 int i; /* loop counter */ 10 11 /* loop 4 times */ 12 for ( i = 1; i <= 4; i++ ) { 13 printf( "Enter a doubleing point string: " ); 14 gets( stringValue ); 15 16 /* atof converts stringValue to a floating-point value */ 17 sum += atof( stringValue ); 18 } /* end for */ 19 20 printf( "\nThe total of the values is %f\n", sum ); 21 22 return 0; /* indicate successful termination */ 23 24 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 286 C Characters and Strings: Solutions Chapter 8 Enter a doubleing point string: 1.2 Enter a doubleing point string: 2.3 Enter a doubleing point string: 3.4 Enter a doubleing point string: 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 /* Exercise 8.9 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 char string1[ 20 ]; /* first string input by user */ 8 char string2[ 20 ]; /* second string input by user */ 9 int result; /* result of comparing two strings */ 10 11 printf( "Enter two strings: " ); 12 scanf( "%s%s", string1, string2 ); /* read two strings */ 13 14 result = strcmp( string1, string2 ); 15 16 /* display appropriate message for result */ 17 if ( result > 0 ) { 18 printf( "\"%s\" is greater than \"%s\"\n", string1, string2 ); 19 } /* end if */ 20 else if ( result == 0 ) { 21 printf( "\"%s\" is equal to \"%s\"\n", string1, string2 ); 22 } /* end else if */ 23 else { 24 printf( "\"%s\" is less than \"%s\"\n", string1, string2 ); 25 } /* end else */ 26 27 return 0; /* indicate successful termination */ 28 29 } /* 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. Chapter 8 C Characters and Strings: Solutions 287 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 /* Exercise 8.10 Solution */ 2 #include 3 #include 4 5 int main() 6{ 7 char string1[ 20 ]; /* first string input by user */ 8 char string2[ 20 ]; /* second string input by user */ 9 int result; /* result of using strncmp */ 10 int compareCount; /* how many characters to be compared */ 11 12 /* get two strings from user */ 13 printf( "Enter two strings: " ); 14 scanf( "%s%s", string1, string2 ); 15 16 /* get number of characters to compare */ 17 printf( "How many characters should be compared: " ); 18 scanf( "%d", &compareCount ); 19 20 result = strncmp( string1, string2, compareCount ); 21 22 /* display appropriate message for result */ 23 if ( result > 0 ) { 24 printf( "\"%s\" is greater than \"%s\" up to %d characters\n", 25 string1, string2, compareCount ); 26 } /* end if */ 27 else if ( result == 0 ) { 28 printf( "\"%s\" is equal to \"%s\" up to %d characters\n", 29 string1, string2, compareCount ); 30 } /* end else if */ 31 else { 32 printf( "\"%s\" is less than \"%s\" up to %d characters\n", 33 string1, string2, compareCount ); 34 } /* end else */ 35 36 return 0; /* indicate successful termination */ 37 38 } /* 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 /* Exercise 8.11 Solution */ 2 #include 3 #include 4 #include 5 #include 6 #include 7 8 int main() 9{ 10 /* initialize 4 arrays of char pointers */ 11 char *article[] = { "the", "a", "one", "some", "any" }; 12 char *noun[] = { "boy", "girl", "dog", "town", "car" }; 13 char *verb[] = { "drove", "jumped", "ran", "walked", "skipped" }; 14 char *preposition[] = { "to", "from", "over", "under", "on" }; 15 char sentence[ 100 ] = ""; /* completed sentence */ 16 int i; /* loop counter */ 17 18 /* create 20 sentences */ 19 for ( i = 1; i <= 20; i++ ) { 20 21 /* randomly choose pieces of sentence */ 22 strcat( sentence, article[ rand() % 5 ] ); 23 strcat( sentence, " " ); 24 25 strcat( sentence, noun[ rand() % 5 ] ); 26 strcat( sentence, " " ); 27 28 strcat( sentence, verb[ rand() % 5 ] ); 29 strcat( sentence, " " ); 30 31 strcat( sentence, preposition[ rand() % 5 ] ); 32 strcat( sentence, " " ); 33 34 strcat( sentence, article[ rand() % 5 ] ); 35 strcat( sentence, " " ); 36 37 strcat( sentence, noun[ rand() % 5 ] ); 38 39 /* capitalize first letter and print sentence */ 40 putchar( toupper( sentence[ 0 ] ) ); 41 printf( "%s.\n", &sentence[ 1 ] ); 42 sentence[ 0 ] = '\0'; 43 } /* end for */ 44 45 return 0; /* indicate successful termination */ 46 47 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 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. C Characters and Strings: Solutions 289 © 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 /* Exercise 8.13 Solution */ 2 #include 3 #include 4 5 void printLatinWord( char *word ); /* function prototype */ 6 7 int main() 8{ 9 char sentence[ 80 ]; /* sentence input by user */ 10 char *tokenPtr; /* pointer to current token */ 11 12 printf( "Enter a sentence:\n" ); 13 gets( sentence ); 14 printf( "\nThe sentence in Pig Latin is:\n" ); 15 16 /* call function strtok to alter the sentence */ 17 tokenPtr = strtok( sentence, " .,;" ); 18 19 /* if tokenPtr does not equal NULL */ 20 while ( tokenPtr ) { 21 22 /* pass the token to printLatinWord and get next token */ 23 printLatinWord( tokenPtr ); 24 tokenPtr = strtok( NULL, " .,;" ); 25 26 /* if tokenPtr not NULL, print space */ 27 if ( tokenPtr ) { 28 printf( " " ); 29 } /* end if */ 30 31 } /* end while */ 32 33 printf( "." ); 34 35 return 0; /* indicates successful termination */ 36 37 } /* end main */ 38 39 /* print out the English word in pig Latin form */ 40 void printLatinWord( char *word ) 41 { 42 unsigned int i; /* loop counter */ 43 44 /* loop through the word */ 45 for ( i = 1; i < strlen( word ); i++ ) { 46 printf( "%c", word[ i ] ); 47 } /* end for */ 48 49 printf( "%c%s", word[ 0 ], "ay" ); 50 } /* end function printLatinWord */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 8 C Characters and Strings: Solutions 291 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 /* Exercise 8.14 Solution */ 2 #include 3 #include 4 #include 5 6 int main() 7{ 8 char p[ 20 ]; /* complete phone number */ 9 char phoneNumber[ 10 ] = { '\0' }; /* long integer phone number */ 10 char *tokenPtr; /* store temporary token */ 11 int areaCode; /* store area code */ 12 long phone; /* store phone number */ 13 14 printf( "Enter a phone number in the form ( 555 )" 15 " 555-5555:\n" ); 16 gets( p ); 17 18 /* convert area code token to an integer */ 19 areaCode = atoi( strtok( p, "()" ) ); 20 21 /* take next token and copy to phoneNumber */ 22 tokenPtr = strtok( NULL, " -" ); 23 strcpy( phoneNumber, tokenPtr ); 24 25 /* take last token and concatenate to phoneNumber */ 26 tokenPtr = strtok( NULL, "" ); 27 strcat( phoneNumber, tokenPtr ); 28 29 /* convert phoneNumber to long integer */ 30 phone = atol( phoneNumber ); 31 32 printf( "\nThe integer area code is %d\n", areaCode ); 33 printf( "The long integer phone number is %ld\n", phone ); 34 35 return 0; /* indicate successful termination */ 36 37 } /* 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 Chapter 8 8.15 Write a program that inputs a line of text, tokenizes the line with function strtok and outputs the tokens in reverse order.. ANS: 1 /* Exercise 8.15 solution */ 2 #include 3 #include 4 5 void reverseTokens( char *sentence ); /* function prototype */ 6 7 int main() 8{ 9 char text[ 80 ]; /* line of text from user */ 10 11 printf( "Enter a line of text:\n" ); 12 gets( text ); 13 14 reverseTokens( text ); /* call to function reverseTokens */ 15 16 return 0; /* indicate successful termination */ 17 18 } /* end main */ 19 20 /* function to reverse the individual tokens */ 21 void reverseTokens( char *sentence ) 22 { 23 char *pointers[ 50 ]; /* array to store entire sentence */ 24 char *temp; /* pointer to each token */ 25 int count = 0; /* token counter */ 26 int i; /* loop counter */ 27 28 /* function strtok takes first word of sentence */ 29 temp = strtok( sentence, " " ); 30 31 /* while temp does not equal NULL */ 32 while ( temp ) { 33 34 /* add the word into the array and get next token */ 35 pointers[ count++ ] = temp; 36 temp = strtok( NULL, " " ); 37 } /* end while */ 38 39 printf( "The tokens in reverse order are:\n" ); 40 41 /* loop through the array backwards */ 42 for ( i = count - 1; i >= 0; i-- ) { 43 printf( "%s ", pointers[ i ] ); 44 } /* end for */ 45 46 } /* 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. Chapter 8 C Characters and Strings: Solutions 293 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 /* Exercise 8.16 Solution */ 2 #include 3 #include 4 int main() 5{ 6 char text[ 80 ]; /* line of text */ 7 char search[ 15 ]; /* search string */ 8 char *searchPtr; /* poiner to search string */ 9 10 /* get line of text from user */ 11 printf( "Enter a line of text:\n" ); 12 gets( text ); 13 14 /* get search string from user */ 15 printf( "Enter a search string: " ); 16 scanf( "%s", search ); 17 18 /* search for search string in text */ 19 searchPtr = strstr( text, search ); 20 21 /* if searchPtr is not NULL */ 22 if ( searchPtr ) { 23 printf( "\n%s\n%s\"%s\":\n%s\n", 24 "The remainder of the line beginning with", 25 "the first occurrence of ", search, searchPtr ); 26 27 /* search for a second occurrence */ 28 searchPtr = strstr( searchPtr + 1, search ); 29 30 /* if searchPtr is not NULL */ 31 if ( searchPtr ) { 32 printf( "\n%s\n%s\"%s\":\n%s\n", 33 "The remainder of the line beginning with", 34 "the second occurrence of ", search, searchPtr ); 35 } /* end if */ 36 else { 37 printf( "The search string appeared only once.\n" ); 38 } /* end else */ 39 40 } /* end if */ 41 else { 42 printf( "\"%s\" not found.\n", search ); 43 } /* end else */ 44 45 return 0; /* indicate successful termination */ 46 47 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 294 C Characters and Strings: Solutions Chapter 8 Enter a line of text: To be or not to be; that is the question. Enter a search string: be The remainder of the line beginning with the first occurrence of "be": be or not to be; that is the question. The remainder of the line beginning with the second occurrence of "be": be; that is the question. 8.17 Write a program based on the program of Exercise 8.16 that inputs several lines of text and a search string, and uses function strstr to determine the total occurrences of the string in the lines of text. Print the result. ANS: 1 /* Exercise 8.17 Solution */ 2 #include 3 #include 4 #include 5 6 int main() 7{ 8 char text[ 3 ][ 80 ]; /* array to hold text entered by user */ 9 char search[ 20 ]; /* search string */ 10 char *searchPtr; /* pointer to search string */ 11 int count = 0; /* total occurrences of search string */ 12 int i; /* loop counter */ 13 int j; /* loop counter */ 14 15 printf( "Enter three lines of text:\n" ); 16 17 /* read in 3 lines of text */ 18 for ( i = 0; i <= 2; i++ ) { 19 gets( &text[ i ][ 0 ] ); 20 } /* end for */ 21 22 /* make all characters lowercase */ 23 for ( i = 0; i <= 2; i++ ) { 24 25 /* loop through each character */ 26 for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { 27 text[ i ][ j ] = tolower( text[ i ][ j ] ); 28 } /* end for */ 29 30 } /* end for */ 31 32 printf( "\nEnter a search string: " ); /* get search string */ 33 scanf( "%s", search ); 34 35 /* loop through all three strings */ 36 for ( i = 0; i <= 2; i++ ) { 37 38 /* set pointer to first character of string */ 39 searchPtr = &text[ i ][ 0 ]; 40 41 /* loop while strstr does not return NULL */ 42 while ( searchPtr = strstr( searchPtr, search ) ) { 43 ++count; 44 searchPtr++; 45 } /* end while */ 46 47 } /* end for */ 48 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 8 C Characters and Strings: Solutions 295 49 printf( "\nThe total occurrences of \"%s\" in the text is %d\n", 50 search, count ); 51 52 return 0; /* indicate successful termination */ 53 54 } /* end main */ Enter three lines of text: This program inputs three lines of text and counts the number of occurrences of the search string in the three lines of text. Enter a search string: th The total occurrences of "th" in the text is 6 8.18 Write a program that inputs several lines of text and a search character, and uses function strchr to determine the total occurrences of the character in the lines of text. ANS: 1 /* Exercise 8.18 Solution */ 2 #include 3 #include 4 #include 5 6 int main() 7{ 8 char text[ 3 ][ 80 ]; /* array to hold text entered by user */ 9 char search; /* search character */ 10 char *searchPtr; /* pointer to search character */ 11 int count = 0; /* total search characters found */ 12 int i; /* loop counter */ 13 int j; /* loop counter */ 14 15 printf( "Enter three lines of text:\n" ); 16 17 /* read 3 lines of text */ 18 for ( i = 0; i <= 2; i++ ) { 19 gets( &text[ i ][ 0 ] ); 20 } /* end for */ 21 22 /* convert all letters to lowercase */ 23 for ( i = 0; i <= 2; i++ ) { 24 25 /* loop through each character */ 26 for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { 27 text[ i ][ j ] = tolower( text[ i ][ j ] ); 28 } /* end for */ 29 30 } /* end for */ 31 32 /* get search character */ 33 printf( "\nEnter a search character: " ); 34 scanf( "%c", &search ); 35 36 /* loop through 3 lines of text */ 37 for ( i = 0; i <= 2; i++ ) { 38 39 /* set pointer to first character in line */ 40 searchPtr = &text[ i ][ 0 ]; 41 42 /* loop while strchr does not return NULL */ 43 while ( searchPtr = strchr( searchPtr, search ) ) { 44 ++count; © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 296 C Characters and Strings: Solutions 45 searchPtr++; 46 } /* end while */ 47 48 } /* end for */ 49 50 printf( "\nThe total occurrences of '%c' in the text is %d\n", 51 search, count ); 52 53 return 0; /* indicate successful termination */ 54 55 } /* end main */ Enter three lines of text: This program inputs three lines of text and counts the number of occurrences of the specified search character in the text Enter a search character: e The total occurrences of 'e' in the text is 15 Chapter 8 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 8 C Characters and Strings: Solutions 297 8.19 Write a program based on the program of Exercise 8.18 that inputs several lines of text and uses function strchr to determine the total occurrences of each letter of the alphabet in the lines of text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array and print the values in tabular format after the totals have been determined. ANS: 1 /* Exercise 8.19 Solution */ 2 #include 3 #include 4 #include 5 6 int main() 7{ 8 char text[ 3 ][ 80 ]; /* 3 lines of text */ 9 char *searchPtr; /* pointer to search character */ 10 char characters[ 26 ] = { 0 }; /* totals for each letter */ 11 int count = 0; /* total for current letter */ 12 int i; /* loop counter */ 13 int j; /* loop counter */ 14 15 printf( "Enter three lines of text:\n" ); 16 17 /* read three lines of text */ 18 for ( i = 0; i <= 2; i++ ) { 19 gets( &text[ i ][ 0 ] ); 20 } /* end for */ 21 22 /* convert letters to lowercase */ 23 for ( i = 0; i <= 2; i++ ) { 24 25 /* loop through each character of line */ 26 for ( j = 0; text[ i ][ j ] != '\0'; j++ ) { 27 text[ i ][ j ] = tolower( text[ i ][ j ] ); 28 } /* end for */ 29 30 } /* end for */ 31 32 /* loop through alphabet */ 33 for ( i = 0; i <= 25; i++ ) { 34 35 /* loop through 3 lines of text */ 36 for ( j = 0, count = 0; j <= 2; j++ ) { 37 searchPtr = &text[ j ][ 0 ]; 38 39 /* while strchr does not return NULL */ 40 while ( searchPtr = strchr( searchPtr, 'a' + i ) ) { 41 ++count; 42 searchPtr++; 43 } /* end while */ 44 45 } /* end for */ 46 47 characters[ i ] = count; 48 } /* end for */ 49 50 printf( "\nThe total occurrences of each character:\n" ); 51 52 /* display totals for each character */ 53 for ( i = 0; i <= 25; i++ ) { 54 printf( "%c:%3d\n", 'a' + i, characters[ i ] ); 55 } /* end for */ 56 57 return 0; /* indicate successful termination */ 58 59 } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 298 C Characters and Strings: Solutions Enter three lines of text: This program inputs three lines of text and determines the number of occurrences of each character in the three lines. The total occurrences of each character: a: 5 b: 1 c: 6 d: 2 e: 17 f: 3 g: 1 h: 7 i: 6 j: 0 k: 0 l: 2 m: 3 n: 8 o: 5 p: 2 q: 0 r: 10 s: 6 t: 10 u: 3 v: 0 w: 0 x: 1 y: 0 z: 0 Chapter 8 © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 8 C Characters and Strings: Solutions 299 8.20 Write a program that inputs several lines of text and uses strtok to count the total number of words. Assume that the words are separated either by spaces or newline characters. ANS: 1 /* Exercise 8.20 Solution */ 2 #include 3 #include