Arrays, 2-D Arrays, and ArrayList

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 8 Arrays and Strings
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Array in C# Array in C# RIHS Arshad Khan
EGR 2261 Unit 10 Two-dimensional Arrays
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Parameter Lists & Command Line Arguments
JavaScript: Functions.
2D Arrays October 12, 2007 ComS 207: Programming I (in Java)
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays in Java What, why and how Copyright Curt Hill.
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
int [] scores = new int [10];
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
CS1001 Lecture 14.
Visual Programming COMP-315
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
How do you do the following?
Arrays.
Presentation transcript:

Arrays, 2-D Arrays, and ArrayList

Objectives Learn about arrays and when to use them Learn the syntax for declaring and initializing arrays and how to access array’s size and elements Learn about the java.util.ArrayList class Discuss “for each” loops Learn simple array algorithms Understand two-dimensional arrays

Arrays Array – memory blocks consisting of several consecutive memory locations of the same data type under the same name. Elements – individual memory locations. Size or length - number of elements Index or subscript – element’s number

What is an Array An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array’s elements. When we say “element” we often mean the value stored in that element. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. An array of doubles 1.39 1.69 1.74 0.0

What is an Array (cont’d) Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms. 1.39 1.69 1.74 0.0 c is array’s name c[0] c[1] c[2] c[3]

Indices (Subscripts) In Java, an index is written within square brackets following array’s name (for example, a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1. The convention of starting indices from 0 comes from C. It is easy to get used to.

Indices (cont’d) We can use as an index an int variable or any expression that evaluates to an int value. For example: a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ] That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.

Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one filled with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and then aborts the program.

Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. No arrays: With arrays: int sum = 0; sum += score0; sum += score1; … sum += score999; int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible: with linked lists (Chapter 20). 1000 times!

Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. No arrays: With arrays: if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); 1000 times! “Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as opposed to scanning from the beginning to find an item (as on a tape).

Advantages Allows you to store many values of the same type. Allows you to manipulate large quantities of data of the same type. Makes coding easier

Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. Array declaration: anyType [ ] arrName; This has several implications: you have to create (initialize) an array before you can use it, an array is passed to methods as a reference, etc. You can pass an array to any method that expects an Object type of argument. If you want to test it, try: Object x = new int[100];

Arrays as Objects (cont’d) As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. One way to create an array: arrName = new anyType [length] ; Brackets, not parens! The second way is show later, on Slide 12-14

Declaring Arrays Java treats arrays as objects of the data type that it is declared as. Declaring Arrays DataType name[]; int sum[]; Declaring more than one Array DataType [] name1, name2; String [] first, last; Same as String first[], last[]; Arrays in Java are treated as objects

Alternate Array Syntax The brackets of the array type can be associated with the element type or with the name of the array Therefore the following two declarations are equivalent: float[] prices; float prices[]; The first format generally is more readable and should be used

Declaring & Creating Arrays Use the new operator Example: int score[] = new int[10]; String words[] = new String[12]; Notice the bracket is used instead of parentheses. Number in brackets indicates the size of the array.

Arrays declaring and creating When an array is created, its elements are initialized to default values. (0 –Numeric, false – boolean, null - objects) If the array elements are of that type, then the array contains references to objects of that type and they are initialized to null Once an array is declared and initialized, it is not possible to change its size. You can only reassign its name to another array and throw away the first one.

Explicitly Declaring and Creating an Array Another way to declare and create an array is to list explicitly, between braces, the values of all its elements. The new operator is not used in this form. Example: int scores[] = {95, 56, 76, 58}; String name[] = {“Bob”, “Sue”, “Sam”};

Arrays An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 scores The entire array has a single name Each value has a numeric index 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used

Arrays For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);

Arrays The values held in an array are called array elements An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. In Java, the array itself is an object that must be instantiated

Arrays Another way to depict the scores array: scores 79 87 94 82 67 98 81 74 91

int[] scores = new int[10]; Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers) Note that the array type does not specify its size, but each object of that type has a specific size The reference variable scores is set to a new array object that can hold 10 integers

Declaring Arrays Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

Using Arrays The iterator version of the for loop can be used when processing array elements for (int score : scores) System.out.println (score); This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index)

Declaration and Initialization When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. For example: length 10, all values set to 0 As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.” scores = new int [10] ; words = new String [10000]; length 10000, all values set to null

Initialization (cont’d) An array can be declared an initialized in one statement. For example: int [ ] scores = new int [10] ; private double [ ] gasPrices = { 3.05, 3.17, 3.59 }; String [ ] words = new String [10000]; String [ ] cities = {"Atlanta", "Boston", "Cincinnati" }; Nothing new here: this is true for any object.

