Exercise 4: Loops, Arrays and Files

Size: px
Start display at page:

Download "Exercise 4: Loops, Arrays and Files"

Transcription

1 Exercise 4: Loops, Arrays and Files worth 24% of the final mark November 4, 2004 Instructions Submit your programs in a floppy disk. Deliver the disk to Michele Zito at the 12noon lecture on Tuesday November 24th. A submission not containing all required programs in electronic form will be penalised. Each program should be submitted in a separate text file (extension.java). Such file should contain an initial part (commented) with the analysis, comments on the solution strategy, data dictionary. 1 Exercise 1 DO NOT SUBMIT ANY WORD DOCUMENT! A matrix is a rectangular bi-dimensional array. Here is an example This is declared in Java as follows int [][] A = new int[3][4]; and then filled with the appropriate input statements (as described in the lectures). Matrices are very important in computer graphics applications. Several operations can be performed on matrices. Complete the following programming tasks (assume the elements of the matrices are integer numbers): 1. Write a program that, given a matrix A, defines another matrix B with the same number of rows and columns of A. The matrix B will have all the elements in its first row equal to zero. The elements in the first column position of each of the other rows will be the reciprocal (i.e. the same value but with the sign swapped) of the element in corresponding position of A. The element B[i][j] for all other values of i and j will be - A[i][0]*A[0][j]/A[0][0] 2. Two matrices can be added together!! " # $ ## $ ## &% ' ( ) To perform addition you simply add pairs of corresponding components. Extend the program developed for the previous question (but save this as a separate Java file) to return the sum of A and B. ( ( ) 3. Two matrices can also be multiplied together. The result of multiplying the matrices: )*+*,)*.-")*0/")*.1 )(-2*,)(-3-")(-+/")4-31 )(/2*,)(/3-")(/+/")4/ *3* 7-9* /9* 12* * / *0/ -+/ /+/ 19/ ;: :

2 is the matrix! " " " " " " " " # $ $ # $ # $ $! $ $ " # $ &% Notice that the number of columns in the first matrix must coincide with the number of rows in the second one. Moreover the resulting matrix will have as many rows as the first matrix and as many columns as the second one. Return a program that receives from the keyboard the elements of the two matrices and produces in output the result of their product (or an error message if the sizes of the two matrices are not right or any other error occur). ( ) Return your solutions as three separate programs. (Total mark ). 2 Exercise 2 Submit two different program files, one for each of the following sections. As the marking scheme suggests the first exercise is the most important. Concentrate on getting that right. If you manage to solve it, then the second part will be easy. The second part will take little time to code but it does not have any more conceptual difficulties than the first one. ' Return a working implementation of the League Table program described in the lecture. Hints: You need to implement the system designed during the lecture 9% ' Modify the League Table program to manage the Chart of the World Rugby League championship. The input this time is a number of lines of the form: TEAM1 score tries TEAM2 score tries Points are added to an overall league table with the following conventions: 1. Points (that get added to the score) can be gained by either scoring tries or kicks. 2. Each kick (following a penalty or resulting from a drop goal) is worth three points. Each kick following a try is worth two points. 3. Each try is worth five points. 4. The score is the total number of points a team earns in a match. 5. A win gives the team three points in the overall standing, a draw one point a defeat zero. 6. One bonus point in the overall standing is earned by any team that scores four tries in a match (no matter whether it wins or not). 7. One bonus point in the overall standing is earned by any team that wins with a difference of more than four tries. Assume sixteen teams take part in the tournament. Hints: start from the program for part one, and change the way in which points are awarded. 4% (Total mark: 4 ) 2

3 Marking guidelines. They have to solve two exercises. If all programs they have submitted compile then 10% of the mark for each exercise is for documentation (so 1.1% for exercise one and 1.3% for exercise two). If some (perhaps even all of them) of their programs do NOT compile then given 20% of the mark for the exercise to the documentation. To make life simple mark the documentation only once for each exercise (no matter if they have submitted separate programs for each part). We distinguish between Good and complete documentation (full mark), complete documentation (three quarters of the mark), incomplete but clear documentation (half of the mark) bad documentation (a quarter) missing documentation (no mark at all here). In the spreadsheet there is a cell for each part of each exercise. We give a mark between zero and ten to each part of each exercise (even if they have submitted a single program solving all parts, it does not matter). We try to be simple. We distinguish between Perfect, Good, Not so Good, Bad program only. After marking each exercise make sure your mark satisfies the following constraints. A program that compiles must get (at least) 25% of the mark allocated for it. If the program does NOT compile, it cannot get more than a 20% of the mark allocated for the program. Essentially there may be two reasons why the program does not compile: (a) some stupid typo (a missing or ; ) (b) major syntactic errors (these are serious). A program that produces correct results sometimes must get 50% of the mark allocated for the program. Rules on Exercise 1. The first part is about defining a matrix in terms on another one (10% of a distinction mark taken out if they don t check A[0][0]!= 0, only 5% taken out is the program is not a high quality one; Good or Perfect solutions will have a single pair of nested loops and an if statement to set B as in the program below). The second one is about the sum of two matrices. The third about the product of a matrix by a vector. See sample solution below. The following solves the first two parts (students are required to write TWO distinct programs). import java.io.*; import java.util.*; class Gauss { // global declarations static BufferedReader keyboard = new BufferedReader ( new InputStreamReader(System.in) ); public static void main (String[] args) throws IOException { double [][] A; double [][] B; double [][] C; double [] X; int n, m; StringTokenizer data; System.out.print("Please enter the dimensions of A: "); if (data.counttokens() == 2) { n = new Integer(data.nextToken()).intValue(); m = new Integer(data.nextToken()).intValue(); // the number of rows and columns is now fixed, no possibility // of a mistake. If X is defined later and you choose to input // its dimension again then you need to check that the sizes are // right. A = new double [n][m]; B = new double [n][m]; C = new double [n][m]; X = new double [m]; 3

4 // You may prefer to use the tokenizer again here... (I think // the code becomes a bit more complex). for ( int i = 0 ; i < n ; i++) { System.out.print("A["+(i+1)+","+(j+1)+"] = "); A[i][j] = new Double(keyboard.readLine()).doubleValue(); // Definition of B. for ( int i = 0 ; i < n ; i++) if (i==0) B[i][j] = 0.0; else if (A[0][0]!=0.0) B[i][j] = - A[i][0]*A[0][j]/A[0][0]; else { System.out.println("The PIVOT is zero!!! I am getting out of here!"); break; // Computing A+B if (A[0][0]!=0.0) { for ( int i = 0 ; i < n ; i++) C[i][j] = A[i][j] + B[i][j]; // printing what is going on System.out.println("Matrix A"); for ( int i = 0 ; i < n ; i++) { System.out.print(A[i][j] + " "); System.out.println(); // printing what is going on System.out.println("Matrix B"); for ( int i = 0 ; i < n ; i++) { System.out.print(B[i][j] + " "); System.out.println(); // printing what is going on System.out.println("Matrix C"); for ( int i = 0 ; i < n ; i++) { System.out.print(C[i][j] + " "); System.out.println(); else System.out.println("You did not give me the number of rows and columns of A."); The product program should be along the following example: import java.io.*; import java.util.*; class Matrix\_Prod { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader(System.in) ); public static void main(string[] args) throws IOException { int dim1, dim2; int[][] A; int dim3, dim4; 4

5 int[][] B; int b1, b2, b3, b4; int partial; StringTokenizer data; int i, j; int k; // read the first matrix dimension dim1 = new Integer( data.nexttoken()).intvalue(); dim2 = new Integer( data.nexttoken()).intvalue(); A = new int[dim1][dim2]; // read the first matrix values for ( i = 0; i < dim1; i++ ) { // checks on the presence of a valid array of values // can be added here to get more distinction marks for ( j = 0; j < dim2; j++ ) // checks on the presence on next token, using // token counter can be used here. A[i][j] = new Integer( data.nexttoken()).intvalue(); // read the second matrix dimension dim3 = new Integer( data.nexttoken()).intvalue(); dim4 = new Integer( data.nexttoken()).intvalue(); if ( dim2 == dim3 ) { B = new int[dim3][dim4]; System.out.println( "Multiplying two matrices"); // read the second matrix values for ( i = 0; i < dim3; i++ ) { // checks on the presence of a valid array of values // can be added here to get more distinction marks for ( j = 0; j < dim4; j++ ) // checks on the presence on next token, using // token counter can be used here. B[i][j] = new Integer( data.nexttoken()).intvalue(); // produce the resulting matrix for ( i = 0; i < dim1; i++ ) { for ( j = 0; j < dim4; j++ ) { partial = 0; for ( k = 0; k < dim3; k++ ) partial = partial + (A[i][k]*B[k][j]); System.out.print( partial + " "); System.out.println(); else System.out.println("The dimensions of the two matrices do not match!"); As test case use the following: 5

6 # 5 # # " % " # Specific rules Exercise 2. A complete solution must contain two programs. The different programs are worth.1%, 3.6% respectively (the 10% for the documentation has been subtracted). One needs to be hard in marking the first exercise, but then easily give 10 marks for exercise 2 if it is correct. Ex. 2.1 The following is a sample solution which would get 90% of the program marks for this question (this is 1% of the full mark for this question (this is what I call mark in absolute terms below). A better solution should cope with input checks, as follows. Every time something is read from the input file a number of checks could be enforced to test whether the number of tokens in the line just read is right (4%, in absolute terms) and if the team names are consistent (5%). Overall assign max 9% (which takes the overall percentage for the program to 90%). Penalise solutions in which not all variables declared are necessary (max -10% mark in absolute terms) or they are NOT like specified in the design provided during the Lectures. Programs that only work for results of two weeks get 60% in absolute terms. // chap_5\ex_ // program to calculate the league chart based on a number of results // stored in a text file "results.txt" import java.io.*; import java.util.*; class League { // The program has no reader from input. It will get all its data from // a file. public static void main(string[] args) throws IOException { // I am using a league of 20 teams final int NUMBER_OF_TEAMS = 20; // File containing all results. FileReader file = new FileReader("results.txt"); BufferedReader inputfile = new BufferedReader(file); StringTokenizer data; // Output data structures String[] Teams = new String[NUMBER_OF_TEAMS]; int[] points = new int[number_of_teams]; // Internal representation of a week results. We need it // to be the full table if we want to split the initialisation // of the score chart (first loop) from its updating. String[][] weekresults = new String[NUMBER_OF_TEAMS/2][4]; // counters int match, i; boolean TeamListHasBeenSet = false; for ( i = 0; i < NUMBER_OF_TEAMS; i++) points[i] = 0; // read week results from the file results.txt and store this // data in a two-dimensional array. // The first readline reads in the WEEK 1 banner. 6

7 while (!data.nexttoken().equals(".")) { // Enter data for the next week for ( match = 0; match < (NUMBER_OF_TEAMS/2); match++) { // The following instruction reads one after the other // the results of a week. for ( i = 0; i < 4; i++) weekresults[match][i] = data.nexttoken(); if (!TeamListHasBeenSet) { Teams[2*match] = weekresults[match][0]; Teams[2*match + 1] = weekresults[match][2]; // Teams will not be changed any more. TeamListHasBeenSet = true; // Updates the various teams points based on the latest results. for ( match = 0; match < (NUMBER_OF_TEAMS/2); match++) { // Find the index of the team. i = 0; while (!Teams[i].equals(weekResults[match][0])) i++; if ((new Integer(weekResults[match][1]).intValue()) > (new Integer(weekResults[match][3]).intValue())) points[i] = points[i] + 3; else if ((new Integer(weekResults[match][1]).intValue()) == (new Integer(weekResults[match][3]).intValue())) i = 0; while (!Teams[i].equals(weekResults[match][2])) i++; if ((new Integer(weekResults[match][1]).intValue()) < (new Integer(weekResults[match][3]).intValue())) points[i] = points[i] + 3; else if ((new Integer(weekResults[match][1]).intValue()) == (new Integer(weekResults[match][3]).intValue())) // The next instruction reads a new line from the text file. System.out.println("League Table\n"); System.out.println("Team\tTotal\n"); for ( i = 0; i < NUMBER_OF_TEAMS; i++) { if (Teams[i].length() > 7) System.out.println(Teams[i].substring(0,7) + "\t" + points[i]); else System.out.println(Teams[i] + "\t" + points[i]); Ex. 2.2 The modification on Ex. 2.1 is obvious. Give the full marks (plus whatever comes from the documentation) for a program that differs from the one solving 2.1 only for the size of the internal data structure for the week results, for the different place where the points can be computed and for the few more instructions needed to deal with bonus points. The final output part should be exactly the same as for exercise

8 Any more complicate CORRECT solution gets a pass mark. // program to calculate the rugby league chart based on a number of results // stored in a text file "results.txt" import java.io.*; import java.util.*; class RugbyLeague { // The program has no reader from input. It will get all its data from // a file. public static void main(string[] args) throws IOException { // I am using a league of 10 teams final int NUMBER_OF_TEAMS = 10; // File containing all results. FileReader file = new FileReader("rugby.txt"); BufferedReader inputfile = new BufferedReader(file); StringTokenizer data; // Output data structures String[] Teams = new String[NUMBER_OF_TEAMS]; int[] points = new int[number_of_teams]; // Internal representation of a week results. We need it // to be the full table if we want to split the initialisation // of the score chart (first loop) from its updating. String[][] weekresults = new String[NUMBER_OF_TEAMS/2][6]; // counters int match, i; boolean TeamListHasBeenSet = false; for ( i = 0; i < NUMBER_OF_TEAMS; i++) points[i] = 0; // read week results from the file results.txt and store this // data in a two-dimensional array. // The first readline reads in the WEEK 1 banner. while (!data.nexttoken().equals(".")) { // Enter data for the next week for ( match = 0; match < (NUMBER_OF_TEAMS/2); match++) { // The following instruction reads one after the other // the results of a week. for ( i = 0; i < 6; i++) weekresults[match][i] = data.nexttoken(); if (!TeamListHasBeenSet) { Teams[2*match] = weekresults[match][0]; Teams[2*match + 1] = weekresults[match][3]; // Teams will not be changed any more. TeamListHasBeenSet = true; // Updates the various teams points based on the latest results. for ( match = 0; match < (NUMBER_OF_TEAMS/2); match++) { // Find the index of the team. i = 0; while (!Teams[i].equals(weekResults[match][0])) i++; if ((new Integer(weekResults[match][1]).intValue()) >

9 (new Integer(weekResults[match][4]).intValue())) points[i] = points[i] + 3; else if ((new Integer(weekResults[match][1]).intValue()) == (new Integer(weekResults[match][4]).intValue())) if ((new Integer(weekResults[match][2]).intValue()) >= 4) if ((new Integer(weekResults[match][2]).intValue()) > (new Integer(weekResults[match][5]).intValue())+3) i = 0; while (!Teams[i].equals(weekResults[match][3])) i++; if ((new Integer(weekResults[match][1]).intValue()) < (new Integer(weekResults[match][4]).intValue())) points[i] = points[i] + 3; else if ((new Integer(weekResults[match][1]).intValue()) == (new Integer(weekResults[match][4]).intValue())) if ((new Integer(weekResults[match][5]).intValue()) >= 4) if ((new Integer(weekResults[match][5]).intValue()) > (new Integer(weekResults[match][2]).intValue())+3) // The next instruction reads a new line from the text file. System.out.println("League Table\n"); System.out.println("Team\tTotal\n"); for ( i = 0; i < NUMBER_OF_TEAMS; i++) { if (Teams[i].length() > 7) System.out.println(Teams[i].substring(0,7) + "\t" + points[i]); else System.out.println(Teams[i] + "\t" + points[i]); 9

oblem. The annual rainfall is recorded monthly over four regions calculate the total and average rainfall for a region one needs to sum up

oblem. The annual rainfall is recorded monthly over four regions calculate the total and average rainfall for a region one needs to sum up ecture 10 More examples with (multi-dimensional) arrays. Vectors (variable size sequences). Material from the second half of Holmes Chapter 5 (with few bits missing). 1 ase Study: Calculate Rainfall over

More information

Case Study: Savings Account Interest

Case Study: Savings Account Interest ecture 8 Loops: recap + example. Files: abstracting from a specific devise. Streams and Tokens. Examples. Material from the second half of Holmes Chapter 4. 1 w do you add up a sequence of numbers? = 1;

More information

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples. // Simple program to show how an if- statement works. import java.io.*; Lecture 6 class If { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); public static void

More information

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern School of Computer Science, University of Birmingham. Java Lecture notes. M. D. Ryan. September 2001. A very simple program Week 2: variables & expressions Variables, assignments, expressions, and types.

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library HSA to Core Java A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library The examples below compare how tasks are done using the hsa Console class with how they

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

Building Java Programs

Building 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 information

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP Administration Conditional Statements CS 99 Summer 2000 Michael Clarkson Lecture 4 Lab 2 due now on floppy Lab 3 due tomorrow via FTP need Instruct account password Lab 4 posted this afternoon Prelim 1

More information

Lecture 14. 'for' loops and Arrays

Lecture 14. 'for' loops and Arrays Lecture 14 'for' loops and Arrays For Loops for (initiating statement; conditional statement; next statement) // usually incremental body statement(s); The for statement provides a compact way to iterate

More information

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1) Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

Algorithms and Problem Solving

Algorithms and Problem Solving Algorithms and Problem Solving Introduction What is an Algorithm? Algorithm Properties Example Exercises Unit 16 1 What is an Algorithm? What is an Algorithm? An algorithm is a precisely defined and ordered

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last 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 information

Recitation: Loop Jul 7, 2008

Recitation: Loop Jul 7, 2008 Nested Loop Recitation: Loop Jul 7, 2008 1. What is the output of the following program? Use pen and paper only. The output is: ****** ***** **** *** ** * 2. Test this program in your computer 3. Use "for

More information

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371 Class IX HY 2013 Revision Guidelines Page 1 Section A (Power Point) Q1.What is PowerPoint? How are PowerPoint files named? Q2. Describe the 4 different ways of creating a presentation? (2 lines each) Q3.

More information

Lesson 3: Accepting User Input and Using Different Methods for Output

Lesson 3: Accepting User Input and Using Different Methods for Output Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program

More information

COMP 110 Project 1 Programming Project Warm-Up Exercise

COMP 110 Project 1 Programming Project Warm-Up Exercise COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

CS 161: Object Oriented Problem Solving

CS 161: Object Oriented Problem Solving About this course CS 161: Object Oriented Problem Solving About this course Course webpage: http://www.cs.colostate.edu/~cs161/ The course webpage is our major communication tool. Check it on a daily basis!

More information

Programming Problems 15th Annual Computer Science Programming Contest

Programming Problems 15th Annual Computer Science Programming Contest Programming Problems 15th Annual Computer Science Programming Contest Department of Mathematics and Computer Science Western Carolina University March 0, 200 Criteria for Determining Scores Each program

More information

Lab #10 Multi-dimensional Arrays

Lab #10 Multi-dimensional Arrays Multi-dimensional Arrays Sheet s Owner Student ID Name Signature Group partner 1. Two-Dimensional Arrays Arrays that we have seen and used so far are one dimensional arrays, where each element is indexed

More information

Last 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 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 information

McGill University School of Computer Science COMP-202A Introduction to Computing 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

CSEN 202 Introduction to Computer Programming

CSEN 202 Introduction to Computer Programming CSEN 202 Introduction to Computer Programming Lecture 4: Iterations Prof. Dr. Slim Abdennadher and Dr Mohammed Abdel Megeed Salem, slim.abdennadher@guc.edu.eg German University Cairo, Department of Media

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence 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 information

The source code is as follows:

The source code is as follows: ENCE 688R: Solutions to Homework 1 March 2017 ========================================================================= Problem 7.2: Compute and print sum of numbers below 1000 that are either multiples

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 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 information

Principles of Computer Science I

Principles of Computer Science I Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination Tuesday, November 4, 2008 Examiners: Mathieu Petitpas [Section 1] 18:30

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM Let s get some practice creating programs that repeat commands inside of a loop in order to accomplish a particular task. You may

More information

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file? CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7 Question 1. (2 points) What is the difference between a stream and a file? A stream is an abstraction representing the flow of data from one place to

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

CS2 Practical 1 CS2A 22/09/2004

CS2 Practical 1 CS2A 22/09/2004 CS2 Practical 1 Basic Java Programming The purpose of this practical is to re-enforce your Java programming abilities. The practical is based on material covered in CS1. It consists of ten simple programming

More information

Arrays in Java Multi-dimensional Arrays

Arrays in Java Multi-dimensional Arrays Suppose you are tasked with writing a program to help maintain seating records for a theatre company. The auditorium has 25 rows, each of which contains 30 seats. One utility you need to provide is tracking

More information

Selec%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 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 information

1.00 Lecture 30. Sending information to a Java program

1.00 Lecture 30. Sending information to a Java program 1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes

More information

CSE 143 Au03 Final Exam Page 1 of 15

CSE 143 Au03 Final Exam Page 1 of 15 CSE 143 Au03 Final Exam Page 1 of 15 Reference information about many standard Java classes appears at the end of the test. You might want to tear off those pages to make them easier to refer to while

More information

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development

More information

Example: Computing prime numbers

Example: 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 information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 000 Spring 2015 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

Project #1 Computer Science 2334 Fall 2008

Project #1 Computer Science 2334 Fall 2008 Project #1 Computer Science 2334 Fall 2008 User Request: Create a Word Verification System. Milestones: 1. Use program arguments to specify a file name. 10 points 2. Use simple File I/O to read a file.

More information

COMP-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 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 information

Bjarne Stroustrup. creator of C++

Bjarne Stroustrup. creator of C++ We Continue GEEN163 I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. Bjarne Stroustrup creator

More information

Attendance (2) Performance (3) Oral (5) Total (10) Dated Sign of Subject Teacher

Attendance (2) Performance (3) Oral (5) Total (10) Dated Sign of Subject Teacher Attendance (2) Performance (3) Oral (5) Total (10) Dated Sign of Subject Teacher Date of Performance:... Actual Date of Completion:... Expected Date of Completion:... ----------------------------------------------------------------------------------------------------------------

More information

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input

More information

Building Java Programs

Building 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 information

Classes Basic Overview

Classes Basic Overview Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

Selec%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 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 information

Declaring a 2D Array

Declaring a 2D Array Lecture 13 Declaring a 2D Array Model: type name[row_size ][ column_size] Example: int grades[10][20]; string students[10][20]; 2D Array data structure Say we have the following array: int grades[4][8];

More information

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

Combo Lecture Lecture 14/15. Instructor: Craig Duckett Combo Lecture Lecture 14/15 Instructor: Craig Duckett Assignment Dates (By Due Date) Assignment 1 (LECTURE 5) GRADED! Section 1: Monday, January 22 nd Assignment 2 (LECTURE 8) GRADED! Section 1: Wednesday,

More information

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

CP122 CS I. Iteration

CP122 CS I. Iteration CP122 CS I Iteration Tech News! Pix2Pix: machine learning translation of images https://affinelayer.com/pixsrv/ Tech News! Pix2Pix: machine learning translation of images https://affinelayer.com/pixsrv/

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

DOMjudge team manual. Summary. Reading and writing. Submitting solutions. Viewing scores, submissions, etc.

DOMjudge team manual. Summary. Reading and writing. Submitting solutions. Viewing scores, submissions, etc. judge DOMjudge team manual Summary /\ DOM DOM judge Here follows a short summary of the system interface. This is meant as a quick introduction, to be able to start using the system. It is, however, strongly

More information

Decisions in Java IF Statements

Decisions in Java IF Statements Boolean Values & Variables In order to make decisions, Java uses the concept of true and false, which are boolean values. Just as is the case with other primitive data types, we can create boolean variables

More information

Building Java Programs

Building 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 information

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file

More information

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one

More information

Soda Machine Laboratory

Soda Machine Laboratory Soda Machine Laboratory Introduction This laboratory is intended to give you experience working with multiple queue structures in a familiar real-world setting. The given application models a soda machine

More information

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java. CS121: Computer Programming I A) Collections B) File I/O & Error Handling Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use

