CSC 211 Java I for loops and arrays.

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

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
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.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
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.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
COMP Loop Statements Yi Hong May 21, 2015.
int [] scores = new int [10];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Week 6 - Friday.  What did we talk about last time?  Loop examples.
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.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Comp1004: Loops and Arrays I Whiles, For and Arrays[]
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.
Information and Computer Sciences University of Hawaii, Manoa
Arrays.
REPETITION CONTROL STRUCTURE
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
© 2016 Pearson Education, Ltd. All rights reserved.
Loop Structures.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Arrays, For loop While loop Do while loop
Arrays An Array is an ordered collection of variables
Outline Altering flow of control Boolean expressions
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.
int [] scores = new int [10];
Defining methods and more arrays
Module 4 Loops.
int [] scores = new int [10];
Announcements Lab 6 was due today Lab 7 assigned this Friday
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
Java Programming Loops
Suggested self-checks: Section 7.11 #1-11
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays.
Week 7 - Monday CS 121.
Presentation transcript:

CSC 211 Java I for loops and arrays

Today’s plan Midterm Primitive data types vs. object variables for Loops Arrays

Midterm Statistics High: 99%, Low: 43%, Average: 81% 100 – 90: 6 89 – 80: 6 79 – 70: 2 <=69: 3 Course grading review: Labs: 20% OWL: 10% Programs: 25% Midterm: 45% (both exams together)

Today’s plan Midterm Primitive data types vs. object variables for Loops Arrays

The Key: When it comes to objects, you must distinguish between the object’s reference and the object’s state (data). This is vital! While a bit confusing at the moment, we will discuss it in class. Review online and/or with your textbook Practice and become familiar with this principle

Overview: When it comes to primitive data types, the information stored by the variable is the value. When it comes to objects, the information stored by the variable is the memory address of the object.

** Primitive types vs objects “I love Java” x 4 love Memory location x033622x3544 int x; x=4; String love; love=new String(“I love Java”); x holds a value love holds a reference (to an object) -- actually the reference to the memory location where the object is stored

Assignment of primitive data type x y 4 5 int x = 4, y = 5; Recall: Since x and y are primitive data types (i.e. int), they store values. So when you say y = x, you are assigning the value of x to y. However, things work differently with objects…. With objects, if you say objB = objA, you are not assigning the value of one to the other. Instead, you are assigning the memory address. y = x;

Assignment of strings s f s f s f t t = = s; s = = f; s.equals(t); “soup” “fish” s f String s =new String(“soup”), f =new String(“fish”); String t = new String(“soup”); s f “soup” “fish” s f “soup” “fish” t “soup” f = s; t = = s; s = = f; s.equals(t);

public boolean equals (String yourString) Comparing Strings public boolean equals (String yourString) boolean check1, check2; String love=new String(“I love Java”); check1 = love.equals(“I LOVE JAVA”); Value of check1 is? check2 = love.equalsIgnoreCase(“I LOVE JAVA”); Value of check2 is?

Today’s plan Midterm Primitive data types vs. object variables for Loops Arrays

Remember the while loop: If condition is never true the while_true statements are never executed Remember the while loop: condition while (condition) while_true_statements { } while_true_statements true Back to the program Remaining program statements false If condition is always true the while_true statements are executed forever

Are you with me? Write a piece of code that prints out the even numbers between 2 and 10.

Can we do it differently? In this last example, we knew exactly how many iterations of the loop are needed (i.e. we stopped at 10). Sometimes, we don’t know ahead of time when we’re going to stop. E.g. Situations where at the end of each loop we ask the user if they want to continue) However, for situations where we do know when we’re going to stop, we have a built in counter for the loop Java has another ‘shortcut’ form of loop syntax that handles these cases very well

The for loop The for loop is coordinated by a counter for which we need to set: An initial value A test condition (as long as the condition is true the loop will keep going) An way of updating the counter

