Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.
|
|
- Adelia Tucker
- 5 years ago
- Views:
Transcription
1 How would you solve this? Array basics Readings:. Consider the following program: How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Average temp =. days were above average. What makes the problem hard? Arrays We need each input twice to compute the average via a cumulative sum to count how many were above the average What about putting the s into variables? How many variables would we declare? Need a way to declare many variables at once. array: An object that stores many s of the same type. element: a in an array : an integer indicating the position of a in an array - - element element element Array declaration Array auto-initialization Declaring/initializing an array: <type>[] <name> = new <type>[<length>]; int[] numbers = new int[]; When arrays are initially constructed, every element is automatically initialized to a "zero-equivalent". int: double:. boolean: false object type: null (null means "no object") The length can be any integer expression: int x = * + ; int[] data = new int[x % + ];
2 Array auto-initialization: Example Assigning array elements An array of doubles... An array of booleans false false.. false false Assigning a to an array element: <array name>[<>] = <>; numbers[] = ; numbers[] = -; - Accessing array elements Don't go out of bounds! Using an array element's in an expression: <array name>[<>] Reading or writing any outside the valid range will throw an ArrayIndexOutOfBoundsException. System.out.println(numbers[]); if (numbers[] < ) { System.out.println("Element is negative."); int[] data = new int[]; System.out.println(data[]); System.out.println(data[-]); System.out.println(data[]); System.out.println(data[]); // okay // exception! // okay // exception! - Example Arrays and for loops int[] numbers = new int[]; numbers[] = ; numbers[] = ; numbers[] = ; int x = numbers[]; numbers[x] = ; numbers[numbers[]] = ; // use numbers[] as! x: numbers: Arrays are very commonly used with for loops to access each element for (int i = ; i < ; i++) { System.out.print(numbers[i] + " "); System.out.println(); // end the line of output
3 Arrays and for loops Arrays and for loops for (int i = ; i < ; i++) { numbers[i] = * i; for (int i = ; i < ; i++) { numbers[i] = i * i; What s in the array? What s in the array? The length field Example An array's length field stores its number of elements. General syntax: <array name>.length NB: Because it's a field (i.e. not a method), it does not use parentheses like a String's.length()! for (int i = ; i < numbers.length; i++) { System.out.print(numbers[i] + " "); What expression refers to the last element of an array? The middle element? How it all started Solution Solve the following problem: // This program reads several days' temperatures from the user // and computes the average and how many days were above average. import java.util.*; How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Average temp =. days were above average. public class Weather { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int days = console.nextint(); int[] temperatures = new int[days]; // array to store days' temperatures int sum = ; for (int i = ; i < days; i++) { // read/store each day's temperature System.out.print("Day " + (i + ) + "'s high temp: "); temperatures[i] = console.nextint(); sum += temperatures[i]; double average = (double) sum / days; int count = ; for (int i = ; i < days; i++) { if (temperatures[i] > average) { count++; // report results System.out.println("Average temp = " + average); System.out.println(count + " days above average"); // see if each day is above average
4 A multi-counter problem Arrays for counting / tallying Readings:. Problem: Examine a number and count the number of occurrences of every digit. The number contains: two s, one, three s, one, and one Solution? Declare counter variables one per digit. Eeewww!!!! int counter, counter, counter, counter; int counter, counter, counter, counter; int counter, counter; A multi-counter problem An array of counters Problem: Examine a number and count the number of occurrences of every digit. The number contains: two s, one, three s, one, and one Solution: Declare an array of elements the element at i will store the counter for digit i. int[] counts = new int[]; int num = ; int[] counts = new int[]; while (num > ) { int digit = num % ; counts[digit]++; num = num / ; Histogram: Exercise Histogram: Exercise Given a file of integer exam scores, such as: Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. : ***** : ************ : *** : * : **** Variations: Make a curve that adds a fixed number of points to each score. (But don't allow a curved score to exceed the max of.) Chart the data with a DrawingPanel.
5 Histogram: Solution Histogram: Solution // Reads an input file of test scores (integers) and displays a // graphical histogram of the score distribution. import java.awt.*; import java.io.*; import java.util.*; public class Histogram { public static final int CURVE = ; // adjustment to each exam score public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("midterm.txt")); int[] counts = new int[]; // counters of test scores - while (input.hasnextint()) { // read file into counts array int score = input.nextint(); score = Math.min(score + CURVE, ); // curve the exam score counts[score]++; // if score is, then counts[]++ // use a DrawingPanel to draw the histogram DrawingPanel p = new DrawingPanel(counts.length * +, ); Graphics g = p.getgraphics(); g.setcolor(color.black); for (int i = ; i < counts.length; i++) { g.drawline(i * +,, i * +, - * counts[i]); for (int i = ; i < counts.length; i++) { if (counts[i] > ) { System.out.print(i + ": "); for (int j = ; j < counts[i]; j++) { System.out.print("*"); System.out.println(); // print star histogram Why are arrays useful Array initialization statement Arrays store a large amount of data accessible from one variable. Arrays help us group related data into elements. Quick array initialization, general syntax: <type>[] <name> = {<>, <>,, <>; int[] numbers = {,, -,,,, - ; Arrays let us access data in random order. Cassette tape vs. DVD - - Useful when you know in advance what the array's element s will be. Example Printing arrays: Arrays.toString int[] a = {,,,,,, ; for (int i = ; i < a.length; i++) { a[i] += a[i - ]; What s in the array? Arrays.toString accepts an array as a parameter and returns the String representation, which you can then print. int[] a = {,,,,,, ; for (int i = ; i < a.length; i++) { a[i] += a[i - ]; System.out.println("a is " + Arrays.toString(a)); a is [,,,,,, ]
6 Array traversal Traversal algorithms Readings:. traversal: An examination of each element of an array. Traversal algorithms often takes the following form: for (int i = ; i < <array>.length; i++) { do something with <array>[i]; Examples: printing out the elements searching for a specific rearranging the elements computing a based on the elements Printing array elements Searching an array int[] list = {,,, ; for (int i = ; i < list.length; i++) { System.out.println(i + ": " + list[i]); : : : : int[] list = {,,,,,,,,, ; int largesteven = ; for (int i = ; i < list.length; i++) { if (list[i] % == && list[i] > largesteven) { largesteven = list[i]; System.out.println("Largest even: " + largesteven); Largest even: What assumptions does this code make? String traversal String traversal: Example Strings are represented internally as arrays of chars. 'l' 'e' 't' 't' 'e' 'r' We can write algorithms to traverse strings to compute information. What useful information might the following string have? "BDRBRRBDRRBDMBDBRRRBRBRBBDBDDRDDRRDBDBBD" 's' // string stores voters' votes // (R)EPUBLICAN, (D)EMOCRAT, (B)ENSON, (M)ARTY String votes = "BDRBRRBDRRBDMBDBRRRBRBRBBDBDDRDDRRDBDBBD"; int[] counts = new int[]; // R ->, D ->, B ->, M -> for (int i = ; i < votes.length(); i++) { char c = votes.charat(i); if (c == 'R') { counts[]++; else if (c == 'D') { counts[]++; else if (c == 'B') { counts[]++; else { // c == 'M' counts[]++; System.out.println(Arrays.toString(counts)); [,,, ]
7 Example data: Section attendance Data transformations Consider the following dataset which represents attendance for three sections of five students: week week week week week week week week week Sometimes we will use data in one form to compute new data in another form. Often each transformation is stored into its own array. Transformations require a mapping between the original data and array indices. student student student student student Typical mappings Exercise: Section attendance Tally If the input is the integer i, do something with array i. Based on the position in the data Store the i th we read into i. Explicit mappings Count occurrences of 'R' into and occurrences of 'D' into. Write a program that reads the preceding section data file and produces output such as the following: Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Solution: Section attendance Solution: Section attendance // This program reads a file representing which students attended // which discussion sections and produces output of the students' // section attendance and scores. import java.io.*; import java.util.*; public class Sections { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); int section = ; // used to count sections while (input.hasnextline()) { String line = input.nextline(); processsection(section, line); section++; // one section's data public static void processsection(int sectionnum, String line) { System.out.println("Section #" + sectionnum + ":"); int[] attended = new int[]; // count sections attended for (int i = ; i < line.length(); i++) { char c = line.charat(i); if (c == '') { // student attended section attended[i % ]++; System.out.println("Sections attended: " + Arrays.toString(attended));
8 Solution: Section attendance // compute section score out of points int[] scores = new int[]; for (int i = ; i < scores.length; i++) { scores[i] = Math.min( * attended[i], ); System.out.println("Student scores: " + Arrays.toString(scores)); Arrays and methods // compute section grade out of % double[] grades = new double[]; for (int i = ; i < scores.length; i++) { grades[i] =. * scores[i] / ; System.out.println("Student grades: " + Arrays.toString(grades)); System.out.println(); Readings:. Arrays as parameters Arrays as parameters Declaration, syntax: public static <type> <name>(<type>[] <name>) { public static double average(int[] numbers) { Method call, syntax: <method name>(<array name>); int[] scores = {,,,, ; double avg = average(scores); public static void main(string[] args) { int[] iq = {,, ; System.out.println("Max = " + max(iq)); public static int max(int[] array) { int largest = array[]; for (int i = ; i < array.length; i++) { if (array[i] > largest) { largest = array[i]; return largest; Max = Arrays as parameters Arrays as parameters Unlike primitive types, when arrays are passed as parameters, changes made to the array elements in the called method will be visible in the calling method. public static void main(string[] args) { int[] iq = {,, ; System.out.println(Arrays.toString(iq)); doubleall(iq); System.out.println(Arrays.toString(iq)); public static void doubleall(int[] array) { for (int i = ; i < array.length; i++) { array[i] *= ; [,, ] [,, ] public static void main(string[] args) { int[] iq = {,, ; System.out.println(Arrays.toString(iq)); doubleall(iq); System.out.println(Arrays.toString(iq)); public static void doubleall(int[] array) { for (int i = ; i < array.length; i++) { array[i] *= ; [,, ] [,, ] array: iq:
9 Useful result: Output parameter Output parameter output parameter: An object passed as a parameter that has its contents altered by the method. We can pass an array to a method and the method can change its contents in useful ways. After calling Arrays.sort(<array>), the array passed in will be in sorted order. int[] nums = {, -,,,, ; System.out.println(Arrays.toString(nums)); Arrays.sort(nums); System.out.println(Arrays.toString(nums)); [, -,,,, ] [-,,,,, ] Arrays as return s Arrays as return s Declaration, syntax: public static <type>[] <name>(<parameters>) { public static int[] readallnumbers(scanner input) { Method call, syntax: <type>[] <name> = <method name>(<parameters>); Scanner filescan = new Scanner(new File("nums.txt")); int[] numbers = readallnumbers(filescan); public static int[] countdigits(int n) { int[] counts = new int[]; while (n > ) { int digit = n % ; n = n / ; counts[digit]++; return counts; public static void main(string[] args) { int[] tally = countdigits(); System.out.println(Arrays.toString(tally)); [,,,,,,,,, ] Exercises Solutions Write a method named average that accepts an array of integers and returns the average of the s in the array. Write a method named contains that accepts an array of integers and a target integer and returns whether the array contains the target. Write a method named roundall that accepts an array of doubles and modifies each element of the array so that it is rounded to the nearest whole number. public static double average(int[] numbers) { int sum = ; for (int i = ; i < numbers.length; i++) { sum += numbers[i]; return (double) sum / numbers.length; public static boolean contains(int[] s, int target) { for (int i = ; i < s.length; i++) { if (s[i] == target) { return true; return false; public static void roundall(double[] array) { for (int i = ; i < array.length; i++) { array[i] = Math.round(array[i]);
10 Exercise Solution Modify our previous Sections program to use methods for structure. Pass arrays as parameters and return. Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] // This program reads a file representing which students attended // which discussion sections and produces output of the students' // section attendance and scores. // This version uses methods for structure. import java.io.*; import java.util.*; public class Sections { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); while (input.hasnextline()) { // process one section String line = input.nextline(); int[] attended = countattended(line); int[] points = computepoints(attended); double[] grades = computegrades(points); results(attended, points, grades); Solution Solution // Counts the sections attended by each student for one section. public static int[] countattended(string line) { int[] attended = new int[]; for (int i = ; i < line.length(); i++) { char c = line.charat(i); // c == '' or c == '' if (c == '') { // student attended their section attended[i % ]++; return attended; // Computes the points earned for each student for one section. public static int[] computepoints(int[] attended) { int[] points = new int[]; for (int i = ; i < attended.length; i++) { points[i] = Math.min(, * attended[i]); return points; // Computes the percentage for each student for one section. public static double[] computegrades(int[] points) { double[] grades = new double[]; for (int i = ; i < points.length; i++) { grades[i] =. * points[i] /.; return grades; // Produces all output about one section. public static void results(int[] attended, int[] points, double[] grades) { System.out.println("Sections attended: " + Arrays.toString(attended)); System.out.println("Sections scores: " + Arrays.toString(points)); System.out.println("Sections grades: " + Arrays.toString(grades)); System.out.println();
Array basics. Readings: 7.1
Array basics Readings: 7.1 1 How would you solve this? Consider the following program: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp:
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.6, 4.3 A multi-counter problem Problem: Write a method mostfrequentdigit that returns the digit value that
More informationBuilding Java Programs Chapter 7
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson 2013. All rights reserved. Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Section attendance question Write a program that reads
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Section attendance question Write a program that reads
More informationTopic 23 arrays - part 3 (tallying, text processing)
Topic 23 arrays - part 3 (tallying, text processing) "42 million of anything is a lot." -Doug Burger (commenting on the number of transistors in the Pentium IV processor) Copyright Pearson Education, 2010
More informationBuilding Java Programs
Building Java Programs Chapter 7 Arrays reading: 7.1 2 Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp:
More informationArrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals
Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Can we solve this problem? Consider the following program
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationBuilding Java Programs
Building Java Programs Chapter 7: Arrays Lecture 7-3: More text processing, file output 1 Remember: charat method Strings are internally represented as char arrays String traversals are a common form of
More informationTopic 21 arrays - part 1
Topic 21 arrays - part 1 "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. " - Stan Kelly-Bootle Copyright Pearson Education, 2010 Based
More informationAP Computer Science. Arrays. Copyright 2010 by Pearson Education
AP Computer Science Arrays Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39
More informationarrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.
Topic 21 https://commons.wikimedia.org/w/index.php?curid=66702 arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether,
More informationBuilding Java Programs
Building Java Programs Chapter 6: File Processing Lecture 6-2: Advanced file input reading: 6.3-6.5 self-check: #7-11 exercises: #1-4, 8-11 Copyright 2009 by Pearson Education Hours question Given a file
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationLecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.
Lecture 9: Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Can we solve this problem? Consider the following program
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: 6.4-6.5, 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Two separate topics File output A lot like printing
More informationCSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp
CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp http://www.cs.washington.edu/143/ Arrays (7.1) array: An object that stores many values of the same type. element: One value in an array.
More informationAdmin. CS 112 Introduction to Programming. Recap: Arrays. Arrays class. Array Return (call) Array Return (declare) q Exam 1 Max: 50 Avg/median: 32
Admin 100# 95# 90# 85# 80# CS 112 Introduction to Programming q Exam 1 Max: 50 Avg/median: 32 75# 70# 65# 60# 55# 50# 45# 40# 35# 30# 25# Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin. q Puzzle Day
More informationAdmin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements
Admin. CS 112 Introduction to Programming q Puzzle Day from Friday to Monday Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:
More informationComputer Science is...
Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic
More informationObject Oriented Programming. Java-Lecture 6 - Arrays
Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types
More informationArrays in Java Using Arrays
Recall Length of an Array Arrays in Java Using Arrays Once an array has been created in memory, its size is fixed for the duration of its existence. Every array object has a length field whose value can
More informationTopic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Swapping values public static void main(string[] args)
More informationBuilding Java Programs
Building Java Programs Chapter 4: Conditional Execution 1 loop techniques cumulative sum fencepost loops conditional execution Chapter outline the if statement and the if/else statement relational expressions
More informationwhile (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */
import java.util.scanner; public class CourseManager1 { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter number of students: "); /* read the number
More informationChapter 4: Control Structures I
Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #07: September 21, 2015 1/30 We explained last time that an array is an ordered list of values. Each value is stored at a specific, numbered position in
More informationComputer Programming, I. Laboratory Manual. Experiment #6. Loops
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #6
More informationArrays and Lists CSC 121 Fall 2016 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationArrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:
Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types: int, short, byte, long, float, double, boolean, char The data
More information! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like
Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is
More informationLoops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG
Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive
More informationChapter 8 Multi-Dimensional Arrays
Chapter 8 Multi-Dimensional Arrays 1 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections of elements. myarray: 6 4 1 9 7 3 2 8 Now think
More information1. An operation in which an overall value is computed incrementally, often using a loop.
Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More information1 Short Answer (10 Points Each)
1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationMotivation of Loops. Loops. The for Loop (1) Learning Outcomes
Motivation of Loops Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print the Hello World message
More informationLoops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 6 Loops
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignment Class Exercise 19 is assigned Homework 8 is assigned Both Homework 8 and Exercise 19 are
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays
WIT COMP1000 Arrays Arrays An array is a list of variables of the same type, that represents a set of related values For example, say you need to keep track of the cost of 1000 items You could declare
More informationChapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey
Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What
More informationLecture 10: Arrays II
Lecture 10: Arrays II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Largest Value Given an array, return the largest
More informationArrays and Lists CSC 121 Fall 2015 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationArrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal
Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review
More informationQ5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter.
Q1. Which of the following choices is the correct syntax for declaring/initializing an array of integers? 1. int[] a = new int[10]; 2. int a[10] = new int[10]; 3. []int a = [10]int; 4. int a[10]; 5. int[10]
More informationLoops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG
Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for
More informationLast Class. More on loops break continue A bit on arrays
Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };
More informationWeb-CAT submission URL: CAT.woa/wa/assignments/eclipse
King Saud University College of Computer & Information Science CSC111 Lab10 Arrays II All Sections ------------------------------------------------------------------- Instructions Web-CAT submission URL:
More informationCS 106A, Lecture 16 Arrays
CS 106A, Lecture 16 Arrays suggested reading: Java Ch. 11.1-11.5 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights
More informationLast Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it
Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]
More informationArrays and Lists CSC 121 Fall 2014 Howard Rosenthal
Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods
More informationReview pages for the AP CS Exam
Review pages for the AP CS Exam NOTE: Sections that are not considered part of the Java Subset for the AP CS exam are not included in these pages, for example Scanners. Taken from the UW 143 Review Building
More informationArrays. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays
More informationExam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:
كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this
More informationFundamentals of Programming Data Types & Methods
Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationMotivation of Loops. Loops. The for Loop (1) Learning Outcomes
Motivation of Loops Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Program Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q PS5 Walkthrough Thursday
More informationCAT.woa/wa/assignments/eclipse
King Saud University College of Computer & Information Science CSC111 Lab10 Arrays II All Sections ------------------------------------------------------------------- Instructions Web-CAT submission URL:
More informationModule 7: Arrays (Single Dimensional)
Module 7: Arrays (Single Dimensional) Objectives To describe why arrays are necessary in programming ( 7.1). To declare array reference variables and create arrays ( 7.2.1 7.2.2). To obtain array size
More informationNoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.
CSC116 Practice Exam 2 - KEY Part I: Vocabulary (10 points) Write the terms defined by the statements below. Cumulative Algorithm 1. An operation in which an overall value is computed incrementally, often
More informationChapter 7: Arrays and the ArrayList Class
Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 7 discusses the following main topics: Introduction
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 The if/else statement Executes one block if a test is true,
More informationCSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:
CSE 20 SAMPLE FINAL Version A Time: 180 minutes Name The following precedence table is provided for your use: Precedence of Operators ( ) - (unary),!, ++, -- *, /, % +, - (binary) = = =,!= &&
More informationExample: Computing prime numbers
Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will
More informationSample Midterm Exam #2
Sample Midterm Exam #2 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for
More informationBuilding Java Programs
Building Java Programs Chapter 8 Lecture 8-1: Classes and Objects reading: 8.1-8.3 self-checks: #1-9 exercises: #1-4 A programming problem Given a file of cities' (x, y) coordinates, which begins with
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009
More informationFirst Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010
First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010 NAME (Printed) NAME (Signed) E-mail Exam Rules Show all your work. Your grade will be
More informationLiang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
1 Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes
More informationCOMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz
COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz The in-class quiz is intended to give you a taste of the midterm, give you some early feedback about
More informationBuilding Java Programs
Building Java Programs Chapter 6: File Processing 1 Lecture outline line-based file processing using Scanners processing a file line by line mixing line-based and token-based file processing searching
More information1 Short Answer (10 Points Each)
1 Short Answer (10 Points Each) 1. For the following one-dimensional array, show the final array state after each pass of the three sorting algorithms. That is, after each iteration of the outside loop
More informationChapter 8 Multidimensional Arrays
Chapter 8 Multidimensional Arrays 8.1 Introduction Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a
More informationCSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges)
CSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges) 1. Expressions For each expression at left, indicate its value in the right column. List a value of appropriate type
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Arrays A data structure for a collection of data that is all of the same data type. The data type can be
More informationMethod OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper
More informationFinal Exam. COMP Summer I June 26, points
Final Exam COMP 14-090 Summer I 2000 June 26, 2000 200 points 1. Closed book and closed notes. No outside material allowed. 2. Write all answers on the test itself. Do not write any answers in a blue book
More informationCSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score
CSC 1051 Algorithms and Data Structures I Final Examination May 12, 2017 Name: KEY Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces
More informationBuilding Java Programs
Building Java Programs Chapter 16 References and linked nodes reading: 16.1 2 Value semantics value semantics: Behavior where values are copied when assigned, passed as parameters, or returned. All primitive
More informationSPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each
Your Name: Your Pitt (mail NOT peoplesoft) ID: Part Question/s Points available Rubric Your Score A 1-6 6 1 pt each B 7-12 6 1 pt each C 13-16 4 1 pt each D 17-19 5 1 or 2 pts each E 20-23 5 1 or 2 pts
More informationTopic 12 more if/else, cumulative algorithms, printf
Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly
More informationCOMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.
More informationSequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationCSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011
CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011 Name: Section: Student ID #: TA: You have 50 minutes to complete this exam. You may receive a deduction if you keep working after the instructor
More informationChoose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.
Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Use the remaining question as extra credit (worth 1/2 of the points earned). Specify which question is
More informationArrays Chris Piech CS106A, Stanford University
Arrays Chris Piech CS106A, Stanford University What does this say? 53 305))6*;4826)4 )4 );806*;48 8 60))85;1 (;: *8 83(88)5* ;46(;88*96*?;8)* (;485);5* 2:* (;4956*2(5* 4)8 8*;4069285);)6 8)4 ;1( 9;48081;8:8
More informationCS115 Principles of Computer Science
CS5 Principles of Computer Science Chapter Arrays Prof. Joe X. Zhou Department of Computer Science CS5 Arrays. Re: Objectives in Methods To declare methods, invoke methods, and pass arguments to a method
More informationCS 1083 Introduction to Programming I for Computer Scientists Final Solutions
CS 1083 Introduction to Programming I for Computer Scientists Final Solutions Question Question 1 Question 2 Question 3 Question 4 Question 5 Question 6 Question 7 Question 8 Total Points NAME: Instructions
More information(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution
Ch 5 Arrays Multiple Choice Test 01. An array is a ** (A) data structure with one, or more, elements of the same type. (B) data structure with LIFO access. (C) data structure, which allows transfer between
More informationChapter 2: Basic Elements of Java
Chapter 2: Basic Elements of Java TRUE/FALSE 1. The pair of characters // is used for single line comments. ANS: T PTS: 1 REF: 29 2. The == characters are a special symbol in Java. ANS: T PTS: 1 REF: 30
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More information