CS0007: Introduction to Computer Programming Introduction to Arrays.

Slides:



Advertisements
Similar presentations
Chapter 8: Arrays.
Advertisements

CS0007: Introduction to Computer Programming Arrays: Higher Dimensional Arrays.
CS0007: Introduction to Computer Programming
Arrays.
CS0004: Introduction to Programming Repetition – Do Loops.
Chapter 10 Introduction to Arrays
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Repeating Actions While and For Loops
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Chapter 5: Loops and Files.
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.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
The switch Statement, DecimalFormat, and Introduction to Looping
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Iterative Constructs Review l What are named constants? Why are they needed? l What is a block? What is special about declaring a variable inside a block?
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
BIT115: Introduction to Programming
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];
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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 9 Introduction to Arrays Fundamentals of Java.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Sections 10.1 – 10.4 Introduction to Arrays
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
The switch Statement, and Introduction to Looping
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Arrays, For loop While loop Do while loop
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.
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

CS0007: Introduction to Computer Programming Introduction to Arrays

Review A Conditionally-Controlled Loop repeats… as long as a particular condition exists. A Count-Controlled Loop repeats… a specific number of times. A count-controlled loop has three elements An initialization expression A test expression An update expression The difference between the prefix and postfix increment operators is… pretest increments before the value of the operand is evaluated, posttest increments after the value of the operand is evaluated.

Review An accumulator variable is… a variable that keeps track of a running total. A Sentinel Value is… a special value that cannot be mistaken for normal input that signals that a loop should terminate. break in a loop… makes the program’s control flow go to the statement following the loop. continue in a loop… skips to the next iteration of the loop. Java provides a class that generates pseudo-random numbers called… Random

Arrays So far we have worked primarily with primitive variables One characteristic of primitive variables is that they hold one value at a time. int x = 100 – can only hold one integer value at a time (100 at this time) Imagine that you want to hold the names of 100 people at a time. What would you have to do? Declare 100 variables, one for each name. Better solution: Use Arrays. Arrays are complex variables that can hold multiple values of the same data type. Now we can declare a single array that holds all the names. In Java, Arrays are objects and behave very similarly (use new keyword to create the object, has methods, etc.)

Arrays To declare an integer array: int[] numbers; It is just like declaring any primitive variable, EXCEPT for the [] between the data type and the identifier. Just like any other object, this does not create the array, it creates a reference variable that can point to an array. To create an array object for this reference variable: numbers = new int[6]; The number inside of the square brackets is called the array’s size declarator. An array’s Size Declarator indicates the number of elements, or values the array can hold. Individual values inside of an array are called elements. So the numbers array can hold 6 integers. You can declare and create on the same line like any other object: int[] numbers = new int [6];

Arrays The elements in an array are numbered starting from 0. So the first element has index 0. The size declarator must be a non-negative integer expression. Often cases we know the size of the array when writing the code and can just use a literal. However, it is common practice to use a constant as the size declarator. final int NUM_ELEMENTS = 6; double[] numbers = new double [NUM_ELEMENTS]; Once an array is created the size cannot change! Arrays can be of any type we discussed up to this point.

Accessing Array Elements Even though, the array has one name, we can access the individual elements by their index (or subscript). An element’s Index (or Subscript) is a uniquely identifying number that is used to pinpoint its position in the array. So, if I want a specific element, I use its index. Again, indices start at 0. When you access an element in the array, you can use it just like any simple variable of the array’s declared type. The following statement assigns 20 to the first element in the numbers array: numbers[0] = 20; To access an element of an array, simply use the array name followed by the element’s index inside of square brackets.

Array Example 1 New Topics: Arrays

Array Example 2 This seems repetitive… I have to use a separate segment of code for taking in the employees hours and for printing the result out. Is there a better way? Answer: Yes, using loops. Arrays work great with loops, because you can loop through the elements of the array and perform operations on them. New Topic: Looping through arrays

Bounds Checking and Off-by-One Errors What is the problem with this? int[] numbers = new int [3]; numbers[5] = 10; Answer: The index 5 is out of the bounds defined by the size declarator. Java performs bounds checking at runtime. In the case with Java that means that if you attempt to index an element outside of the array’s bounds, it will throw an exception (cause an error and terminate your program). We will not discuss exceptions in this course. What is the problem with this? int[] numbers = new int [3]; numbers[3] = 10; Answer: The index 3 is still out of the array’s bounds. Because indexing starts at 0, the last element of the array is the size of the array minus 1. This is called an Off-by-One error.

Array Declaration Notes You can initialize Arrays just like any other variables. int[] numbers = {1, 2, 3, 4, 5}; This array has an implicit size of 5 and the values in the initialization are indexed from left to right. Example: ArrayInitialization.java Java also allows for two different syntactical forms for declaring an array: int[] numbers; int numbers[]; The difference is when you declare multiple arrays on the same line: int[] numbers1, numbers2, numbers3; This declares three reference variables to integer arrays int numbers1[], numbers2, numbers3; This declares one reference variable to an integer array and two primitive integer variables int numbers1[], numbers2[], numbers3[]; This, again, declares three reference variables to integer arrays

Array Elements Individual array elements can be treated like any simple variable of that type. int[] numbers = new int[5]; int x = 5; numbers[1] = x + 5; x = numbers[1] + 20; numbers[2] = numbers[1] / 5; numbers[2]++; Also, since arrays are objects in Java, they have methods and data members. For instance the length data member holds the number of elements in the array. int size = numbers.length; This is helpful for looping through an array.

Enhanced for Loop The last kind of loop we will be discussing in this course is called the enhanced for loop. The Enhanced for Loop is a special loop that iterates through the elements in a collection (in this case array) and allows access to each element. Each iteration of the loop corresponds to an element in the array. General Form: for(dataType elementVariable : array) block or statement dataType – The type of the array elementVariable – A variable that holds the value of the current iteration’s element. array – The array in which we are iterating through.

Enhanced for Loop Example New Topics: Enhanced for Loop

When NOT To Use the Enhanced for Loop The enhanced for loop is useful for when you need only all the values of the array, but there are many situations when you should NOT use it: 1. If you need to change the contents of an array element 2. If you need to work through the array elements in reverse order 3. If you need to access some of the array elements, but not all of them 4. If you need to simultaneously work with two or more arrays within the loop 5. If you need to refer to the index of a particular element If any of these cases apply, use a regular for loop.

Allowing the User to Specify an Array’s Size Since the size declarator is an integer, you can let the user enter an integer, and then create an array of that size. Example: UserSizeArray.java

Reassigning Reference Variables and Array Copying As stated before, you cannot change the size of an array once it has been set. You can, however, make the reference variable point to a new array. int[] numbers = {1, 2, 3, 4, 5}; numbers = new int [10]; What is the problem with this? Now numbers has no values in it! What you need to do is copy the elements of the old array to the new one, and make the original reference variable point to the new array: 1. Create a new reference variable 2. Make the new reference variable point to an array of the newly specified size 3. Use a loop to assign the elements from the old array to the new one. 4. Assign the new reference variable to the old one.

Array Copying Example New Topics: Array Copying