Instructor: Eng.Omar Al-Nahal

Similar documents
Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Arrays (Deitel chapter 7)

Object Oriented Programming. Java-Lecture 6 - Arrays

Computer Programming: C++

Control Statements. Musa M. Ameen Computer Engineering Dept.

Arrays OBJECTIVES. In this chapter you will learn:

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

CS111: PROGRAMMING LANGUAGE II

Arrays. Eng. Mohammed Abdualal

Array. Prepared By - Rifat Shahriyar

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Programming for Engineers Arrays

Multiple-Subscripted Arrays

Control Statements: Part 1

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Introduction to Java Applications

CS111: PROGRAMMING LANGUAGE II

Chapter 7 Array. Array. C++, How to Program

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

C: How to Program. Week /Apr/23

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 12 Two-Dimensional Arrays

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Introduction to Java & Fundamental Data Types

Arrays and Applications

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Chapter 4: Control structures. Repetition

Recap: Assignment as an Operator CS 112 Introduction to Programming

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Chapter 4: Control structures

CS 112 Introduction to Programming

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Chapter 6: Using Arrays

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

More non-primitive types Lesson 06

Spring 2010 Java Programming

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Computer Science is...

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Pace University. Fundamental Concepts of CS121 1

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

2.8. Decision Making: Equality and Relational Operators

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

AP CS Unit 3: Control Structures Notes

Chapter 9 Introduction to Arrays. Fundamentals of Java

C Arrays Pearson Education, Inc. All rights reserved.

Lab Session # 5 Arrays. ALQUDS University Department of Computer Engineering

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Programming with Java

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

Lecture 04 FUNCTIONS AND ARRAYS

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Introduction to Programming Using Java (98-388)

Arrays Pearson Education, Inc. All rights reserved.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Example: Monte Carlo Simulation 1

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

egrapher Language Reference Manual

Computer Programming, I. Laboratory Manual. Final Exam Solution

Introduction to the Java Basics: Control Flow Statements

C++ PROGRAMMING SKILLS Part 4: Arrays

PieNum Language Reference Manual

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

CP122 CS I. Iteration

Unit 3 Decision making, Looping and Arrays

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Advanced Computer Programming

array Indexed same type

Repetition CSC 121 Fall 2014 Howard Rosenthal

Give one example where you might wish to use a three dimensional array

Creating Two-dimensional Arrays

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Software Development (ISD) Week 3

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

APCS Semester #1 Final Exam Practice Problems

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Nested Loops. A loop can be nested inside another loop.

Computational Expression

Transcription:

Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar Al-Nahal Copyright March, 2010 WWW.PALINFONET.COM

Lab 6 1. Lab Objectives In this Lab you will learn: 1. To use arrays to store data in and retrieve data from lists and tables of values. 2. 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. 4. To pass arrays to methods. 5. To declare and manipulate multidimensional arrays. 2. Prior to the Laboratory Before you come to the lab, you should read about simple java programs instructions in the course and solve the homework below. You should also read this laboratory exercise in detail. Note that you must solve the homework. Read in book, Chapter 7, Sections 7.2,7.,7.4,7.5,7.6,7.7,7.8,7.9 Review the Theoretical Lesson.. Learn Java Programming by Examples Declaring and Creating Arrays Array objects occupy space in memory. Like other objects, arrays are created with keyword new. To create an array object, the programmer specifies the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. Such an expression returns a reference that can be stored in an array variable. The following declaration and array-creation expression create an array object containing 12 int elements and store the array's reference in variable c: int c[] = new int[ 12 ]; int c[]; c = new int[ 12 ]; // declare the array variable // create the array; assign to array variable In the declaration, the square brackets following the variable name c indicate that c is a variable that will refer to an array (i.e., the variable will store an array reference). In the assignment statement, the array variable c receives the reference to a new array of 12 int elements. When an array is created, each element of the array receives a default valuezero for the numeric primitive-type elements, false for boolean elements and null for references (any nonprimitive type). As we will soon see, we can provide specific, nondefault initial element values when we create an array. A program can create several arrays in a single declaration. The following String array declaration reserves 100 elements for b and 27 elements for x:

