loops revisited I/O arrays

Slides:



Advertisements
Similar presentations
CS100A, Fall 1997, Lecture 111 CS100A, Fall 1997 Lecture 11, Tuesday, 7 October Introduction to Arrays Concepts: Array declaration and allocation Subscripting.
Advertisements

Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
CS 100Lecture 41 CS100J Lecture 4 n Previous Lecture –Programming Concepts n iteration n programming patterns (templates) –Java Constructs n while-statements.
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.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
CS100A, Fall 1997, Lecture 91 CS100A, Fall 1997 Lecture 9, Tuesday, 30 September Input/Output & Program Schema System.in, class Text, Some basic data processing,
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
CS 100Lecture 21 CS100J: Lecture 2 n Previous Lecture –Programming Concepts n problem, algorithm, program, computer, input, output, sequential execution,
CPSC 233 Tutorial 5 February 2 th /3 th, Java Loop Statements A portion of a program that repeats a statement or a group of statements is called.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Midterm preview.
Chapter Topics Chapter 16 discusses the following main topics:
Introduction to Arrays
Chapter 7 User-Defined Methods.
Repetition (While-Loop) version]
Chapter 5 - Control Structures: Part 2
Lecture 13: More Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Chapter 12 Variables and Operators
Chapter 5: Control Structures II
Repetition-Counter control Loop
Counted Loops.
C++ Arrays.
CSC 142 Computer Science II
Looping.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
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
One-Dimensional Array Introduction Lesson xx
CSE 143 Lecture 5 More Stacks and Queues; Complexity (Big-Oh)
Java Language Basics.
Java Programming Loops
Arrays in Java What, why and how Copyright Curt Hill.
Coding Concepts (Basics)
Algorithm Discovery and Design
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CS100J Lecture 11 Previous Lecture This Lecture
Chapter 7 The Java Array Object © Rick Mercer.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Building Java Programs
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Announcements Lab 6 was due today Lab 7 assigned this Friday
Loops.
Building Java Programs
CSC 142 Arrays [Reading: chapter 12].
Arrays in Java.
Java Programming Loops
Building Java Programs
Introduction to Arrays
Building Java Programs
Computing Spans Given an an array X, the span S[i] of X[i] is
Repetition Statements
Building Java Programs
Building Java Programs
Question 1a) What is printed by the following Java program? int s;
Review of Previous Lesson
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CS100A Sections Dec Loop Invariant Review C Review and Example
Corresponds with Chapter 5
CS100A Lect. 12, 8 Oct More About Arrays
CS100A Lect. 10, 1 Oct Input/Output & Program Schema
Presentation transcript:

loops revisited I/O arrays Oct 6-7 loops revisited I/O arrays

Loops: #1 Write a program to calculate and print the average of all the multiples of 3 from 3 up to (and including) 33333. Invariant: s contains 3 + 6 + 9 + ... + i and i is a multiple of 3 c is the number of values that have been summed in s Initalization: i= 3; s= 3; c= 1; Stopping condition: when i = 33333 So, continue while i != 33333 Body: make progress i= i+3; maintain invariant s= s+i; c= c+1;