More information

CS 2223 B15 Term. Homework 1 (100 pts.)

CS 2223 B15 Term. Homework 1 (100 pts.) CS 2223 B15 Term. Homework 1 (100 pts.) Homework Instructions This homework is to be completed individually. If you have any questions as to what constitutes improper behavior, review the examples I have

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture 2 Use case Use case diagram State (machine) diagram Sequence diagram Class diagram of vending machine Vending

More information

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

A sample print out is: is is -11 key entered was: w

A sample print out is: is is -11 key entered was: w Lab 9 Lesson 9-2: Exercise 1, 2 and 3: Note: when you run this you may need to maximize the window. The modified buttonhandler is: private static class ButtonListener implements ActionListener public void

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

Final Exam. COMP Summer I June 26, points

Final 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 information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Supplementary Examination Question

More information

Fall 2002 Page 1 of 9 READ THIS NOW!

Fall 2002 Page 1 of 9 READ THIS NOW! Fall 2002 Page 1 of 9 READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Failure to adhere to these directions will not constitute an excuse or defense. Print

More information

Chapter 9 Lab Text Processing and Wrapper Classes

Chapter 9 Lab Text Processing and Wrapper Classes Lab Objectives Chapter 9 Lab Text Processing and Wrapper Classes Use methods of the Character class and String class to process text Be able to use the StringTokenizer and StringBuffer classes Introduction

