Docsity

CMPSCI 121 Spring 2009: Array Manipulations and Swapping Values - Prof. Erik Learned-Mille, Study notes of Computer Science

Partial preview of the text

Download CMPSCI 121 Spring 2009: Array Manipulations and Swapping Values - Prof. Erik Learned-Mille and more Study notes Computer Science in PDF only on Docsity!

Arrays..continued

March 26, 2009

CMPSCI 121, Spring 2009

Introduction to Problem Solving with Computers Prof. Learned-Miller

Logistics

 Snake game, part 1, due next

Wednesday.

 Due on same day!! (in about 2 weeks):

 Snake game, part 2

 Anagram

Using array elements in for

loops

 for (int i : bunchOfInts) {

System.out.println(i);

 for (Car c: carArray) {

c.printMiles();

Initializing int arrays

 int [] x={1,2,7,12,3,4,2};

 int [] x=new int[7];

 x[0]=1;

 x[1]=2;

 x[2]=7;

 x[3]=12;

Swapping Values

 int x = 3;

 int y = 5;

 How to swap values of x and y?

 y=x; // After this, x == 3, y == 3.

 x=y; // After this, x == 3, y == 3.

 // This is the wrong result!

Swapping Values

 int x = 3;

 int y = 5;

 How to swap values of x and y?

 int temp = y; // temp==5, x==3, y==5.

 y = x; // temp==5, x==3, y==3.

 x = temp; // temp==5, x==5, y==3.

 // The correct result!

Solution

Starting point 3 8 2 7 Goal Temporary variable “workspace” array temp array

Solution

Starting point 3 8 2 7 Goal Temporary variable “workspace” array temp array

Solution

Starting point 3 8 2 7 Goal 3 8 2 7 array temp array array 3 8 2 7

Solution

“Workspace solution”