Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Programming with Collections Collections in Java Using Arrays Week 9.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Arrays Chapter 6.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert.
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Loops Chapter 4. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while” structures.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Loops Chapter 4. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while” structures.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
ArrayList, Multidimensional Arrays
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member 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.
1 BUILDING JAVA PROGRAMS CHAPTER 7.1 ARRAY BASICS.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
1 Java Basics: Data Types, Variables, and Loops “ If debugging is the process of removing software bugs, then programming must be the process of putting.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
int [] scores = new int [10];
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
The ArrayList Data Structure The Most Important Things to Review.
The ArrayList Data Structure Standard Arrays at High Speed!
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Building Java Programs
Building Java Programs Chapter 2
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.
Building Java Programs
Building Java Programs
Object Oriented Programming in java
CS2011 Introduction to Programming I Arrays (I)
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Presentation transcript:

Loops Notes adapted from Dr. Flores

It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while” structures

It repeats a set of statements while a condition is true. while ( condition ) { execute these statements; } The dynamics of “while” Evaluate condition: if TRUE go to 2 If FALSE go to 3 Execute statements, and then go to 1 Continue with next statement. The dynamics of “while” Evaluate condition: if TRUE go to 2 If FALSE go to 3 Execute statements, and then go to 1 Continue with next statement

“while” structures It repeats a set of statements while a condition is true. int speedLimit = 55; int speed = 0; while ( speed <= speedLimit ) { speed = speed + 1; } // since we don’t want a ticket… speed = speed - 1; What is the value of “speed” at this point?

“while” structures It repeats a set of statements while a condition is true. int speedLimit = 55; int speed = 0; while ( speed < speedLimit ) { speed = speed + 1; } // since we don’t want a ticket… speed = speed - 1; initialize variables in conditional initialize variables in conditional 1 modify variables in conditional modify variables in conditional 2

