Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 211 Java I for loops and arrays.

Similar presentations


Presentation on theme: "CSC 211 Java I for loops and arrays."— Presentation transcript:

1 CSC 211 Java I for loops and arrays

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

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

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

5 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

6 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.

7 ** 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

8 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;

9 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);

10 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?

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

12 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

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

14 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

15 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

16 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 ++

17 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

18 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

19 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)

20 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)

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

22 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

23 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?

24 … 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!

25 Pills anyone? Sun Mon Tue Wed Thu Fri Sat

26 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 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

27 Arrays A particular value in an array is referenced using the array name followed by the index in brackets 94 scores[2] The expression scores[2] refers to the number 94, the third element in the array

28 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

29 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

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

31 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

32 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

33 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.

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

35 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

36 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, , 269, 97.18, 114, 298.3, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

37 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

38 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

39 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


Download ppt "CSC 211 Java I for loops and arrays."

Similar presentations


Ads by Google