+ All Categories
Home > Documents > Cpcs 203 -array-problems

Cpcs 203 -array-problems

Date post: 20-Jun-2015
Category:
Upload: maheraalqasim
View: 651 times
Download: 6 times
Share this document with a friend
Description:
ncnckdkc kd;kdlksd
Popular Tags:
41
CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ King Abdulaziz University Faculty of Computing and Information Systems Spring Term 2012/1433 Course Code: CPCS-203 Course Name: Programming II _________________________________________________________________ _____ Objectives In 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.
Transcript
Page 1: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

King Abdulaziz UniversityFaculty of Computing and Information Systems

Spring Term 2012/1433

Course Code: CPCS-203 Course Name: Programming II______________________________________________________________________

Objectives

In 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.

Page 2: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Prelab Activity:

MatchingThe questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before the lab.

For each term in the left column, write the letter for the description from the right column that best matches the term.

Term Description

_ 1. pass by value a) Indicates that a method receives a variable numberof arguments.

_ 2. a[ i ][ j ] b) Declares an array of type int.

_ 3. index c) A collection of variables that contain values of the same 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 passed to 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.

Page 3: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

_ 12. command-line arguments l) An array member that contains the number of elements in an array.

Prelab Activity:

Fill in the Blank

Fill 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 specify the array’s ________ followed by only the row ________

Page 4: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Prelab Activity:

Short Answers

22. 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 if command-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.

Page 5: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Prelab Activity:

Program Output

For each of the given program segments, read the code, and write the output in the space provided below each program. [Note: Do not execute these programs on a computer.]Unless specified otherwise, for the following questions assume that the code segments are contained within the main 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" );34 for ( int i = 0; i < array.length; i++ )5 System.out.printf( "%d %d\n", 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: ";34 for ( int i = 0; i < sentence.length; i++ )5 System.out.printf( "%c ", sentence[ i ] );67 System.out.println();

Page 6: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

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 };23 for ( int i = 0; i < array.length; i++ )4 {5 for ( int j = 0; j < array [ i ]; j++ )6 System.out.print( "*" );78 System.out.println();9 }

Your answer:

30. What is the output of the following code segment?

1 int array[] = { 3, 2, 5 };23 for ( int i = 0; i < 3; i++ )4 array[ i ] *= 2;56 for ( int j : array )7 System.out.print( "%d ", j );89 System.out.println();

Your answer:

Given the following declaration of a method

Page 7: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

1 public int method1( int... values )2 {3 int mystery = 1;45 for ( int i : values )6 mystery *= i;78 return mystery;9 }

31. What is the output of the following code segment?1 System.out.println( method1( 1, 2, 3, 4, 5 ) );

Your answer:

Given the following declaration of a method

1 public int method1( int values[][] )2 {3 int mystery = 1;45 for ( int i[] : values )6 for ( int j : i )7 mystery *= j;89 return 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 } };23 System.out.println( mystery( array ) );

Your answer:

Page 8: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Prelab Activity:

Correct the Code

Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more than 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 for statement that follows should initialize all of array’s elements to -1.

1 int array[] = new int[ 10 ];23 for ( int i = 0; i < 9; i++ )4 array[ i ] = -1;

Your answer:

Page 9: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

35. Array a should contain all the integers from 0 through 10, inclusive.