Initialization (cont’d) Otherwise, initialization can be postponed until later. For example: Not yet initialized String [ ] words; ... words = new String [ console.readInt() ]; private double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; Not yet initialized If you try to use an unititialized array, (for example, arr.length or arr[k]), you will get a NullPointerException. The second initialization form (for gasPrices) is not in the AP subset.

Initializing Elements Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects. If its elements are objects, the array holds references to objects, which are initially set to null. Each object-type element must be initialized before it is used. It is important to understand this two-step process for initializing an array of objects: first you create the array object as a whole; then you initialize each element.

Access array’s elements using indices A program can access individual elements of an array using indices(subscripts). An index is an integer value placed in square brackets after the array name to indicate the consecutive number of the element. In Java arrays are numbered starting at 0. Example: int num[] = {5,6,7,8}; 5 is in the 0 position num[0]; 6 is in the 1st position num[1]; 7 is in the 2nd position num[2]; 8 is in the 3rd position num[3];

Accessing arrays y  8 int num[] = {5,6,7,8}; int x = 2; int y = num[x]; y  7 Or y = num[x+1]; y  8

Access array’s length In arrays, length is not a method (as in the String Class). It is accessed like a field , without parenthesis. Example: int nums[] = {1,2,3,4}; int y = nums.length; y  4

Length All indices must fall in the range from 0 to length – 1, where length is the number of elements in the array. If an index happens to be out of this range, your program will report a run-time error (IndexOutOfBoundsException)

Pass arrays to methods Arrays are not immutable objects. You can set any elements in an array with a simple assignment statement. Like other Java objects, arrays are always passed to methods as references. If an array is passed to a method, the method gets the address of the original array and works with the original array, not a copy.

Examples of passing Arrays Methods Signatures public void swap(int x[]) Call Obj.swap(nameOfArray);//no brackets

Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length is like a public field (not a method) in an array object. As opposed to String, where length() is a method.

Passing Arrays to Methods As other objects, an array is passed to a method as a reference. The elements of the original array are not copied and are accessible in the method’s code. // Swaps a [ i ] and a [ j ] public void swap (int [ ] a, int i, int j) { int temp = a [ i ]; a [ i ] = a [ j ]; a [ j ] = temp; } So a void method can do all kinds of things to an array passed to it as a parameter.

Returning Arrays from Methods As any object, an array can be returned from a method. The returned array is usually constructed within the method or obtained from calls to other methods. The return type of a method that returns an array with someType elements is designated as someType[ ]. It is helpful to think of someType[] as a data type designation, “array of someType elements.”

Returning Arrays from Methods (cont’d) public double[ ] solveQuadratic (double a, double b, double c) { double d = b * b - 4 * a * c; if (d < 0) return null; d = Math.sqrt(d); double[ ] roots = new double[2]; roots[0] = (-b - d) / (2*a); roots[1] = (-b + d) / (2*a); return roots; } Or simply: return new double[ ] { (-b - d) / (2*a), (-b + d) / (2*a) }; Since any type of reference can be set to null, it is legal to return null from a method that is supposed to return an array. This means the array has not been created in the method (not to be confused with an array that has been created but whose elements are set to null). Again, the form with a list of values in braces {...}, called “anonymous initialized array,” is not in the AP subset.

Inserting a Value (cont’d) 1. Find the right place to insert: 2. Shift elements to the right, starting from the last one: 3. Insert the value in its proper place: 5 Can be combined together in one loop: look for the place to insert while shifting. 1 1 2 3 8 13 5 1 1 2 3 8 13 When an element is removed, the subsequent elements are shifted to the left, starting from the leftmost. 1 1 2 3 5 8 13

Inserting a Value (cont’d) // Returns true if inserted successfully, false otherwise public boolean insert(double[ ] arr, int count, double value) { if (count >= arr.length) return false; int k = count - 1; while ( k >= 0 && arr [ k ] > value ) arr [ k + 1 ] = arr [ k ]; k--; } arr [ k + 1] = value; return true; Or it could just throw an IndexOutOfBoundsException if the array is full.

Bounds Checking Once an array is created, it has a fixed size An index used in an array reference must specify a valid element That is, the index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsExceptio n if an array index is out of bounds This is called automatic bounds checking

Bounds Checking For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 If the value of count is 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); It’s common to introduce off-by-one errors when using arrays problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index

Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Initializer Lists Note that when an initializer list is used: the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can be used only in the array declaration

Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

System.out.println (words[0]); Arrays of Objects The words array when initially declared: words - At this point, the following reference would throw a NullPointerException: System.out.println (words[0]);