2 String b[] = new String[ 100 ], x[] = new String[ 27 ]; In this case, the class name String applies to each variable in the declaration. For readability, we prefer to declare only one variable per declaration, as in: String b[] = new String[ 100 ]; // create array b String x[] = new String[ 27 ]; // create array x When an array is declared, the type of the array and the square brackets can be combined at the beginning of the declaration to indicate that all the identifiers in the declaration are array variables. For example, the declaration double[] array1, array2; indicates that array1 and array2 are "array of double" variables. The preceding declaration is equivalent to: double array1[]; double array2[]; or double[] array1; double[] array2; The preceding pairs of declarations are equivalentwhen only one variable is declared in each declaration, the square brackets can be placed either after the type or after the array variable name. In the Java programming language arrays are objects, are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive. 2

In this program we will see how to declare and implementation. A Simple Example The example: class Gauss { public static void main(string[] args) { int[] ia = new int[101]; for (int i = 0; i < ia.length; i++) ia[i] = i; int sum = 0; for (int i = 0; i < ia.length; i++) sum += ia[i]; System.out.println(sum); } } That produces the output: 5050 --------------------------------------------------------------------------------------------------------------------------- Using an Array Initializer A program can create an array and initialize its elements with an array initializer, which is a commaseparated list of expressions (called an initializer list) enclosed in braces ({ and }). In this case, the array length is determined by the number of elements in the initializer list. For example, the declaration int n[] = { 10, 20, 0, 40, 50 }; creates a five-element array with index values 0, 1, 2, and 4. Element n[ 0 ] is initialized to 10, n[ 1 ] is initialized to 20, and so on. This declaration does not require new to create the array object. When the compiler encounters an array declaration that includes an initializer list, the compiler counts the number of initializers in the list to determine the size of the array, then sets up the appropriate new operation "behind the scenes." Initializing the elements of an array with an array initializer. 1 // Fig. 7.: InitArray.java 2 // Initializing the elements of an array with an array initializer. 4 public class InitArray 5 { 6 public static void main( String args[] ) 7 { 8 // initializer list specifies the value for each element 9 int array[] = { 2, 27, 64, 18, 95, 14, 90, 70, 60, 7 }; 10 11 System.out.printf( "%s%8s\n", "Index", "Value" ); // column

4 headings 12 1 // output each array element's value 14 for ( int counter = 0; counter < array.length; counter++ ) 15 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 16 } // end main 17 } // end class InitArray Index Value 0 2 1 27 2 64 18 4 95 5 14 6 90 7 70 8 9 60 7 In this program the sort() function of the java.util.*; package is using to sort all the numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending order by default. The example: import java.util.*; public class array{ public static void main(string[] args){ int num[] = {50,20,45,82,25,6}; int l = num.length; int i,j,t; System.out.print("Given number : "); for (i = 0;i < l;i++ ){ System.out.print(" " + num[i]); } System.out.println("\n"); System.out.print("Accending order number : "); Arrays.sort(num); for(i = 0;i < l;i++){ System.out.print(" " + num[i]); } } } That produces the output: Given number : 50 20 45 82 25 6 Ascending order number : 20 25 45 50 6 82 Enhanced for Statement In previous examples, we demonstrated how to use counter-controlled for statements to iterate through the elements in an array. In this section, we introduce a feature new in J2SE 5.0the enhanced for 4

5 statement, which iterates through the elements of an array or a collection without using a counter. This section discusses how to use the enhanced for statement to loop through an array. We show how to use the enhanced for statement. The syntax of an enhanced for statement is: for ( parameter : arrayname ) statement Using the enhanced for statement to total integers in an array. 1 // Fig. 7.12: EnhancedForTest.java 2 // Using enhanced for statement to total integers in an array. 4 public class EnhancedForTest 5 { 6 public static void main( String args[] ) 7 { 8 int array[] = { 87, 68, 94, 100, 8, 78, 85, 91, 76, 87 }; 9 int total = 0; 10 11 // add each element's value to total 12 for ( int number : array ) 1 total += number; 14 15 System.out.printf( "Total of array elements: %d\n", total ); 16 } // end main 17 } // end class EnhancedForTest Total of array elements: 849 The enhanced for statement simplifies the code for iterating through an array. Note, however, that the enhanced for statement can be used only to access array elementsit cannot be used to modify elements. If your program needs to modify elements, use the traditional counter-controlled for statement. The enhanced for statement can be used in place of the counter-controlled for statement whenever code looping through an array does not require access to the counter indicating the index of the current array element. For example, totalling the integers in an array requires access only to the element valuesthe index of each element is irrelevant. However, if a program must use a counter for some reason other than simply to loop through an array (e.g., to print an index number next to each array element value, as in the examples earlier in this chapter), use the counter-controlled for statement. Passing Arrays to Methods This section demonstrates how to pass arrays and array elements as arguments to methods. At the end of the section, we discuss how all types of arguments are passed to methods. To pass an array argument to a 5