1 int a[] = new int[ 10 ];23 for ( int i = 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;23 int a[] = new int[ arraySize ];45 arraySize = 6;67 int b[] = new int[ arraySize ];

Your answer:

Page 10: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

37. The following code segment should initialize a two-dimensional array, then print its values.

1 int a[][] = new int[ 10 ][ 5 ];23 for ( int i = 0; i < a.length; i++ )4 for ( int j = 0; j < a[ i ].length; j++ )5 a[ j ][ i ] = j;67 for ( int i = 0; i < a.length; i++ )8 {9 for ( int j = 0; j < a[ i ].length; j++ )10 System.out.printf( "%d ", a[ j ][ i ] );1112 System.out.println();13 }

Your answer:

Page 11: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

38. The following code segment should assign the value 10 to the array element that corresponds to the third row and the fourth column.

1 int a[] = new int[ 10 ][ 5 ];23 a[ 2 ][ 3 ] = 10;

Your answer:

Lab Exercises:

Lab Exercise 1 — Duplicate Elimination

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem 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 Activities

The program template represents a complete working Java program, with one or more key lines of code replaced with 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. Compile and execute the source code for the template is available at www.pearsonhighered.com/deitel

Lab Objectives

In this lab, you will practice: Declaring and initializing arrays. Comparing input to array elements.

Page 12: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

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 Problem

Use a one-dimensional array to solve the following problem: Write an application that inputs five numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user inputs each new value.

Sample Output

Program Template

1 // Lab 1: Unique.java2 // Reads in 5 unique numbers.3 import java.util.Scanner;45 public class UniqueTest6 {7 public static void main( String args[] )8 {9 getNumbers();11 } // end main1213 // gets 5 unique numbers from the user

Enter number: 1111Enter number: 8511 85Enter number: 2611 85 26Enter number: 1111 has already been entered11 85 26Enter number: 4111 85 26 41

Page 13: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

14 public void getNumbers()15 {16 Scanner input = new Scanner( System.in );1718 /* Create an array of five elements*/19 int count = 0; // number of uniques read20 int entered = 0; // number of entered numbers2122 while( entered < numbers.length )23 {24 System.out.print( "Enter number: " );25 /* Write code here to retrieve the input from the user */2627 // validate the input28 /* Write an if statement that validates the input */29 {30 // flags whether this number already exists31 boolean containsNumber = false;3233 // increment number of entered numbers34 entered++;3536 /* Compare the user input to the unique numbers in the array using a for37 statement. If the number is unique, store new number */3839 /* add the user input to the array only if the number is not already40 in the array */41 if ( !containsNumber )42 {43 /* Write code to add the number to the array and increment44 unique items input */45 } // end if46 else47 System.out.printf( "%d has already been entered\n",48 number );49 } // end if50 else51 System.out.println( "number must be between 10 and 100" );5253 // print the list of unique values54 /* Write code to output the contents of the array */55 } // end while56 } // end method getNumbers57 } // end class UniqueTest

Figure 1: Unique.java

Problem-Solving Tips

1. 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.

Page 14: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

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 Activities

1. Modify the program in Lab Exercise 1 to input 30 numbers, each of which is between 10 to 500, inclusive.

2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full.

Page 15: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

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 Game

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into five parts:

1. Lab Objectives2. Description of Problem3. Sample Output4. Program Template (Figure 2)5. Problem-Solving Tips

The program template represents a complete working Java program, with one or more key lines of code replaced with 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. Compile and execute the program. Compare your output with the sample output provided. The source code for the template is available at www.pearsonhighered.com/deitel

Lab Objectives

In this lab you will practice: Declaring and initializing arrays. Using arrays to store sets of data.

Page 16: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Description of the Problem

Write 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

Program Template

1 // Lab 2: CrapsTest.java

224 games won and 99 games lost on roll #174 games won and 119 games lost on roll #250 games won and 96 games lost on roll #333 games won and 54 games lost on roll #423 games won and 47 games lost on roll #522 games won and 37 games lost on roll #618 games won and 13 games lost on roll #78 games won and 18 games lost on roll #87 games won and 14 games lost on roll #95 games won and 6 games lost on roll #105 games won and 6 games lost on roll #114 games won and 3 games lost on roll #121 games won and 3 games lost on roll #131 games won and 0 games lost on roll #140 games won and 4 games lost on roll #151 games won and 0 games lost on roll #160 games won and 0 games lost on roll #170 games won and 1 games lost on roll #180 games won and 0 games lost on roll #190 games won and 0 games lost on roll #203 games won and 1 games lost on rolls after the 20th rollThe chances of winning are 479 / 1000 = 47.90%The average game length is 3.37 rolls.

Page 17: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

2 // Program plays 1000 games of craps and displays winning3 // and losing statistics.4 import java.util.Random;56 public class CrapsTest7 {8 public static void main( String args[] )9 {10 // create random number generator for use in method rollDice11 private static Random randomNumbers = new Random();1213 // enumeration with constants that represent the game status14 private enum Status { CONTINUE, WON, LOST };1516 /* 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 wins21 int loseSum = 0; // total number of losses2223 // plays one game of craps24 `play();25 } // end main262728 public void play()29 {30 int sumOfDice = 0; // sum of the dice31 int myPoint = 0; // point if no win or loss on first roll3233 Status gameStatus; // can contain CONTINUE, WON or LOST3435 int roll; // number of rolls for the current game3637 /* Create the array to store the number of games won */38 /* Create the array to store the number of games lost */3940 for ( int i = 1; i <= 1000; i++ )41 {42 sumOfDice = rollDice(); // first roll of the dice43 roll = 1;4445 // determine game status and point based on sumOfDice46 switch ( sumOfDice )47 {48 case 7: // win with 7 on first roll49 case 11: // win with 11 on first roll50 gameStatus = Status.WON;51 break;52 case 2: // lose with 2 on first roll53 case 3: // lose with 3 on first roll

Page 18: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

54 case 12: // lose with 12 on first roll55 gameStatus = Status.LOST;56 break;57 default: // did not win or lose, so remember point58 gameStatus = Status.CONTINUE; // game is not over59 myPoint = sumOfDice; // store the point60 break; // optional for default case at end of switch61 } // end switch6263 // while game is not complete ...64 while ( gameStatus == Status.CONTINUE )65 {66 sumOfDice = rollDice(); // roll dice again67 roll++;6869 // determine game status70 if ( sumOfDice == myPoint ) // win by making point71 gameStatus = Status.WON;72 else if ( sumOfDice == 7 ) // lose by rolling 773 gameStatus = Status.LOST;74 } // end while7576 // all roll results after 20th roll placed in last element77 /* Write an if statement to test whether the number of rolls is greater than78 21 and, if true, set number of rolls to 21 */7980 // increment number of wins in that roll81 if ( gameStatus == Status.WON )82 {83 /* Write code to increment the number of games won for a84 specific number of rolls */85 /* Write code to increment the overall number of games won */86 } // end if87 else // increment number of losses in that roll88 {89 /* Write code to increment the number of games lost for a90 specific number of rolls */91 /* Write code to increment the overall number of games lost */92 } // end else93 } // end for9495 printStats();96 } // end method play9798 // print win/loss statistics99 public void printStats()100 {101 int totalGames = winSum + loseSum; // total number of games102 int length = 0; // total length of the games103104 // display number of wins and losses on all rolls105 for ( int i = 1; i <= 21; i++ )106 {

Page 19: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

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 */109 else110 /* Output number of games won and lost after each roll less than 20 */111112 // calculate total number of rolls to win/lose all games113 // add number of wins by number of rolls needed to win114 // add number of losses by number of rolls needed to lose115 /* Write code to calculate total length of games */116 } // end for117118 // calculate chances of winning119 System.out.printf( "\n%s %d / %d = %.2f%%\n",120 "The chances of winning are", winSum, totalGames,121 ( 100.0 * winSum / totalGames ) );122123124 System.out.printf( "The average game length is %.2f rolls.\n",125 ( ( double ) length / totalGames ) );126 } // end method printStats127128 // roll dice, calculate sum and display results129 public int rollDice()130 {131 // pick random die values132 int die1 = 1 + randomNumbers.nextInt( 6 );133 int die2 = 1 + randomNumbers.nextInt( 6 );134 int sum = die1 + die2; // sum die values135136 return sum; // return sum of dice137 } // end method rollDice138} // end class CrapsTest

Problem-Solving Tips

1. 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. 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.

Page 20: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Lab Exercises:

Debugging

The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic errors that exist. The sample output demonstrates what the program’s output should be once the program’s code is corrected. The file is available at www.deitel.com/books/jhtp8/ and at www.pearsonhighered.com/deitel.

Sample Output

Enter sales person number (-1 to end): 1Enter product number: 4Enter sales amount: 1082Enter sales person number (-1 to end): 2Enter product number: 3Enter sales amount: 998Enter sales person number (-1 to end): 3Enter product number: 1Enter sales amount: 678Enter sales person number (-1 to end): 4Enter product number: 1Enter sales amount: 1554Enter sales person number (-1 to end): -1

Page 21: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Broken Code

1 // Debugging Problem Chapter 7: Sales2.java2 // Program totals sales for salespeople and products.3 import java.util.Scanner;45 // Debugging Problem Chapter 7: Sales2Test.java6 // Test application for class Sales27 public class Sales2Test8 {9 public static void main( String args[] )10 {11 calculateSales();12 } // end main13 14 Scanner input = new Scanner( System.in );15 // sales array holds data on number of each product sold16 // by each salesman17 double sales = new double[ 5 ][ 4 ];1819 System.out.print( "Enter sales person number (-1 to end): " );20 int person = input.nextInt();2122 while ( person != -1 )23 {24 System.out.print( "Enter product number: " );25 int product = input.next();26 System.out.print( "Enter sales amount: " );27 double amount = input.nextDouble();2829 // error-check the input30 if ( person < 1 && person > 5 &&31 product >= 1 && product < 6 && amount >= 0 )32 sales[ product - 1 ][ person - 1 ] += amount;33 else

Enter sales person number (-1 to end): 1Enter product number: 4Enter sales amount: 1082Enter sales person number (-1 to end): 2Enter product number: 3Enter sales amount: 998Enter sales person number (-1 to end): 3Enter product number: 1Enter sales amount: 678Enter sales person number (-1 to end): 4Enter product number: 1Enter sales amount: 1554Enter sales person number (-1 to end): -1

Page 22: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

34 System.out.println( "Invalid input!" );3536 System.out.print( "Enter sales person number (-1 to end): " );37 person = input.nextInt();38 } // end while3940 // total for each salesperson41 double salesPersonTotal[][] = new double[ 4 ];4243 // display the table44 for ( int column = 0; column < 4; column++ )45 salesPersonTotal[ column ][ row ] = 0;4647 System.out.printf( "%7s%14s%14s%14s%14s%10s\n",48 "Product", "Salesperson 1", "Salesperson 2",49 "Salesperson 3", "Salesperson 4", "Total" );5051 // for each column of each row, print the appropriate52 // value representing a person's sales of a product53 for ( int row = 0; row < 5; row++ )54 {55 double productTotal = 0.0;56 System.out.printf( "%7d", ( row + 1 ) );5758 for ( int column = 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 for6364 System.out.printf( "%10.2f\n", productTotal );65 } // end for6667 System.out.printf( "%7s", "Total" );6869 for ( int column = 0; column < 4; column++ )70 System.out.printf( "%14.2f", salesPersonTotal[ column ] );7172 System.out.println();73 } // end method calculateSales64 } // end class Sales2Test

Page 23: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Postlab Activities

TopicsLab Exercises

One-Dimensional Arrays Tracking SalesGrading QuizzesReversing an ArrayAdding To and Removing From an Integer List

Page 24: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Command Line Arguments Averaging Numbers

Variable Length Parameter Lists Exploring Variable Length Parameter Lists

Two-Dimensional Arrays Matrix Inverse

Coding Exercise 1

Tracking Sales

File Sales.java contains a Java program that prompts for and reads in the sales for each of 5 salespeople in a company. It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify 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 create an 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{ public static void main(String[] args)

Page 25: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

{ 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 Quizzes

Write a program that grades arithmetic quizzes as follows:

Page 26: Cpcs 203 -array-problems

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

Page 27: Cpcs 203 -array-problems

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 many values. Store these values in an array and print the array. Then reverse the array elements so that the first element becomes the last element, the second element becomes the second to last element, and so on, with the old last element now first. Do not just reverse the order in which they are printed; actually change the way they are stored in the array. Do not create a second array; just rearrange the elements within the array you have. (Hint: Swap elements that need to change places.) When the elements have been reversed, print the array again.

Postlab Activities

Coding Exercise 4

Page 28: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Averaging Numbers

When you run a Java program called Foo, anything typed on the command line after “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 nothing is 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 no arguments, print a message. If there is at least one argument, compute and print the average of the arguments. Note that you will need to use the parseInt method of the Integer class to extract integer values from the strings that are passed in. If any non-integer values are passed in, your program will produce an error, which is unavoidable at this point.

Postlab Activities

Coding Exercise 5

Page 29: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Exploring Variable Length Parameter Lists

The file Parameters.java contains a program to test the variable length method average from Section 7.5 of the text. Note that average must be a static method since it is called from the static method 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. Your program should have a loop that reads the integers into an array and stops when a negative is entered (the negative number should not be stored). Invoke the average method to find the average of the integers in the array (send the array as the parameter). Does this work?

5. Add a method minimum that takes a variable number of integer parameters and returns the minimum of the parameters. 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;

Page 30: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

result = (double)sum / list.length;}return result;}}