String[] words = new String[5]; Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately

Arrays of Objects After some String objects are created and stored in the array: “friendship” words - “loyalty” “honor”

Arrays of Objects Keep in mind that String objects can be created using literals The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"};

Variable Length Parameter Lists Suppose we wanted to create a method that processed a different amount of data from one invocation to the next For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

Variable Length Parameter Lists We could define overloaded versions of the average method Downside: we'd need a separate version of the method for each parameter count We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists

Variable Length Parameter Lists Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method Indicates a variable length parameter list public double average (int ... list) { // whatever } array name element type

Variable Length Parameter Lists public double average (int ... list) { double result = 0.0; if (list.length != 0) int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result;

Variable Length Parameter Lists The type of the parameter can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }

Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever }

Variable Length Parameter Lists The varying number of parameters must come last in the formal arguments A single method cannot accept two sets of varying parameters Constructors can also be set up to accept a variable number of parameters

2-D Arrays

Two-Dimensional Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns two dimensions one dimension

Two-Dimensional Arrays To be precise, in Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; A array element is referenced using two index values: value = scores[3][6] The array stored in one row can be specified using one index

Two-Dimensional Arrays Expression Type Description table int[][] 2D array of integers, or array of integer arrays table[5] int[] array of integers table[5][12] int integer

Multidimensional Arrays An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays

2-D Arrays 2-D arrays are used to represent rectangular tables of elements of the same type.

Declare a 2-D Array Two ways to declare a 2-D array int name[][] = new int[5][4]; int name[][] = {{1,2,3},{4,5,6}}; The first set of brackets represents the row and the second set of brackets represents the column. The 2-D array is set to the default values if not initialized.

Accessing a 2-D Array We access the elements of a 2-D array with a pair of indices, each placed in square brackets. We can think of the first index as a “row” and the second as a “column”. Both indices start from 0. Example: int arr[][] ={{1,2,3},{4,5,6}}; Then arr[0][0] =1;arr[0][1] = 2; arr[0][2] = 3; arr[1][0] = 4; arr[1][1] = 5;arr[1][2] = 6;

Length of a 2-D array If m is a 2-D array, then m.length is the number of rows in the array, m[0] is the first row (a 1-D array), and m[0].length is the number of columns(in the first row). m[r][c] is the element in row r and column c. You can also declare a 3-D array the same way as a 2-D array.

Two-Dimensional Arrays 2-D arrays are used to represent tables, matrices, game boards, images, etc. An element of a 2-D array is addressed using a pair of indices, “row” and “column.” For example: board [ r ] [ c ] = 'x'; For some reason, 2-D arrays have been excluded from the AP-A subset. They remain in the AP-AB subset.

2-D Arrays: Declaration // 2-D array of char with 5 rows, 7 cols: char[ ] [ ] letterGrid = new char [5][7]; // 2-D array of Color with 1024 rows, 768 cols: Color[ ] [ ] image = new Color [1024][768]; // 2-D array of double with 2 rows and 3 cols: double [ ] [ ] sample = { { 0.0, 0.1, 0.2 }, { 1.0, 1.1, 1.2 } }; It is simply a convention that the first index is “row” and the second “column.”

2-D Arrays: Dimensions In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations. If m is a 2-D array, then m[k] is a 1-D array, the k-th row. m.length is the number of rows. m[k].length is the length of the k-th row. Nothing unusual: an array of rows contains objects; each object happens to be an array.

Dimensions (cont’d) Java allows “ragged” arrays, in which different rows have different lengths. In a rectangular array, m[0].length can be used to represent the number of columns. “Ragged” array: Rectangular array: Ragged 2-D arrays are not in the AP subset. m.length m.length m[3].length m[0].length

2-D Arrays and Nested Loops A 2-D array can be traversed using nested loops: for (int r = 0; r < m.length; r++) { for (int c = 0; c < m[0].length; c++) ... // process m[ r ][ c ] } Sometimes we need to traverse by column first, then by row.

“Triangular” Loops “Transpose a matrix” idiom: int n = m.length; for (int r = 1; r < n; r++) { for (int c = 0; c < r; c++) double temp = m [ r ][ c ]; m [ r ][ c ] = m [ c ][ r ]; m [ c ][ r ] = temp; } The total number of iterations through the inner loop is: 1 + 2 + 3 + ... + n-1 = n (n - 1) / 2 “Triangular” loops are also used to find duplicate values in a list, and in other algorithms. To find the sum of an arithmetic sequence 1 + 2 + ... + (n-1), take the average of the first and the last terms and multiply it by the number of terms.