6 method, specify the name of the array without any brackets. For example, if array hourlytemperatures is declared as double hourlytemperatures[] = new double[ 24 ]; then the method call modifyarray( hourlytemperatures ); passes the reference of array hourlytemperatures to method modifyarray. Every array object "knows" its own length (via its length field). Thus, when we pass an array object's reference into a method, we need not pass the array length as an additional argument. For a method to receive an array reference through a method call, the method's parameter list must specify an array parameter. For example, the method header for method modifyarray might be written as void modifyarray( int b[] ) indicating that modifyarray receives the reference of an integer array in parameter b. The method call passes array hourlytemperature's reference, so when the called method uses the array variable b, it refers to the same array object as hourlytemperatures in the calling method. See example in Java how to Program Chapter 7, Section 7.7 Multidimensional Arrays Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indices. By convention, the first identifies the element's row and the second its column. Arrays that require two indices to identify a particular element are called two-dimensional arrays. (Multidimensional arrays can have more than two dimensions.) Java does not support multidimensional arrays directly, but it does allow the programmer to specify one-dimensional arrays whose elements are also one-dimensional arrays, 6

7 Arrays of One-Dimensional Arrays Like one-dimensional arrays, multidimensional arrays can be initialized with array initializers in declarations. A two-dimensional array b with two rows and two columns could be declared and initialized with nested array initializers as follows: int b[][] = { { 1, 2 }, {, 4 } }; The initializer values are grouped by row in braces. So 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ], respectively, and and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ], respectively. The compiler counts the number of nested array initializers (represented by sets of braces within the outer braces) in the array declaration to determine the number of rows in array b. The compiler counts the initializer values in the nested array initializer for a row to determine the number of columns in that row. As we will see momentarily, this means that rows can have different lengths. Multidimensional arrays are maintained as arrays of one-dimensional arrays. Therefore array b in the preceding declaration is actually composed of two separate one-dimensional arraysone containing the values in the first nested initializer list { 1, 2 } and one containing the values in the second nested initializer list {, 4 }. Thus, array b itself is an array of two elements, each a one-dimensional array of int values. Two-Dimensional Arrays with Rows of Different Lengths The manner in which multidimensional arrays are represented makes them quite flexible. In fact, the lengths of the rows in array b are not required to be the same. For example, int b[][] = { { 1, 2 }, {, 4, 5 } }; creates integer array b with two elements (determined by the number of nested array initializers) that represent the rows of the two-dimensional array. Each element of b is a reference to a one-dimensional array of int variables. The int array for row 0 is a one-dimensional array with two elements (1 and 2), and the int array for row 1 is a one-dimensional array with three elements (, 4 and 5). Creating Two-Dimensional Arrays with Array-Creation Expressions A multidimensional array with the same number of columns in every row can be created with an arraycreation expression. For example, the following lines declare array b and assign it a reference to a threeby-four array: int b[][]; b = new int [ ][ 4 ]; In this case, we use the literal values and 4 to specify the number of rows and number of columns, respectively, but this is not required. Programs can also use variables to specify array dimensions. As with one-dimensional arrays, the elements of a multidimensional array are initialized when the array object is created. 7