public static void main (String[] args) { int i= 3; int s= 3; int c= 1; // invariant: ... while (i != 33333) { i= i+3; s= s+i; c= c+1; } System.out.println("average = " + s/c);

Loops: #2 Read in a sequence of positive integers (followed by a 0) and print the biggest together with its frequency of occurrence. Invariant: x the last number read max the largest value read in so far freq the number of times max has appeared

Basic input class import java.io.*; public static void main (String args[]) { int a; // initialize TokenReader object in to read // from standard input. TokenReader in = new TokenReader(System.in); // Read one number into a System.out.print("Please enter an integer: "); System.out.flush( ); a = in.readInt( ); System.out.println(“a: ’’ + a); }

Some input methods // read and return a value of type int public int readInt( ) // read and return a value of type double public double readDouble( ) // read and return a value of class String public String readString( ) // Skip the rest of the input line and return as a string // all the characters on the next line public String readLine( )

import java.io.*; public static void main (String args[]) { // initialize TokenReader object in to read from standard input. TokenReader in = new TokenReader(System.in); int max = 0; //maximum integer read in so far int freq = 0; //frequency of max // read in integers until a 0 int x = in.readInt(); while (x != 0) { if (x > max) { //x is a new max value max = x; freq = 1; } else if (x == max) //x is the same as the current max value freq = freq + 1; x = in.readInt(); //read in next value from standard input

Array Rules When an array is allocated int[ ] A = new int[size]; size may be any integer expression. When using A[exp] to refer to an element, the subscript exp may be any integer expression. The elements in an array are numbered A[0], A[1], …, A[size-1], where size is the number of elements in the array. In a reference to an array element A[exp], it is an error if exp<0 or exp=size. Be sure to be careful to distinguish the subscript (or location) of an array element from the data that is actually stored in that location.

Arrays: #1 Write a program that takes an array x[] of double's (assume that it is already initialized) and create a new array s of the same length such that s[i] is the average of x[i] and its circular neighbors: For j in the range 0 <= j < x.length-1, we say x[j+1] is the neighbor to the right of x[j]. For j in the range 0 < j <= x.length-1, we say x[j-1] is the neighbor to the left of x[j]. We say x[0] is the neighbor to the right of x[x.length-1], and x[x.length-1] is the neighbor to the right of x[0]. (This is the circular part of "circular neighbors": think of joining the ends of x[] together, forming a circle, making the original ends into neighbors.) For example, here are some values for x and the corresponding outcomes s: x = [] --> s = [] x = [2] --> s = [2] since (2+2+2)/3 = 2 x = [0 9] --> s = [6 3] since (9+0+9)/3 = 6 and (0+9+0)/3 = 3

… //code here initializes x int n = x.length; double[] s = new double[n]; int i = 0; // invariant: 0 <= i <= n = x.length, // s[0..i-1] has been computed, // and s[i..n-1] remains to be done while (i < n) { int left = i-1; int right = i+1; if (left < 0) left = n-1; if (right == n) right = 0; s[i] = (x[left] + x[i] + x[right]) / 3.0; i = i+1; } ...

… // code here initializes x int n = x.length(); double[] s = new double[n]; int i = 0; // invariant: 0 <= i <= n = x.length, // s[0..i-1] has been computed, // and s[i..n-1] remains to be done while (i < n) { s[i] = (x[(i-1+n) % n] + x[i] + x[(i+1) % n]) / 3.0; i = i+1; } … This solution uses the remainder operation % to “wrap” values. We use (i-1+n) % n instead of just (i-1) % n to be safe: in Java, % can/will return negative values if given negative dividends.

Arrays: #2 // Move top card k[0] down into position j, // thereby pushing cards k[1..j] into positions 0..j-1 public static void cycleTopDown(int[] k, int j) { int top = k[0]; int i = 0; // invariant: 0 <= i <= j, and k[1..i] has been moved to k[0..i-1] while (i < j) { k[i] = k[i+1]; i = i+1; } k[j] = top; // Create an array k[] and // repeatedly cycle k[0] down into position k[0] until k[0] is 0 public static void topCycles () { int[] k = {2, 4, 3, 1, 0}; // Repeatedly cycle k[0] into position k[0] until k[0] is 0 while (k[0] != 0) cycleTopDown(k, k[0]);

Carefully trace a call to topCycles(): a) Show EVERY step -- ALL of them -- until one iteration of the loop in topCycles has completed. Remember to trace execution of the statements within method calls. You will have to draw diagrams showing the state of affairs at about 10 places. Do not worry about where to place a frame for a method- call. Place all frames outside of all other boxes. b) Show us the contents of k[] after each iteration of the loop in topCycles (there are at most 7 iterations).

Solution (w/o the trace) Here are the contents of k after each iteration of the loop in topCycles (we include the contents before entering the loop): 0 1 2 3 4 <- positions - - - - - 2 4 3 1 0 <- contents 4 3 2 1 0 3 2 1 0 4 2 1 0 3 4 1 0 2 3 4 0 1 2 3 4