Upcoming SlideShare
×

# Cpcs 203 -array-problems

1,266 views

Published on

ncnckdkc kd;kdlksd

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
1,266
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
13
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Cpcs 203 -array-problems

1. 1. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ King Abdulaziz University Faculty of Computing and Information Systems Spring Term 2012/1433Course Code: CPCS-203 Course Name: Programming II______________________________________________________________________ ObjectivesIn this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program.
2. 2. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Prelab Activity: MatchingThe questions are intended to test and reinforce your understanding of key concepts. You mayanswer the questions before the lab.For each term in the left column, write the letter for the description from the right column thatbest matches theterm. Term Description_1. pass by value a) Indicates that a method receives a variable number of arguments._2. a[ i ][ j ] b) Declares an array of type int._3. index c) A collection of variables that contain values of thesame type._4. new int[ 12 ] d) Iterates through an array without using a counter._5. ... e) Information passed to an application when it executes._6. pass by reference f) A copy of the argument’s value is made and passedto the called method._7. array g) Represented by an array with two dimensions._8. enhanced for statement h) A calling method gives a called method the ability to access and potentially modify the caller’s data directly._9. int c[] i) One element of an array with two dimensions._10. tables of values j) Specifies a particular element in an array._11. length k) Creates an array of integers._12. command-line arguments l) An array member that contains the number of elements in an array.
3. 3. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Prelab Activity: Fill in the BlankFill in the blanks for each of the following statements:13. Every array has a(n) ________ member that specifies the number of elements in the array.14. When an argument is ________, a copy of the argument’s value is made and passed to the called method.15. To pass an array to a method, you must specify the ________ of the array as an argument in the method call.16. An array ________ may be an integer or an integer expression.17. The first element in every array has index ________.18. A(n) ________argument list is treated as an array within the method declaration’s body.19. Arrays are ________entities—they remain the same length once they are created.20. ________must be initialized before they are used and cannot be modified thereafter.21. To pass one row of a two-dimensional array to a method that receives a one-dimensional array, you specifythe array’s ________ followed by only the row ________Prelab Activity:
4. 4. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ Short Answers22. What is an off-by-one error?23. What benefits does the enhanced for statement provide for array processing? What are its limitations?24. Why are command-line arguments passed to the main method as Strings? What problems would arise ifcommand-line arguments were passed using an array of doubles?25. Describe how two-dimensional arrays represent a table of data.26. Differentiate between pass-by-value and pass-by-reference.Prelab Activity:
5. 5. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ Program OutputFor each of the given program segments, read the code, and write the output in the spaceprovided below eachprogram. [Note: Do not execute these programs on a computer.]Unless specified otherwise, for the following questions assume that the code segments arecontained within themain method of a Java application.27. What is the output of the following code segment? 1 int array[] = { 8, 6, 9, 7, 6, 4, 4, 5, 8, 10 }; 2 System.out.println("Index Value" ); 3 4 for ( inti = 0; i < array.length; i++ ) 5 System.out.printf("%d %dn", i, array[ i ] );Your answer:28. What is the output of the following code segment? 1 char sentence[] = { H, o, w, , a, r, e, , y, o, u }; 2 String output = "The sentence is: "; 3 4 for ( inti = 0; i < sentence.length; i++ ) 5 System.out.printf("%c ", sentence[ i ] ); 6 7 System.out.println();Your answer:29. What is the output of the following code segment? 1 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
6. 6. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 2 3 for ( inti = 0; i < array.length; i++ ) 4{ 5 for ( intj = 0; j < array [ i ]; j++ ) 6 System.out.print("*" ); 7 8System.out.println(); 9}Your answer:30. What is the output of the following code segment? 1 int array[] = { 3, 2, 5 }; 2 3 for ( inti = 0; i <3; i++ ) 4 array[ i ] *= 2; 5 6for ( intj : array ) 7 System.out.print("%d ", j ); 8 9System.out.println();Your answer:Given the following declaration of a method 1 public int method1(int... values ) 2{ 3 int mystery = 1; 4 5for ( inti : values ) 6 mystery *= i; 7 8return mystery; 9}31. What is the output of the following code segment? 1 System.out.println( method1( 1, 2, 3, 4, 5 ) );Your answer:
7. 7. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Given the following declaration of a method 1 public int method1(int values[][] ) 2{ 3 int mystery = 1; 4 5for ( inti[] : values ) 6 for ( intj : i ) 7 mystery *= j; 8 9return mystery; 10 }32. What is the output of the following code segment? 1 int array[][] = { { 3, 2, 5 }, { 2, 2, 4, 5, 6 }, { 1, 1 } }; 2 3System.out.println( mystery( array ) );Your answer:Prelab Activity:
8. 8. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ Correct the CodeDetermine if there is an error in each of the following program segments. If there is an error,specify whether itis a logic error or a compilation error, circle the error in the program and writethe corrected code in the spaceprovided after each problem. If the code does not contain an error,write “no error.” [Note: There may be morethan one error in each program segment.]33. The following code segment should assign 8 to the element of integer array with index 10. 1 array(10 ) = 8;Your answer:34. The forstatement that follows should initialize all of array’s elements to -1. 1 int array[] = new int[ 10 ]; 2 3 for ( inti = 0; i <9; i++ ) 4 array[ i ] = -1;Your answer:35. Array a should contain all the integers from 0 through 10, inclusive. 1 int a[] = new int[ 10 ];
9. 9. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 2 3 for ( inti = 0; i <10; i++ ) 4 a[ i ] = i;Your answer:36. The following code segment should allocate two arrays containing five and six elements, respectively. 1 final int arraySize = 5; 2 3 int a[] = new int[ arraySize ]; 4 5arraySize = 6; 6 7 int b[] = new int[ arraySize ];Your answer:37. The following code segment should initialize a two-dimensional array, then print its values. 1 int a[][] = new int[ 10 ][ 5 ];
10. 10. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 2 3 for ( inti = 0; i < a.length; i++ ) 4 for ( intj = 0; j < a[ i ].length; j++ ) 5 a[ j ][ i ] = j; 6 7 for ( inti = 0; i < a.length; i++ ) 8{ 9 for ( intj = 0; j < a[ i ].length; j++ ) 10 System.out.printf("%d ", a[ j ][ i ] ); 11 12 System.out.println(); 13 }Your answer:38. The following code segment should assign the value 10 to the array element that corresponds to the thirdrow and the fourth column. 1 int a[] = new int[ 10 ][ 5 ]; 2 3 a[2 ][ 3 ] = 10;Your answer:Lab Exercises:
11. 11. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ Lab Exercise 1 — Duplicate EliminationThis problem is intended to be solved in a closed-lab session with a teaching assistant orinstructor present. Theproblem is divided into six parts:1. Lab Objectives2. Description of Problem3. Sample Output4. Program Template (Figure 1: )5. Problem-Solving Tips6. Follow-Up Questions and ActivitiesThe program template represents a complete working Java program, with one or more key linesof code replacedwith comments. Read the problem description and examine the sample output;then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compileand execute thesource code for the template is available at www.pearsonhighered.com/deitelLab ObjectivesIn thislab, you will practice: Declaring and initializing arrays. Comparing input to array elements. Preventing array out-of-bounds errors.The follow-up questions and activities will also give you practice: Initializing array sizes during program execution. Generalizing programs.Description of the ProblemUse a one-dimensional array to solve the following problem: Write an application that inputs fivenumbers, eachof which is between 10 and 100, inclusive. As each number is read, display it onlyif it is not a duplicate of a numberalready read. Provide for the “worst case,” in which all fivenumbers are different. Use the smallest possiblearray to solve this problem. Display the completeset of unique values input after the user inputs each new value.Sample Output Enter number: 11 11 Enter number: 85 11 85 Enter number: 26 11 85 26 Enter number: 11 11 has already been entered
12. 12. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 3 import java.util.Scanner; 4 5 public classUniqueTest 6{ 7 public static void main( String args[] ) 8{ 9 getNumbers(); 11} // end main 12 13// gets 5 unique numbers from the user 14public void getNumbers() 15 { 16Scanner input = new Scanner( System.in ); 17 18/* Create an array of five elements*/ 19int count = 0; // number of uniques read 20int entered = 0; // number of entered numbers 21 22while( entered < numbers.length ) 23{ 24 System.out.print("Enter number: " ); 25 /* Write code here to retrieve the input from the user */ 26 27 // validate the input 28 /* Write an if statement that validates the input */ 29 { 30 // flags whether this number already exists 31 booleancontainsNumber = false; 32 33 // increment number of entered numbers 34 entered++; 35 36/* Compare the user input to the unique numbers in the array using a for 37statement. If the number is unique, store new number */ 38 39/* add the user input to the array only if the number is not already 40in the array */ 41if ( !containsNumber )
13. 13. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 42{ 43/* Write code to add the number to the array and increment 44unique items input */ 45}// end if 46else 47System.out.printf("%d has already been enteredn", 48number ); 49}// end if 50else 51System.out.println("number must be between 10 and 100" ); 52 53// print the list of unique values 54/* Write code to output the contents of the array */ 55}// end while 56}// end method getNumbers 57}// end class UniqueTestFigure 1: Unique.javaProblem-Solving Tips1. Initialize the integer array numbers to hold five elements. This is the maximum number of values the program must store if all values input are unique.2. Remember to validate the input and display an error message if the user inputs invalid data.3. If the number entered is not unique, display a message to the user; otherwise, store the number in the array and display the list of unique numbers entered so far.4. If you have any questions as you proceed, ask your lab instructor for assistance.Follow-Up Questions and Activities1. Modify the program in Lab Exercise 1 to input 30 numbers, each of which is between 10 to 500, inclusive.
14. 14. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full.3. Modify your solution to Follow-Up Question 2 to allow the user to enter the size of the array as the application begins execution.Lab Exercises: Lab Exercise 2 — Craps GameThis problem is intended to be solved in a closed-lab session with a teaching assistant orinstructor present. Theproblem is divided into five parts: 1. Lab Objectives 2. Description of Problem
15. 15. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 3. Sample Output 4. Program Template (Figure 2) 5. Problem-Solving TipsThe program template represents a complete working Java program, with one or more key linesof code replacedwith comments. Read the problem description and examine the sample output;then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compileand execute theprogram. Compare your output with the sample output provided. The source codefor the template is availableat www.pearsonhighered.com/deitelLab ObjectivesIn thislab you will practice: Declaring and initializing arrays. Using arrays to store sets of data.Description of the ProblemWrite an application that runs 1000 games of craps and answers 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?Sample Output 224 games won and 99 games lost on roll #1 74 games won and 119 games lost on roll #2 50 games won and 96 games lost on roll #3 33 games won and 54 games lost on roll #4 23 games won and 47 games lost on roll #5 22 games won and 37 games lost on roll #6 18 games won and 13 games lost on roll #7 8 games won and 18 games lost on roll #8 7 games won and 14 games lost on roll #9 5 games won and 6 games lost on roll #10 5 games won and 6 games lost on roll #11 4 games won and 3 games lost on roll #12 1 games won and 3 games lost on roll #13 1 games won and 0 games lost on roll #14 0 games won and 4 games lost on roll #15 1 games won and 0 games lost on roll #16
16. 16. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Program Template 1 // Lab 2: CrapsTest.java 2 // Program plays 1000 games of craps and displays winning 3 // and losing statistics. 4 import java.util.Random; 5 6public classCrapsTest 7{ 8public static void main( String args[] ) 9{ 10 // create random number generator for use in method rollDice 11 private static Random randomNumbers = new Random(); 12 13 // enumeration with constants that represent the game status 14 private enum Status { CONTINUE, WON, LOST }; 15 16 /* Declare array to store the number of games won by number of rolls in the 17 game */ 18 /* Declare array to store the number of games lost by number of rolls in the game 19 */ 20 int winSum = 0; // total number of wins 21 int loseSum = 0; // total number of losses 22 23 // plays one game of craps 24 `play(); 25}// end main 26 27 28public void play() 29{ 30int sumOfDice = 0; // sum of the dice 31int myPoint = 0; // point if no win or loss on first roll 32 33Status gameStatus; // can contain CONTINUE, WON or LOST 34 35int roll; // number of rolls for the current game 36 37/* Create the array to store the number of games won */
17. 17. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 38/* Create the array to store the number of games lost */ 39 40for ( inti = 1; i <= 1000; i++ ) 41{ 42sumOfDice = rollDice(); // first roll of the dice 43roll = 1; 44 45// determine game status and point based on sumOfDice 46switch ( sumOfDice ) 47{ 48case 7: // win with 7 on first roll 49case 11: // win with 11 on first roll 50gameStatus = Status.WON; 51break; 52case 2: // lose with 2 on first roll 53case 3: // lose with 3 on first roll 54case 12: // lose with 12 on first roll 55gameStatus = Status.LOST; 56break; 57default: // did not win or lose, so remember point 58gameStatus = Status.CONTINUE; // game is not over 59myPoint = sumOfDice; // store the point 60break; // optional for default case at end of switch 61}// end switch 62 63// while game is not complete ... 64while ( gameStatus == Status.CONTINUE ) 65{ 66sumOfDice = rollDice(); // roll dice again 67roll++; 68 69// determine game status 70if ( sumOfDice == myPoint ) // win by making point 71gameStatus = Status.WON; 72else if ( sumOfDice == 7 ) // lose by rolling 7 73gameStatus = Status.LOST; 74}// end while 75 76// all roll results after 20th roll placed in last element 77/* Write an if statement to test whether the number of rolls is greater than 7821 and, if true, set number of rolls to 21 */ 79 80// increment number of wins in that roll 81if ( gameStatus == Status.WON ) 82{ 83/* Write code to increment the number of games won for a 84specific number of rolls */ 85/* Write code to increment the overall number of games won */ 86}// end if 87else // increment number of losses in that roll 88{ 89/* Write code to increment the number of games lost for a 90specific number of rolls */ 91/* Write code to increment the overall number of games lost */ 92}// end else 93}// end for
18. 18. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 94 95printStats(); 96}// end method play 97 98// print win/loss statistics 99public void printStats() 100{ 101int totalGames = winSum + loseSum; // total number of games 102int length = 0; // total length of the games 103 104// display number of wins and losses on all rolls 105for ( inti = 1; i <= 21; i++ ) 106{ 107/* Write an if statement to test whether i is equal to 21 */ 108/* Output number of games won and lost after the 20th roll */ 109else 110/* Output number of games won and lost after each roll less than 20 */ 111 112// calculate total number of rolls to win/lose all games 113// add number of wins by number of rolls needed to win 114// add number of losses by number of rolls needed to lose 115/* Write code to calculate total length of games */ 116}// end for 117 118// calculate chances of winning 119System.out.printf("n%s %d / %d = %.2f%%n", 120"The chances of winning are", winSum, totalGames, 121( 100.0* winSum / totalGames ) ); 122 123 124System.out.printf("The average game length is %.2f rolls.n", 125( (double ) length / totalGames ) ); 126}// end method printStats 127 128// roll dice, calculate sum and display results 129public int rollDice() 130{ 131// pick random die values 132int die1 = 1 + randomNumbers.nextInt(6 ); 133int die2 = 1 + randomNumbers.nextInt(6 ); 134int sum = die1 + die2; // sum die values 135 136return sum; // return sum of dice 137}// end method rollDice 138} // end class CrapsTestProblem-Solving Tips1. The arrays to hold the number of wins and losses by number of rolls should have 22 elements. We are keeping track of the number of wins and losses decided on the first through twentieth roll along with games decided after the twentieth roll. That requires 21 elements.
19. 19. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ The extra element is because arrays begin with element zero. This element will not hold any information in the program.2. To calculate the total number of rolls, multiply each index in the arrays by the value of that element in the array.3. If you have any questions as you proceed, ask your lab instructor for assistance.Lab Exercises: DebuggingThe program in this section does not run properly. Fix all the compilation errors, so that theprogram will compilesuccessfully. Once the program compiles, compare the output to the sampleoutput, and eliminate any logicerrors that exist. The sample output demonstrates what the
20. 20. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__program’s output should be once the program’s codeis corrected. The file is available atwww.deitel.com/books/jhtp8/ and at www.pearsonhighered.com/deitel.Sample Output Enter sales person number (-1 to end): 1 Enter product number: 4 Enter sales amount: 1082 Enter sales person number (-1 to end): 2 Enter product number: 3 Enter sales amount: 998 Enter sales person number (-1 to end): 3 Enter product number: 1 Enter sales amount: 678 Enter sales person number (-1 to end): 4 Enter product number: 1 Enter sales amount: 1554 Enter sales person number (-1 to end): -1 Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total 1 0.00 0.00 678.00 1554.00 2232.00 2 0.00 0.00 0.00 0.00 0.00 3 0.00 998.00 0.00 0.00 998.00 4 1082.00 0.00 0.00 0.00 1082.00 5 0.00 0.00 0.00 0.00 0.00 Total 1082.00 998.00 678.00 1554.00Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 3 import java.util.Scanner; 4 5// Debugging Problem Chapter 7: Sales2Test.java 6// Test application for class Sales2 7public classSales2Test 8{ 9public static void main( String args[] ) 10{ 11 calculateSales(); 12}// end main 13 14 Scanner input = new Scanner( System.in ); 15 // sales array holds data on number of each product sold 16 // by each salesman 17 double sales = new double[5 ][ 4 ]; 18 19 System.out.print("Enter sales person number (-1 to end): " ); 20 int person = input.nextInt(); 21 22 while ( person != -1 ) 23 { 24 System.out.print("Enter product number: " );
21. 21. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ 25 int product = input.next(); 26 System.out.print("Enter sales amount: " ); 27 double amount = input.nextDouble(); 28 29 // error-check the input 30 if ( person<1 && person >5 && 31 product >= 1 && product <6 && amount >= 0 ) 32 sales[ product - 1 ][ person - 1 ] += amount; 33 else 34 System.out.println("Invalid input!" ); 35 36 System.out.print("Enter sales person number (-1 to end): " ); 37 person = input.nextInt(); 38 } // end while 39 40 // total for each salesperson 41 double salesPersonTotal[][] = new double[ 4 ]; 42 43 // display the table 44 for ( intcolumn = 0; column <4; column++ ) 45 salesPersonTotal[ column ][ row ] = 0; 46 47 System.out.printf("%7s%14s%14s%14s%14s%10sn", 48 "Product", "Salesperson 1", "Salesperson 2", 49 "Salesperson 3", "Salesperson 4", "Total" ); 50 51 // for each column of each row, print the appropriate 52 // value representing a persons sales of a product 53 for ( introw = 0; row <5; row++ ) 54 { 55 double productTotal = 0.0; 56 System.out.printf("%7d", ( row + 1 ) ); 57 58 for ( intcolumn = 0; column <4; column++ ) { 59 System.out.printf("%14.2f", sales[ column ][ row ] ); 60 productTotal += sales[ column ][ row ]; 61 salesPersonTotal[ column ] += sales[ column ][ row ]; 62 } // end for 63 64 System.out.printf("%10.2fn", productTotal ); 65} // end for 66 67System.out.printf("%7s", "Total" ); 68 69for ( intcolumn = 0; column <4; column++ ) 70System.out.printf("%14.2f", salesPersonTotal[ column ] ); 71 72System.out.println(); 73}// end method calculateSales 64}// end class Sales2Test
22. 22. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Postlab ActivitiesTopics Lab ExercisesOne-Dimensional Arrays Tracking Sales