8 A multidimensional array in which each row has a different number of columns can be created as follows: int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ ]; // create columns for row 1 The preceding statements create a two-dimensional array with two rows. Row 0 has five columns, and row 1 has three columns. Two-Dimensional Array Example: Displaying Element Values 1 // Fig. 7.17: InitArray.java 2 // Initializing two-dimensional arrays. 4 public class InitArray 5 { 6 7 // create and output two-dimensional arrays public static void main( String args[] ) 8 { 9 10 int array1[][] = { { 1, 2, }, { 4, 5, 6 } }; int array2[][] = { { 1, 2 }, { }, { 4, 5, 6 } }; 11 12 System.out.println( "Values in array1 by row are" ); 1 outputarray( array1 ); // displays array1 by row 14 15 System.out.println( "\nvalues in array2 by row are" ); 16 outputarray( array2 ); // displays array2 by row 17 } // end main 18 19 // output rows and columns of a two-dimensional array 20 public static void outputarray( int array[][] ) 21 22 { // loop through array's rows 2 for ( int row = 0; row < array.length; row++ ) 24 { 25 // loop through columns of current row 26 for ( int column = 0; column < array[ row ].length; column++ ) 27 System.out.printf( "%d ", array[ row ][ column ] ); 28 29 System.out.println(); // start new line of output 0 1 } // end outer for } // end method outputarray 2 } // end class InitArray Values in array1 by row are 1 2 4 5 6 Values in array2 by row are 1 2 4 5 6 Class InitArray's main declares two arrays. The declaration of array1 (line 9) uses nested array initializers to initialize the first row of the array to the values 1, 2 and, and the second row to the values 4, 5 and 6. The declaration of array2 (line 10) uses nested initializers of different lengths. In this case, the first row is initialized to have two elements with values 1 and 2, respectively. The second row is 8

9 initialized to have one element with value. The third row is initialized to have three elements with the values 4, 5 and 6, respectively. Lines 1 and 16 call method outputarray (lines 20-1) to output the elements of array1 and array2, respectively. Method outputarray specifies the array parameter as int array[][] to indicate that the method receives a two-dimensional array. The for statement (lines 2-0) outputs the rows of a twodimensional array. In the loop-continuation condition of the outer for statement, the expression array.length determines the number of rows in the array. In the inner for statement, the expression array[ row ].length determines the number of columns in the current row of the array. This condition enables the loop to determine the exact number of columns in each row. Common Multidimensional-Array Manipulations Performed with for Statements Many common array manipulations use for statements. As an example, the following for statement sets all the elements in row 2 of array. for ( int column = 0; column < a[ 2 ].length; column++) a[ 2 ][ column ] = 0; We specified row 2; therefore, we know that the first index is always 2 (0 is the first row, and 1 is the second row). This for loop varies only the second index (i.e., the column index). The preceding for statement is equivalent to the assignment statements a[ 2 ][ 0 ] = 0; a[ 2 ][ 1 ] = 0; a[ 2 ][ 2 ] = 0; a[ 2 ][ ] = 0; The following nested for statement totals the values of all the elements in array a: int total = 0; for ( int row = 0; row < a.length; row++ ) { for ( int column = 0; column < a[ row ].length; column++ ) total += a[ row ][ column ]; } // end outer for This nested for statements total the array elements one row at a time. The outer for statement begins by setting the row index to 0 so that the first row's elements may be totaled by the inner for statement. The outer for then increments row to 1 so that the second row can be totaled. Then, the outer for increments row to 2 so that the third row can be totaled. The variable total can be displayed when the outer for statement terminates. In the next example, we show how to process a two-dimensional array in a similar manner using nested enhanced for statements. 9

10 4. Activities/Exercises Write a program using a function to read an array of 12 integer values and print the sum & find the maximum of numbers. Write a program to multiply two matrices. You will need to use two-dimensional arrays. The declaration should be of the form double matrix1 [][], matrix2[][], matrix[][]. You should use nested for-loops. (A loop is nested if it is inside another loop.) Write the whole program in the main function without using any functions. Write a program to read two matrix of 4 rows and the following columns: The first row contains integers. The second row contains 4 integers. The third row contains 2 integers. The fourth row contains 5 integers and use loop to find the sum of each row and columns. 5. Activities/Homework Use a two-dimensional array to solve the following problem: A company has four salespeople (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each type of product sold. Each slip contains the following: a. The salesperson number b. The product number c. The total dollar value of that product sold that day Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume that the information from all the slips for last month is available. Write an application that will read all this information for last month's sales and summarize the total sales by salesperson and by product. All totals should be stored in the two-dimensional array sales. After processing all the information for last month, display the results in tabular format, with each column representing a particular salesperson and each row representing a particular product. Cross-total each row to get the total sales of each product for last month. Cross-total each column to get the total sales by salesperson for last month. Your tabular output should include these cross-totals to the right of the totaled rows and to the bottom of the totaled columns. 6. Web Resources # Java Java Tutorial http://www.learn-java-tutorial.com/java-arrays.cfm # Arab Academy for Information Technology شبكة معلومات فلسطين http://www.palinfonet.com 10