04-arrayintlist

# 04-arrayintlist - CSE143 Lecture4 http/www.cs.washington.edu/143 Exercise (ofunknownsize)fullof occurredinthefile.

This preview shows pages 1–5. Sign up to view the full content.

CSE 143 Lecture 4 Implementing  ArrayIntList slides created by Marty Stepp http://www.cs.washington.edu/143/

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Exercise Write a program that reads a file (of unknown size) full of  integers and prints the integers in the reverse order to how they  occurred in the file.  Consider example file  data.txt : 17 932085 -32053278 100 3 When run with this file, your program's output would be: 3 100 -32053278 932085 17
3 Solution using arrays int[] nums = new int[100]; // make a really big array int size = 0; Scanner input = new Scanner(new File("data.txt")); while (input.hasNextInt()) { nums[size] = input.nextInt(); // read each number size++; // into the array } for (int i = size - 1; i >= 0; i--) { System.out.println( nums[i] ); // print reversed } index 0 1 2 3 4 5 6 ... 98 99 value 17 93208 5 - 32053278 10 0 3 0 0 ... 0 0 size 5

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 Unfilled arrays int[] nums = new int[100]; int size = 0; We often need to store an unknown number of values. Arrays can be used for this, but we must count the values. Only the values at indexes [0,  size  - 1] are relevant. We are using an array to store a
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/04/2011 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

### Page1 / 16

04-arrayintlist - CSE143 Lecture4 http/www.cs.washington.edu/143 Exercise (ofunknownsize)fullof occurredinthefile.

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online