Remaining program statements The for loop Initialize counter condition Update counter for (initialize; test; update) for_statement true for_statement { } Remaining program statements false Back to the program for(int count = 1 ; ) { //statements to be repeated (looped) } count <= 10 ; count ++

Let’s get evens Write a piece of code that prints out the even number between 2 and 10? for( { System.out.println(count) } int count = 2; count <= 10; count += 2 ) int count = 2; while (count <= 10) { System.out.println(count); count += 2; } output 2 4 6 8 10

The for loop Semantically equivalent to a while loop You can always do with a while loop what you can do with a for loop Sometimes a for loop is very awkward E.g. When no initialization needs to be done Use it when some kind of counter of the iterations is natural

Exercise Do Parts 1.1 - 1.3 of the lab All even numbers from 2 to max Sum of squares of all even numbers from 2 to max Tracing the program for max = 4 Not sure what is happening inside your loop? ***** During the debugging phase, insert print/println statements that display the current value of the counter and any other critical variable(s)

Exercise Do Part 1.4 of the lab Ask user to enter his/her name Display the characters of the name to the console window In all caps In reverse order Confused how to do this? Plan!! (Use JEnglish)

Today’s plan Midterm Primitive data type vs object variables for Loops Arrays

Lots of similar things … Create a program that asks the user to enter 5 assignment scores Print out the scores in decreasing order Calculate the average score Now… Imagine you have 40 assignment scores … or 400 assignment scores

Are you with me? Give a rough skeleton of the program Only main ingredients: type of loop, # of variables, etc. What changes for 5 vs. 400 students?

… One big container Instead of declaring 400 double variables, (firstScore, secondScore, thirdScore …) one per student Declare one Score variable with 400 designated spots. We need an array!

Pills anyone? Sun Mon Tue Wed Thu Fri Sat

Each value has a numeric index Arrays An array is an ordered list of data 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.5 87 94 82.5 67 98 87.5 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 94 79.5 87 94 82.5 67 98 87.5 81 74 91 scores[2] 0 1 2 3 4 5 6 7 8 9 The expression scores[2] refers to the number 94, the third element in the array

The 411 on Arrays An array stores multiple values. All values in the array must be of the same data-type These can be primitive types or objects We can create An array of double An array of char An array of String objects An array of Triangle objects etc… In Java, the array itself is an object Therefore the name of the array is a object reference variable, and the array itself is instantiated separately

Declaring Arrays double[] scores = new double[10]; An array of doubles is an object of the class double[] which identifies an array that can contain doubles The name I choose for my array is scores Instantiate an object of the double[] class double[] scores = new double[10]; My array will contain 10 elements. It has index from 0 to 9

Filling an array double[] scores = new double[3]; scores[0] = 70; 38.5 90

length of an array Each array object has a public constant called length that stores the size of the array E.g. scores.length length holds the number of elements In an array of 13 elements (indexed from 0 to 12), System.out.println(scores.length); would output: 13

Exercise Do Parts 2.1- 2.4 of the lab Declare and instantiate the scores array Populate the scores array using input from the user Print all scores to the console separated by commas Print the first and last score entered

Bounds checking Once an array is created, it has a fixed size (for example N). An index used in an array reference must specify a valid element: the index value must be in bounds (0 to N-1) The Java interpreter will complain if an array index is out of bounds. This is called automatic bounds checking Note: As mentioned above, the compiler will NOT complain.(ie: your program will compile. The problems is that your program may “break” crash! In many ways this is worse!! It’s much better to catch things when compiling. At least then you have a chance to fix it.

More array declarations boolean[] flags; flags = new boolean[100]; OR you could also write: boolean[] flags = new boolean[100]; String[] roster = new String[25];

Array declaration revisited The brackets of the array type can be associated with the element type or with the name of the array double[] prices; double prices[]; Preferred format

Initializer list An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: double[] units = {147, 323.2, 89.0, 933, 540.22, 269, 97.18, 114, 298.3, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

Initializer list 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 only be used at the time that you declrae the array

Exercise Do Parts 2.5 - 2.7 of the lab Calculate and display the average score Find and display highest grade and position in the array Find the lowest grade and compute a new average with the lowest grade dropped

Exercise Do Parts 2.8 - 2.9 of the lab Create a copy of the array Use the equality operator to test equality of the two arrays as objects