Your SlideShare is downloading. ×
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Cpcs 203 -array-problems
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Cpcs 203 -array-problems

639

Published on

ncnckdkc kd;kdlksd

ncnckdkc kd;kdlksd

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
639
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Postlab ActivitiesTopics Lab ExercisesOne-Dimensional Arrays Tracking Sales
  • 23. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__ Grading Quizzes Reversing an Array Adding To and Removing From an Integer ListCommand Line Arguments Averaging NumbersVariable Length Parameter Lists Exploring Variable Length Parameter ListsTwo-Dimensional Arrays Matrix Inverse Coding Exercise 1 Tracking SalesFile Sales.java contains a Java program that prompts for and reads in the sales for each of 5salespeople in a company. It thenprints out the id and amount of sales for each salesperson andthe total sales. Study the code, then compile and run theprogram to see how it works. Nowmodify the program as follows:1. Compute and print the average sale. (You can compute this directly from the total; no loop is necessary.)2. Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., “Salesperson 3 had the highest sale with $4500.” Note that you don’t need another loop for this; you can do it in the same loop where the values are read and the sum is computed.3. Do the same for the minimum sale.4. After the list, sum, average, max and min have been printed; ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.5. The salespeople are objecting to having an id of 0—no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array—just make the information for salesperson 1 resides in array location 0, and so on.6. Instead of always reading in 5 sales amounts, at the beginning ask the user for the number of sales people and then createan array that is just the right size. The program can then proceed as before.// ***************************************************************// Sales.java//// Reads in and stores sales for each of 5 salespeople. Displays// sales entered by salesperson id and total sales for all salespeople.//// ***************************************************************import java.util.Scanner;public class Sales
  • 24. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__{public static void main(String[] args) {final int SALESPEOPLE = 5;int[] sales = new int[SALESPEOPLE];int sum; Scanner scan = new Scanner(System.in);for (int i=0; i<sales.length; i++) { System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextInt(); }System.out.println("nSalesperson Sales");System.out.println(" ------------------ ");sum = 0;for (int i=0; i<sales.length; i++) { System.out.println(" " + i + " " + sales[i]); sum += sales[i]; }System.out.println("nTotal sales: " + sum); }}Postlab Activities Coding Exercise 2 Grading QuizzesWrite a program that grades arithmetic quizzes as follows:
  • 25. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__1. Ask the user how many questions are in the quiz.2. Ask the user to enter the key (that is, the correct answers). There should be one answer for each question in the quiz, and each answer should be an integer. They can be entered on a single line, e.g., 34 7 13 100 81 3 9 10 321 12 might be the key for a 10-question quiz. You will need to store the key in an array.3. Ask the user to enter the answers for the quiz to be graded. As for the key, these can be entered on a single line. Again there needs to be one for each question. Note that these answers do not need to be stored; each answer can simply be compared to the key as it is entered.4. When the user has entered all of the answers to be graded, print the number correct and the percent correct.When this works, add a loop so that the user can grade any number of quizzes with a single key.After the results have been printed for each quiz, ask “Grade another quiz? (y/n).”Postlab Activities Coding Exercise 3 Reversing an Array
  • 26. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Write a program that prompts the user for an integer, and then asks the user to enter that manyvalues. Store these values in anarray and print the array. Then reverse the array elements so thatthe first element becomes the last element, the secondelement becomes the second to lastelement, and so on, with the old last element now first. Do not just reverse the order inwhichthey are printed; actually change the way they are stored in the array. Do not create a secondarray; just rearrange theelements within the array you have. (Hint: Swap elements that need tochange places.) When the elements have beenreversed, print the array again.Postlab Activities Coding Exercise 4 Averaging Numbers
  • 27. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__When you run a Java program called Foo, anything typed on the command lineafter “java Foo”is passed to the main method in the args parameter as an array of strings.1. Write a program Average.java that just prints the strings that it is given at the command line, one per line. If nothingis given at the command line, print “No arguments”.2. Modify your program so that it assumes the arguments given at the command line are integers. If there are noarguments, print a message. If there is at least one argument, compute and print the average of the arguments. Notethat you will need to use the parseInt method of the Integer class to extract integer values from the strings that arepassed in. If any non- integer values are passed in, your program will produce an error, which is unavoidable at thispoint.Postlab Activities Coding Exercise 5 Exploring Variable Length Parameter Lists
  • 28. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__The file Parameters.java contains a program to test the variable length method average fromSection 7.5 of the text. Notethat average must be a static method since it is called from the staticmethod main.1. Compile and run the program. You must use the -source 1.5 option in your compile command.2. Add a call to find the average of a single integer, say 13. Print the result of the call.3. Add a call with an empty parameter list and print the result. Is the behavior what you expected?4. Add an interactive part to the program. Ask the user to enter a sequence of at most 20 nonnegative integers. Yourprogram should have a loop that reads the integers into an array and stops when a negative is entered (the negativenumber should not be stored). Invoke the average method to find the average of the integers in the array (send thearray as the parameter). Does this work?5. Add a method minimum that takes a variable number of integer parameters and returns the minimum of theparameters. Invoke your method on each of the parameter lists used for the average function.//*******************************************************// Parameters.java//// Illustrates the concept of a variable parameter list.//*******************************************************import java.util.Scanner;public class Parameters{//-----------------------------------------------// Calls the average and minimum methods with// different numbers of parameters.//-----------------------------------------------public static void main(String[] args){double mean1, mean2;mean1 = average(42, 69, 37);mean2 = average(35, 43, 93, 23, 40, 21, 75);System.out.println ("mean1 = " + mean1);System.out.println ("mean2 = " + mean2);}//----------------------------------------------// Returns the average of its parameters.//----------------------------------------------public static double average (int ... list){double result = 0.0;if (list.length != 0){int sum = 0;for (int num: list)sum += num;result = (double)sum / list.length;}return result;}}
  • 29. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__Postlab Activities Coding Exercise 6 Matrix Inverse
  • 30. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__The inverse of a square matrix A is denoted A-1, such that A×A-1 = I, where I is the identitymatrix with all1’s on the diagonal and 0 on all other cells. 1 2 1 2 0.5 0.5 2 3 1 1 0.5 0.5 4 5 3 1 1.5 0.5The inverse of matrix , for example, isthat is, 1 2 1 2 0.5 0.5 1 0 0 2 3 1 1 0.5 0.5 0 1 0 4 5 3 1 1.5 0.5 0 0 1The inverse of a 3 × 3 matrix a11 a12 a13A a 21 a 22 a 23 a 31 a 32 a 33can be obtained using the following formula if | A | 0 : a 22 a 33 a 23a 32 a13a 32 a12 a 33 a12 a 23 a13a 22 1 1A a 23a 31 a 21a 33 a11a 33 a13 a 31 a13a 21 a11a 23 | A| a 21a 32 a 22 a 31 a12 a 31 a11a 32 a11a 22 a12 a 21 a11 a12 a13| A | a 21 a 22 a 23 a11a 22 a 33 a 31a12 a 23 a13a 21a 32 a13 a 22 a 31 a11a 23 a 32 a 33 a 21a12 a 31 a 32 a 33 .Implement the following function to obtain an inverse of the matrix:public static double[][] inverse(double[][] A) a a a a aWrite a test program that prompts the user to enter a11 , a12 , 13 , a 21 , a 21 , 23 , 31 , 32 , 33 fora matrix and displays its inverse matrix. Here are the sample runs:Sample 1Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 2 1 2 3 1 4 5 3-2 0.5 0.51 0.5 -0.51 -1.5 0.5Sample 2Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 4 2 2 5 8 2 1 8
  • 31. CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__2.0 -1.875 1.3750.0 0.25 -0.25-0.5 0.4375 -0.1875

×