More information

! 52 playing cards in a deck. ! 5 thousand undergrads at Princeton. ! 1 million characters in a book. ! 10 million audio samples in an MP3 file.

! 52 playing cards in a deck. ! 5 thousand undergrads at Princeton. ! 1 million characters in a book. ! 10 million audio samples in an MP3 file. Arrays 1.4 Arrays This lecture. Store and manipulate huge quantities of data. Array. Indexed sequence of values of the same type. Examples.! 52 playing cards in a deck.! 5 thousand undergrads at Princeton.!

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

GB Programming Challenges

GB Programming Challenges GB21802 - Programming Challenges Week 1 - Ad-hoc problems Claus Aranha caranha@cs.tsukuba.ac.jp College of Information Science April 18, 2014 Some Notes Before the Class Don t forget to send me your username

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has. ASSIGNMENT 0 Introduction to Linear Algebra (Basics of vectors and matrices) Due 3:30 PM, Tuesday, October 10 th. Assignments should be submitted via e-mail to: matlabfun.ucsd@gmail.com You can also submit

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 000 Spring 2015 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

Data Types and the while Statement

Data Types and the while Statement Session 2 Student Name Other Identification Data Types and the while Statement In this laboratory you will: 1. Learn about three of the primitive data types in Java, int, double, char. 2. Learn about the