Page 31: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Postlab Activities

Coding Exercise 6

Matrix Inverse

The inverse of a square matrix A is denoted A-1, such that A×A-1 = I, where I is the identity matrix with all 1’s on the diagonal and 0 on all other cells.

The inverse of matrix [1 2 12 3 14 5 3 ]

, for example, is [−2 0 .5 0. 5

1 0 .5 −0.51 −1 .5 0. 5 ]

that is,

[1 2 12 3 14 5 3 ]×[−2 0 .5 0. 5

1 0 .5 −0. 51 −1. 5 0. 5 ]=[1 0 0

0 1 00 0 1 ]

The inverse of a 3 × 3 matrix

A=[ a11 a12 a13

a21 a22 a23

a31 a32 a33]

can be obtained using the following formula if |A|≠0 :

A−1= 1|A|[a22 a33−a23 a32 a13 a32−a12a33 a12a23−a13 a22

a23 a31−a21a33 a11 a33−a13 a31 a13 a21−a11 a23

a21 a32−a22a31 a12 a31−a11a32 a11a22−a12 a21]

|A|=|a11 a12 a13

a21 a22 a23

a31 a32 a33

|=a11 a22 a33+a31a12 a23+a13a21a32−a13 a22 a31−a11 a23 a32−a33a21a12

.

Implement the following function to obtain an inverse of the matrix:

public static double[][] inverse(double[][] A)

Write a test program that prompts the user to enter a11 , a12 , a13 , a21 , a21 , a23 , a31 , a32 , a33 for a matrix and displays its inverse matrix. Here are the sample runs:

Page 32: Cpcs 203 -array-problems

CPCS 203 Lab sheet 1Student Name:_____________________________ Section:__

Sample 1Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 2 1 2 3 1 4 5 3-2 0.5 0.5 1 0.5 -0.5 1 -1.5 0.5

Sample 2Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 4 2 2 5 8 2 1 82.0 -1.875 1.375 0.0 0.25 -0.25 -0.5 0.4375 -0.1875


Recommended