Enhanced For Loops (For Each Loops) Less Code and Less Overhead for Writing For Loops.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
Hip Hip Array! AP Computer Science. Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays.
Basic Algorithms on Arrays. Learning Objectives Arrays are useful for storing data in a linear structure We learn how to process data stored in an array.
Chapter 10 Introduction to Arrays
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Programming with Collections Collections in Java Using Arrays Week 9.
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.
11-1 Chapter 11 2D Arrays Asserting Java Rick Mercer.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Lecture Today’s topic Arrays Reading for this Lecture: –Chaper 11.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
C++ for Engineers and Scientists Third Edition
Chapter 9 Introduction to Arrays
CS0007: Introduction to Computer Programming Introduction to Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Multiple Choice Solutions True/False a c b e d   T F.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 8 Arrays and Strings
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Java Programming: From Problem Analysis to Program Design, 4e
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Two –Dimensional Arrays Mrs. C. Furman September 18, 2008.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Arrays and Strings. Why? Consider a class of 30 students, each has a score for hw1  Do we want to have 30 variables with different names?  Would it.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
Get Longest Run Index (FR) public int getLongestRunIndex(int []values) { int maxRunStart = -1, maxRunLength = 1; int runStart = 0, runLength = 1; for(int.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
COMP More About Arrays Yi Hong June 05, 2015.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
Arrays. Arrays are objects that help us organize large amounts of information.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
ARRAY AND LOOPS REVIEW Mr. Crone. What will the code below print? int[] arry = {2, 5, 2, 1, 3}; for(int i = 0; i < 5; i ++) System.out.print(arry[i]);
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline 1 Introduction 2 Arrays 3Declaring Arrays 4Processing Array Contents 5 Multiple-Subscripted.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Two Dimensional Array Mr. Jacobs.
Counted Loops.
Arrays, For loop While loop Do while loop
Can store many of the same kind of data together
Can store many of the same kind of data together
Can store many of the same kind of data together
Java: Variables, Input and Arrays
Presentation transcript:

Enhanced For Loops (For Each Loops) Less Code and Less Overhead for Writing For Loops

Enhanced For Loops Enhanced For Loops make it easier to access items in an array or ArrayList or some other kind of list, but there are some limitations. Enhanced For Loops are also called “For Each” loops. This nickname has come about because of what this type of for loop does. It automatically gets each element in the list and stores it in the loop control variable so that it can be processed. The data type of the loop control variable is the same as the kind of data in the list (array or ArrayList).

Limitations of Enhanced For Loops The main limitation of Enhanced For Loops is that you cannot make changes to the elements inside the list. You can only access the elements in the list, but you can take them as you get them out and perform other operations. Specifically you cannot …

Limitations of Enhanced For Loops You cannot … Move through an array in reverse, from the last position to the first position (a countdown loop that accesses indexes could do this) Assign elements to particular positions in an array Track the index position of the current element in an array (unless you use an extra counter variable) Access any element other than the current element on each iteration of the loop

General Form of an Enhanced For Loop Here is the general form of an enhanced for loop where there are a list of values. for (type of values in list loop control variable : actual name of list in program) { ……… } If the type of values in the list is represented by E, then we could write …. for (E element : list) { ……… } where element is of type E and list is the name of the list in the program.

Enhanced For Loop for an array of ints int [ ] nums = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; If we want to code an enhanced for loop that will print only the multiples of 10 in nums, then we need a loop control variable of type int, because there are int values in the array. for (int element : nums ) { if (element % 10 == 0) System.out.print( element + “ ”); } Compare this code to standard for loop code: for (int i = 0; i < nums.length; i++) { int element = nums [i]; if (element % 10 == 0) System.out.print( element + “ ”); } Everything to the left in blue is extra code you have to write!

Enhanced For Loop for an array of doubles double [ ] averages = {88.3, 75.4, 67.8, 93.5, 98.1, 82.7, 79.6, 73.4, 86.7}; If we want to code an enhanced for loop that will print only the values in averages that are greater than or equal to 80, then we need a loop control variable of type double, because there are double values in the array. for (double element : averages ) { if (element >= 80) System.out.print( element + “ ”); } Compare this code to standard for loop code: for (int i = 0; i < averages.length; i++) { double element = averages[i]; if (element >= 80) System.out.print( element + “ ”); } Everything to the left in blue is extra code you have to write!

Enhanced For Loop for an array of Objects String [ ] names = {“Obama”, “Bush”, “Clinton”, “Reagan”, “Carter”, “Ford” }; If we want to code an enhanced for loop that will print only the names that begin with a “C”, then we need a loop control variable of type String, because there are String values in the array. for (String element : names) { if (element.substring(0,1).equals(“C”)) System.out.print( element + “ ”); } Compare this code to standard for loop code: for (int i = 0; i < names.length; i++) { String element = names[i]; if (element.substring(0,1).equals(“C”)) System.out.print( element + “ ”); } Everything to the left in blue is extra code you have to write!

Enhanced For Loop for an ArrayList ArrayList names = new ArrayList (); // Code that places Obama, Bush, Clinton, Reagan, Carter, Ford, Nixon in list. If we want to code an enhanced for loop that will print only the names that begin with a “C”, then we need a loop control variable of type String, because there are String values in the array. for (String element : names) { if (element.substring(0,1).equals(“C”)) System.out.print( element + “ ”); } Compare this code to standard for loop code: for (int i = 0; i < names.length; i++) { String element = names[i]; if (element.substring(0,1).equals(“C”)) System.out.print( element + “ ”); } Note the code is not any different for an ArrayList! Everything to the left in blue is extra code you have to write!

Enhanced For Loop for an ArrayList ArrayList students = new ArrayList (); // Code that places students in list. If we want to code an enhanced for loop that will print the name and GPA of all students, then we need a loop control variable of type Student, because there are Student values in the ArrayList. for (Student element : students) { System.out.print( element.getName() + element.getGPA()); } Compare this code to standard for loop code: for (int i = 0; i < students.length; i++) { Student element = students[i]; System.out.print( element.getName() + element.getGPA()); } Everything to the left in blue is extra code you have to write!

Nested Enhanced For Loops for a 2D Array Here is an example of how to use nested enhanced for loops with a two-dimensional array of integers. // Sum the elements in a two-dimensional array int [ ] [ ] table = { {2, 3, 4}, {2, 3, 4}, {2, 3, 4} }; int sum = 0; for (int [ ] row : table) for (int element : row ) sum += element ; System.out.println(Sum: " + sum); }

Nested Enhanced For Loops for a 2D Array Here is an example of how to use an enhanced for loop with a two-dimensional array of Strings values. // concatentate all the string values in table into one string String [ ][ ] table = { {“A”, “B”, “C”}, {“D”, “E”, “F”} } String str = “”; for (String [ ] row : table) for (String element : row ) str += element; }