More information

Last Class. More on loops break continue A bit on arrays

Last 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 information

1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.

1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data. A Foundation for Programming 1.4 Arrays any program you might want to write objects functions and modules graphics, sound, and image I/O arrays store and manipulate huge quantities of data conditionals

More information

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk Chapter 4 Loops Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ while Loop Flow Chart while (loop-continuation-condition) { // loop-body;

More information

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur Lecture 04 Demonstration 1 So, we have learned about how to run Java programs

More information

ECM1406. Answer Sheet Lists

ECM1406. Answer Sheet Lists ECM1406 Answer Sheet Lists These questions are based on those found in Chapters 3 and 4 of the core text Data Structures Using Java by Malik and Nair. The source code for the ArrayListClass, UnorderedArrayList,

More information

Repetitive Program Execution

Repetitive Program Execution Repetitive Program Execution Quick Start Compile step once always mkdir labs javac Vowel3java cd labs mkdir 3 Execute step cd 3 java Vowel3 cp /samples/csc/156/labs/3/* Submit step emacs Vowel3java & submit

More information

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics Inf1-OP Arrays 1 Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics January 30, 2017 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays:

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

More information

Computer Science is...

Computer 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 information

Recursive Problem Solving

Recursive Problem Solving Recursive Problem Solving Objectives Students should: Be able to explain the concept of recursive definition. Be able to use recursion in Java to solve problems. 2 Recursive Problem Solving How to solve

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

COMP-202 Unit 4: Programming with Iterations

COMP-202 Unit 4: Programming with Iterations COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Chapter 7. Iteration. 7.1 Multiple assignment

Chapter 7. Iteration. 7.1 Multiple assignment Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);

More information