“while” structures: Exercises Determine the output of the following methods: public void foo1() { int i=0; while (i <= 20) { System.out.println( i ); i = i + 4; } public void foo2() { int i = 20; while (i > 0) { i = i / 2; System.out.println( i ); }

Do on the board 1.Write a method named “countDown” that receives an integer parameter named “number”, and displays (using System.out.println ) all numbers from the number down to 0. For example, if the parameter was 8, the method should display numbers 7, 6, 5, 4, 3, 2, 1, 0, in this order and with each number in one line. 2.Write a method named “countEven” that receives an integer parameter named “number”, displays (using System.out.println ) all even numbers between 0 and the number received, and returns a integer value with the number of even numbers displayed. For example, if the parameter was 8, the method should display numbers 2, 4 and 6, in this order and with each number in one line, and return a value of 3 (which is how many even numbers were between 0 and 8).

3.Write a method named “reverse” that receives an integer parameter named “number” and displays (using System.out.println) the number with all digits reversed. The method should only work with positive parameter values. For example, if the number was 2001, the method should display (Hint: use modulus by 10 to extract the last digit from the number, and then divide the number by 10 before extracting the next digit). 4.Write a method named “prime” that returns a boolean value indicating whether an integer parameter named number is a prime number (i.e., not divisible by any number except 1 and the number itself). Use only positive integers. Do on Board

“for” structures It (also) repeats statements while a condition is true. Works best when loop will be repeated a known number of times initial statement loop condition modify statement The dynamics of “for” 1. Initialize condition variables. 2. Evaluate loop condition: if TRUE go to 3 If FALSE go to 5 3. Execute statements; then go to 4 4. Modify condition variables; then go to 2 5. Continue with next statements. The dynamics of “for” 1. Initialize condition variables. 2. Evaluate loop condition: if TRUE go to 3 If FALSE go to 5 3. Execute statements; then go to 4 4. Modify condition variables; then go to 2 5. Continue with next statements. for ( ; ; ) { statements; }

prime using for Write a method named “prime” that returns a boolean value indicating whether an integer parameter named number is a prime number. public boolean prime(int nbr) // assumes nbr > 0 { for (int i=2;i<nbr;i++) if (i % nbr == 0) return false; return true; }

“for” structures: Exercises 1.Write a method named “factorial” that calculates the factorial of an integer parameter named “number” (where factorial is the multiplication of all numbers from 1 to number-1). The method should return an integer number with the result of the factorial, and it should work only with positive numbers (return 0 in the case of non-positive parameter numbers). 2.Write a method named “prime” that returns a boolean value indicating whether an integer parameter named “number” is a prime number (where a prime number is a number that is not divisible without remainder by any other numbers except 1 and the number itself). The method should work only with positive numbers (return false if a negative parameter number is given). Sample list of prime numbers: 2, 3, 5, 7, 11, 13, 19, 23…

Arrays Chapter 4

Each variable only holds one item if > 1 item wanted, need an array array that holds a word arrays hold elements all of the same type char[ ] word = new char[4]; holds 4 elements of type char Arrays 0132 word

char[ ] word = new char[4]; two parts to an array: index -- integer element – type inside array 'h''e' 0132 'h' 0132 word[1] = 'e'; 'h''e''o''r' 0132 'h''e''o' 0132 word[3] = 'o'; word[2] = 'r'; word[0] = 'h'; two parts to an array: index -- integer element – type inside array

Can use variables for index OR elements int i=3; char new = 'd'; word[i] = new; can find length word.length // is 4 largest index is always length – 1 word[4] is RUN time error Array manipulation 'h''e''o''r' 0132 'h''e''d''r' 0132

arrays and new char[ ] word; creates word that is of type char array that points to nothing word = new word[4]; creates array of 4 elements initialized to \u0000 (Java always initializes primitives to 0)

Myarray example public class Myarray { private static Circle[ ] circles; private static double[ ] area; // other stuff in the class }

Myarray gets elements allocated Create an object circles = new Circle[4]; area = new double[4];

createcircles() circles[0] = new Circle();

array creation summary char[ ] word; creates a space named word that contains null word = new char [4]; allocates 4 chars, initialized, word points to them classes: Circle[ ] mycircles; same as word mycircles = new Circle[4]; allocates 4 spaces that contain null mycircles[0] = new Circle( ); creates an actual circle

Do: On the board Write code to declare a 4 character word array, then write a loop to initialize chars in word to be 'A' Write code to declare a 4 character array, then write a loop to initalize chars in word to be ABCD (do this in a loop). Hint: use a separate variable for the element value (start with 'A') Declare an int array with 10 integers and write a loop to put the value of the index into the element (e.g., intarray[3] should have the value 3) Declare an int array with 10 integers and write a loop to put the value of the index into the element (e.g., intarray[3] should have the value 3)

Repetition in arrays arrays often do the same thing (e.g., for each Circle in array, create a Circle) for (int i=0; i<circles.length; i++) circles[i] = new Circle( ); memorize this line

“while” structures Adding the values of an array of integers int grades[] = new int[1000]; /* the values of the elements are somehow initialized here. */ int i = 0; int sum = 0; while ( i < grades.length ) { sum += grades[i]; i++; } System.out.println(“The sum is ” + sum);

“for” structures: Exercises 3.Write a method named “digits” that displays (using System.out.println ) the digits of an integer parameter named “number” separated by dashes (“-”). For example, when receiving the number 1234 as a parameter, the method should display “ ”. Hints: use an array to store each digit as you extract them using the modulus operator. Since these digits are stored in the array in the inverse order as they are found in the number, you will need to print them backwards. Also, note that the last digit does not have a trailing dash!

Containers (ArrayList) Chapter 4

ArrayList Like arrays, but have built in operators Use library (package) import java.util.ArrayList; Declare variable private ArrayList circles; To create a list circles = new ArrayList( ); // NOT Circle To add an element to the list (like Circle c) circles.add(c)

More ArrayList methods To find the size: circles.size(); To retrieve an element: circles.get(1); // returns the second element To remove an element circles.remove(1); // removes the second element

ArrayList Overview Part of Java Containers –Not fixed size –Can add without having index ArrayLists, Sets, Maps –Sets have no duplicates and no order –Maps have key and element association Containers have same methods: (size, remove) Can put in any object (want to insert same types) –No primitives in containers

More on Containers No need to specify type of object: private ArrayList circles; circles = new ArrayList( ); // NOT Circle circles.add(c); c could be a Circle, a Square, a Student, ANY object If c is a Student, c.changeColor(“red”); will cause runtime error, not syntax error

ArrayLists (pre Java5) are ugly for loop with index for (int i=0;i<circles.size( ); i++) { Circle c = circles.get(i); // this returns the ith circle c.changeColor(“red”); } Syntax error: –Incompatible types - found java.Lang.Object but expected Circle –Object is superclass of all objects Remember the ()s unlike arrays

ArrayLists are ugly for loop with index for (int i=0;i<circles.size( ); i++) { Circle c = (Circle) circles.get(i); c.changeColor(“red”); } Pre Java-5 containers had to cast object when retrieving them Cast to class that you put in there

ArrayLists and Casting Worse, you could put in something that is NOT a circle: Student s = new Student( ); circles.add(s); // more code, then: (Circle) circles.get(i) // where i is s’s index Runtime error when a circle method is called s.changeColor(“red”) // if s is student

Solution: Java 5 Generics ArrayList circles = new ArrayList ( ); Now, syntax error for: Student s = new Student( ); circles.add(s); Can’t do it

More on Java 5 Generics And, no casting: for (int i=0; i<circles.size( ); i++) { Circle c = circles.get(i); c.changeColor(“red”); } No “(Circle)”

More on Container Loops Containers can use iterators New Java 5 for loop for (Circle c : circles)c.changeColor(“red”); No explicit iterator Read ‘for (’ as “for each”; ‘:’ as “in”

ArrayList Summary Declare Arraylist myName = new ArrayList ( ); Methods –get(i) // returns ith object –add(obj) // inserts obj at end of list –size( ) // returns nbr of elements in list –remove(i) // removes the ith element Loops: with iterators (in text), indexes or foreach loop. No casting needed for “generics” (<> s used)