Lecture 2. Two-Dimensional Arrays
|
|
- Melinda Dawson
- 5 years ago
- Views:
Transcription
1 Lecture 2 Two-Dimensional Arrays 1
2 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 2
3 1. 2-D Array Basics An array that requires two indices to identify a particular element is called two-dimensional arrays (also called matrix). 2-D arrays are often used to represent tables of values consisting of information arranged in rows and columns. 3
4 1. 2-D Array Basics To identify a particular table element, we must specify two indices. By convention, the first index identifies the element s row and the second index identifies the element s column. In general, n-dimensional array is defined as an array of (n - 1)-dimensional arrays. That is, 2-D array is an array of 1-D arrays, 3-D array is an array of 2-D arrays, and so on. 4
5 1. 2-D Array Basics The figure shown below illustrates a twodimensional array a that contains three rows and four columns (i.e., a three-by-four array). In general, an array with m rows and n columns is called an m-by-n array. 5
6 1. 2-D Array Basics Every element of array a in the figure above is identified by an array-access expression of the form a[i][j]; a is the name of the array, and i and j are the indices that uniquely identify each element in array a by row and column number. 6
7 1. 2-D Array Basics A 2-D array is declared as follows. int[][] a; // a = null or int[][] a = {{1, 2, 3}, {4, 5, 6}}; // 2-by-3 array of integers or int a[][] = {{1, 2, 3}, {4, 5, 6}}; 7
8 1. 2-D Array Basics Array rows can have different columns as follows. int[][] b = {{1, 2}, {3, 4, 5}}; The compiler counts the number of nested array initializers (represented by sets of braces within the outer braces) in the array declaration to determine the number of rows in array b. The compiler counts the initializer values in the nested array initializer for a row to determine the number of columns in that row. 8
9 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 9
10 2. Basic Operations on 2-D Array - input a matrix - output a matrix - add two matrices - multiply two matrices - permute a matrix - find min or max element of a matrix 10
11 Input a Matrix int a[][]; System.out.print("Enter #rows:"); M = in.nextint(); System.out.print( "Enter #columns:"); N = in.nextint(); a = new int[m][n]; 11
12 Input a Matrix public static void inputmatrix( int a[][], int M, int N) { Scanner in = new Scanner(System.in); System.out.println( "Enter elements"); 12
13 Input a Matrix for (int i = 0; i < M; i++) { // scan rows for (int j = 0; j < N; j++) { // scan columns System.out.print( "Element (" + i + ", " + j + ") = "); a[i][j] = in.nextint(); } } } // end of inputmatrix() 13
14 Output a Matrix public static void outputmatrix( int a[][]) { // output elements of a 2-D array int i = 0, j = 0; // loop through array's rows for (i = 0; i < a.length; i++) { // loop through columns of current row 14
15 Output a Matrix for (j = 0; j < a[i].length; j++) System.out.printf( "%d ", a[i][j]); // start new line of output System.out.println(); } // end outer for } // end method outputmatrix() 15
16 Matrix Addition C m n = A m n + B m n C ij = A ij + B ij, 0 i < m, 0 j < n 16
17 Matrix Addition public static void add(int a[][], int b[][], int c[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) for (j = 0; j < a[i].length; j++) c[i][j] = a[i][j] + b[i][j]; } // end method add() 17
18 Example of Matrix Addition Values in matrix A Values in matrix B C = A + B
19 Matrix Multiplication. 19
20 Matrix Multiplication public static void multiply(int a[][], int b[][], int c[][]) { int i = 0, j = 0, k = 0; for (i = 0; i < a.length; i++) { // m rows for (j = 0; j < b[i].length; j++) { // n columns c[i][j] = 0; 20
21 Matrix Multiplication for (k = 0; k < a[i].length; k++) // p products c[i][j] += a[i][k] * b[k][j]; } } } // end method multiply() 21
22 Example of Matrix Multiplication Values in matrix A Values in matrix B C = A x B
23 Matrix Permutation public static void permute(int a[][], int pa[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { pa[j][i] = a[i][j]; } } } // end method permute() 23
24 Example of Matrix Permutation Values in matrix A Permuted A is pa
25 Find Minimum Element of Matrix public static int minmatrix(int a[][]) { int i = 0, j = 0, min = a[0][0]; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { if (a[i][j] < min) min = a[i][j]; } } return min; } // end method minmatrix() 25
26 Find Maximum Element of Matrix public static int maxmatrix(int a[][]) { int i = 0, j = 0, max = a[0][0]; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { if (a[i][j] > max) max = a[i][j]; } } return max; } // end method maxmatrix() 26
27 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 27
28 Store Elements of 2D Array to 1D Array Values in 2D array a[m][n] by row are Values in 1D array b[m * n] are 28
29 Store Elements of 2D Array to 1D Array public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) b[i*n + j] = a[i][j]; } } 29
30 Store Elements of 1D Array to 2D Array Values in 1D array b[m * n] are Values in 2D array a[m][n] by row are 30
31 Store Elements of 1D Array to 2D Array public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) a[i][j] = b[i*n + j]; } } 31
32 Store Elements of 1D Array to 2D Array public static void store1dto2d( int b[], int a[][]) { for (int k = 0; k < m*n; k++) a[k / n][k % n] = b[k]; } 32
33 Triangular Matrices An n n lower-triangular matrix a[1..n][1..n] is one in which the non-zero elements are all found on or below the main diagonal, in lower triangle; all elements above the main diagonal are zero. 33
34 Triangular Matrices We need to store = 6 elements (i.e., n(n + 1)/2). An element a ij property i < j. above the main diagonal has the An element a ij below or on the main diagonal has the property i j. a ij is stored in 1D array at b[i(i - 1) / 2 + j] 34
35 Triangular Matrices public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) b[i * (i - 1) / 2 + j] = a[i][j]; } } 35
36 Triangular Matrices public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) if (i < j) a[i][j] = 0; else a[i][j] = b[i * (i - 1) / 2 + j]; } } 36
37 Triangular Matrices Values in 2D array a[n+1][n+1] by row are Values in 1D array b[n*(n+1)/2] are 37
38 Triangular Matrices Values in 1D array b[n*(n+1)/2] are Values in 2D array a[n+1][n+1] by row are 38
39 Symmetric Matrix A symmetric matrix a[1..n][1..n] is one in which a ij = a ji. We need to store = 6 elements (i.e., n(n + 1)/2). a ij is stored in 1D array at b[i(i - 1) / 2 + j]. 39
40 Symmetric Matrix An element a ij below or on the main diagonal (i.e., i j) is retrieved from b[i(i - 1) / 2 + j]. An element a ij above the main diagonal (i.e., i < j) is retrieved from b[j(j - 1) / 2 + i]. 40
41 Symmetric Matrix public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) b[i * (i - 1) / 2 + j] = a[i][j]; } } 41
42 Symmetric Matrix public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) if (i >= j) a[i][j] = b[i * (i - 1) / 2 + j]; else a[i][j] = b[j * (j - 1) / 2 + i]; } } 42
43 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 43
44 Digital Image Processing Application Original grayscale Lena image sized pixels 44
45 Read Image Data Stored in File public static void readimagefile(string fn, int I[][]) throws IOException { // Read original image data into I[][] int i = 0, j = 0; System.out.println( "Reading image file " + fn); FileInputStream fin = new FileInputStream(fn); for (i = 0; i < H; i++) { // scan image height (rows) 45
46 Read Image Data Stored in File for (j = 0; j < W; j++) { // scan image width (columns) // read one byte of image data I[i][j] = fin.read(); } } fin.close(); } // end readimagefile() 46
47 Read Image Data Stored in File import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; public class imageapp { final static int H = 512; // image height final static int W = 512; // image width... } // H and W are class data values // H and W are constant data values 47
48 Display Image Data on Screen public static void displayimage(int I[][]) { // display image data in I[][] onto screen int i = 0, j = 0; for (i = 0; i < H; i++) { // loop through image's rows // loop through image's columns for (j = 0; j < W; j++) System.out.printf("%4d", I[i][j]); // start new line of output System.out.println(); } // end outer for } // end displayimage() 48
49 Write Image Data to File public static void saveimage(int I[][], String fn) { // save processed image data in I[][] // to image file int i = 0, j = 0; System.out.println( "Saving image data " + fn); try { FileOutputStream fout = new FileOutputStream(fn, false); 49
50 Write Image Data to File for (i = 0; i < H; i++) { // scan image height (rows) for (j = 0; j < W; j++) { // scan image width (columns) } } // write one byte of image data to file fout.write(i[i][j]); 50
51 Write Image Data to File fout.close(); } // end try catch (IOException ioe) { } } // end saveimage() 51
52 Image Permutation public static void permuteimage( int I[][], int PI[][]) { // permute image I to be // permuted image PI int i = 0, j = 0; 52
53 Image Permutation for (i = 0; i < H; i++) { // scan image height (rows) for (j = 0; j < W; j++) { // scan image width (columns) PI[j][i] = I[i][j]; } } } // end permuteimage() 53
54 Permuted Image Permuted Lena (Horizontal flip, Left Rotation 90 o ) 54
55 Make Image Brighter Original Lena image Brighter image 55
56 Make Image Brighter public static void brighterimage( int I[][], int BI[][]) { // make image I to be brighter image BI int i = 0, j = 0; for (i = 0; i < H; i++) { // scan image height (rows) 56
57 Make Image Brighter for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] < 215) BI[i][j] = I[i][j] + 40; else BI[i][j] = 255; } } } // end brighterimage() 57
58 Make Image Darker Original Lena image Darker image 58
59 Make Image Darker public static void darkerimage( int I[][], int DI[][]) { // make image I to be darker image DI int i = 0, j = 0, min = 0; for (i = 0; i < H; i++) { // scan image height (rows) 59
60 Make Image Darker for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] > 40) DI[i][j] = I[i][j] - 40; else DI[i][j] = 0; } } } // end darkerimage() 60
61 Convert Grayscale Image to Binary Image Original Lena image Binary image 61
62 Convert Grayscale Image to Binary Image public static void BWImage(int I[][], int BWI[][]) { // make image I to be binary image // BWI int i = 0, j = 0; for (i = 0; i < H; i++) { // scan image height (rows) 62
63 Convert Grayscale Image to Binary Image for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] <= 127) // black color BWI[i][j] = 0; else // white color BWI[i][j] = 255; } } } // end BWImage() 63
64 Input/Output from/to Keyboard/Screen import java.util.scanner; class inputoutput { public static void main( String[] args) { Scanner in = new Scanner(System.in); 64
65 Input/Output from/to Keyboard/Screen System.out.print( "Enter an integer number: "); int x = in.nextint(); System.out.printf( "The entered integer is %d\n", x); 65
66 Input/Output from/to Keyboard/Screen System.out.print( "Enter a real number (float): "); float y = in.nextfloat(); System.out.printf( "The entered real number (float) is %.2f\n", y); 66
67 Input/Output from/to Keyboard/Screen System.out.print( "Enter a real number (double): "); double z = in.nextdouble(); System.out.printf( "The entered real number is %.2f\n", z); 67
68 Input/Output from/to Keyboard/Screen System.out.print( "Enter a character: "); String str = in.next(); char chr = str.charat(0); System.out.printf("The entered letter is %c\n", chr); 68
69 Input/Output from/to Keyboard/Screen System.out.print( "Enter a word (string without spaces): "); String w = in.next(); System.out.printf( "The entered word is %s\n", w); 69
70 Input/Output from/to Keyboard/Screen System.out.print( "Enter a string (with spaces): "); in.nextline(); // clear '\n' in buffer String strg = in.nextline(); System.out.printf( "The entered string is %s\n", strg); } // end main() } // end class inputoutput 70
71 Exercises I. Write complete Java programs to perform the following basic operations on 2-D array (i.e., matrix). 1. Input an m-by-n matrix a. 2. Output an m-by-n matrix a. 3. Add two matrices a m n and b p q to obtain matrix s. 4. Multiply two matrices a m n and b p q to obtain matrix M. 5. Permute a matrix a m n to obtain matrix pa n m. 6. Find the minimum element of an m-by-n matrix a. 7. Find the maximum element of an m-by-n matrix a. 71
72 Exercises II. Use the formulas presented in the lecture notes to write complete Java programs to perform the following tasks. 1. Store the elements of a 2D array a[1..m][1..n] to a 1D array b[1..m n] and vice versa. 2. Store the elements of an n n lower-triangular matrix a[1..n][1..n] to a 1D array b[1..n(n + 1)/2] and vice versa. 3. Store the elements of an n n symmetric matrix a[1..n][1..n] to a 1D array b[1..n(n + 1)/2] and vice versa. 72
73 References 1. Noel Kalicharan Advanced Programming in Java. CreateSpace Press. ISBN: Y. Daniel Liang Introduction to Java Programming, Comprehensive Version. 10th Ed. Prentice Hall. ISBN: Paul Deitel, Harvey Deitel Java How to Program, Early Objects. 10 th Ed. Prentice Hall. ISBN:
74 References 4. Water Savitch, Kenrick Mock Absolute Java. 6 th Ed. Pearson. ISBN:
Lecture 7. File Processing
Lecture 7 File Processing 1 Data (i.e., numbers and strings) stored in variables, arrays, and objects are temporary. They are lost when the program terminates. To permanently store the data created in
More informationGive one example where you might wish to use a three dimensional array
CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming
More informationESC101 : Fundamental of Computing
ESC101 : Fundamental of Computing End Semester Exam 19 November 2008 Name : Roll No. : Section : Note : Read the instructions carefully 1. You will lose 3 marks if you forget to write your name, roll number,
More informationMatrix Multiplication
Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2018 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2018 1 / 32 Outline 1 Matrix operations Importance Dense and sparse
More informationMidterm Examination (MTA)
M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and
More informationMatrix Multiplication
Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2013 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2013 1 / 32 Outline 1 Matrix operations Importance Dense and sparse
More information1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174
1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationCSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1 Arrays Prof. Amr Goneid, AUC 2 1-D Arrays Data Structures The Array Data Type How to Declare
More informationProgramming 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 informationArray. Array Declaration:
Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More information1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.
Name: Write all of your responses on these exam pages. 1 Short Answer (5 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss Java s method. 2. Java is a platform-independent
More informationIntroduction to Software Development (ISD) Week 3
Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process
More informationCS141 Programming Assignment #10
CS141 Programming Assignment #10 Due Sunday, May 5th. 1) Write a class with the following methods: a) max( int [][] a) Returns the maximum integer in the array. b) min(int [][] a) Returns the minimum integer
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationNested Loops. A loop can be nested inside another loop.
Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started
More informationArray. 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 informationLesson 7. Reading and Writing a.k.a. Input and Output
Lesson 7 Reading and Writing a.k.a. Input and Output Escape sequences for printf strings Source: http://en.wikipedia.org/wiki/escape_sequences_in_c Escape sequences for printf strings Why do we need escape
More informationFull 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 informationParallelizing The Matrix Multiplication. 6/10/2013 LONI Parallel Programming Workshop
Parallelizing The Matrix Multiplication 6/10/2013 LONI Parallel Programming Workshop 2013 1 Serial version 6/10/2013 LONI Parallel Programming Workshop 2013 2 X = A md x B dn = C mn d c i,j = a i,k b k,j
More informationAgenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction
COMPSCI 230 S2 2016 Software Construction File Input/Output 2 Agenda & Reading Agenda: Introduction Byte Streams FileInputStream & FileOutputStream BufferedInputStream & BufferedOutputStream Character
More informationArrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington
Arrays and Array Lists CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington 1 Motivation Current limitation: We cannot record multiple
More informationAP Computer Science A Unit 2. Exercises
AP Computer Science A Unit 2. Exercises A common standard is 24-bit color where 8 bits are used to represent the amount of red light, 8 bits for green light, and 8 bits for blue light. It is the combination
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationAL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I
AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic
More informationCOMP 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 informationModule 16: Data Flow Analysis in Presence of Procedure Calls Lecture 32: Iteration. The Lecture Contains: Iteration Space.
The Lecture Contains: Iteration Space Iteration Vector Normalized Iteration Vector Dependence Distance Direction Vector Loop Carried Dependence Relations Dependence Level Iteration Vector - Triangular
More informationCS141 Programming Assignment #6
CS141 Programming Assignment #6 Due Sunday, Nov 18th. 1) Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2 1
More informationHow to swap values of two variables without tmp? However, this naive algorithm is biased. 1
Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...
More informationProgrammierpraktikum
Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 05/07/2012 10:31 AM Input / Output Streams 2 of 21 05/07/2012 10:31 AM Java I/O streams
More informationInstructor: Eng.Omar Al-Nahal
Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar
More informationJava Programs. System.out.println("Dollar to rupee converion,enter dollar:");
Java Programs 1.)Write a program to convert rupees to dollar. 60 rupees=1 dollar. class Demo public static void main(string[] args) System.out.println("Dollar to rupee converion,enter dollar:"); int rs
More informationExercise 4: Loops, Arrays and Files
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
More informationSection 2.2 Your First Program in Java: Printing a Line of Text
Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two
More informationIntroduction to Computer Science Unit 2. Exercises
Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the
More informationUniversità degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M
Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware
More informationIST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:
IST 297D Introduction to Application Programming Chapter 4 Problem Set Name: 1. Write a Java program to compute the value of an investment over a number of years. Prompt the user to enter the amount of
More informationSection 2.2 Your First Program in Java: Printing a Line of Text
Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two
More informationExperiment Objectives. 2. Preparation. 3. Tasks. 3.1 Task A: String to Integer Conversion
Experiment 3 1. Objectives In this experiment, you will learn more AVR instructions by writing AVR assembly programs to do string-to-number conversion, positional multiplication, positional division, and
More informationCS 177. Lists and Matrices. Week 8
CS 177 Lists and Matrices Week 8 1 Announcements Project 2 due on 7 th March, 2015 at 11.59 pm Table of Contents Lists Matrices Traversing a Matrix Construction of Matrices 3 Just a list of numbers 1D
More informationLecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18
Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical
More informationCOMPUTER SCIENCE. 4. Arrays. Section 1.4.
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 4. Arrays Section 1.4 http://introcs.cs.princeton.edu Basic building blocks for programming any program you might want to write objects functions and modules
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationQUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop
QUIZ: loops Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop QUIZ: loops Write a program that prints the integers from -7 to 15 using: for
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationJava Console Input/Output The Basics. CGS 3416 Spring 2018
Java Console Input/Output The Basics CGS 3416 Spring 2018 Console Output System.out out is a PrintStream object, a static data member of class System. This represents standard output Use this object to
More informationCS141 Programming Assignment #5
CS141 Programming Assignment #5 Due Wednesday, Nov 16th. 1) Write a class that asks the user for the day number (0 to 6) and prints the day name (Saturday to Friday) using switch statement. Solution 1:
More informationTopics. 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 informationMatrices. Jordi Cortadella Department of Computer Science
Matrices Jordi Cortadella Department of Computer Science Matrices A matrix can be considered a two-dimensional vector, i.e. a vector of vectors. my_matrix: 3 8 1 0 5 0 6 3 7 2 9 4 // Declaration of a matrix
More informationH212 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 informationCSE 230 Intermediate Programming in C and C++ Arrays and Pointers
CSE 230 Intermediate Programming in C and C++ Arrays and Pointers Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Definition: Arrays A collection of elements
More informationGetting started with Java
Getting started with Java by Vlad Costel Ungureanu for Learn Stuff Programming Languages A programming language is a formal constructed language designed to communicate instructions to a machine, particularly
More informationBASIC INPUT/OUTPUT. Fundamentals of Computer Science
BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.
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 informationJava Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari
9/28/8 Java Arrays What could go wrong here? int table[][] = new int[2][]; // some code int sum = ; for (int i = ; i < 2; i++) for (int j = ; j < ; j++) int value = table[i][j]; sum += value; Mohammad
More informationSupplementary Test 1
Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Supplementary Test 1 Question
More informationObject Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang
Object Oriented Programming and Design in Java Session 2 Instructor: Bert Huang Announcements TA: Yipeng Huang, yh2315, Mon 4-6 OH on MICE clarification Next Monday's class canceled for Distinguished Lecture:
More informationProblems with simple variables
Problems with simple variables Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Example problem: Read one hundred numbers,
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationRecitation: 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 informationChapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming
Lecture slides for: Chapter 6 Arrays Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 28. ISBN: 978-1-84448-933-2 http://www.ii.uib.no/~khalid/jac/
More informationJava Console Input/Output The Basics
Java Console Input/Output The Basics Lecture 3 COP 3252 Summer 2017 May 23, 2017 Console Output System.out out is a PrintStream object, a static data member of class System. This represents standard output
More informationFall 2005 CS 11 Final exam Answers
Fall 2005 CS 11 Final exam Answers 1. Question: (5 points) In the following snippet of code, identify all places where type casting would occur automatically or would need to occur through a forced cast.
More informationTutorial about Arrays
Q1: Write Java statements that do the following: Reviewed Tutorial about Arrays a. Declare an array alpha of 15 components of the type int int alpha[] = new int[15]; b. Print the value of the tenth component
More information2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?
COSC 117 Final Exam Spring 2011 Name: Part 1: Definitions & Short Answer (3 Points Each) 1. What do CPU and ALU stand for? 2. What are the two main components to the CPU and what do each of them do? 3.
More informationCPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms
CPSC 319 Week 2 Java Basics Xiaoyang Liu xiaoyali@ucalgary.ca & Sorting Algorithms Java Basics Variable Declarations Type Size Range boolean 1 bit true, false char 16 bits Unicode characters byte 8 bits
More informationSCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming
s SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177 Programming Time allowed: THREE hours: Answer: ALL questions Items permitted: Items supplied: There is
More informationM105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014
M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case
More informationAdvanced Java Concept Unit 1. Mostly Review
Advanced Java Concept Unit 1. Mostly Review Program 1. Create a class that has only a main method. In the main method create an ArrayList of Integers (remember the import statement). Add 10 random integers
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
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 informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationSystem.out.printf("Please, enter the value of the base : \n"); base =input.nextint();
CS141 Programming Assignment #6 Due Thursday, Dec 1st. 1) Write a method integerpower(base, exponent) that returns the value of base exponent For example, integerpower(3, 4) calculates 34 (or 3 * 3 * 3
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More information1. Find the output of following java program. class MainClass { public static void main (String arg[])
1. Find the output of following java program. public static void main(string arg[]) int arr[][]=4,3,2,1; int i,j; for(i=1;i>-1;i--) for(j=1;j>-1;j--) System.out.print(arr[i][j]); 1234 The above java program
More informationLecture 5: Matrices. Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur
Lecture 5: Matrices Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur 29 th July, 2008 Types of Matrices Matrix Addition and Multiplication
More informationData Structures COE 312 ExamII Preparation Exercises
Data Structures COE 312 ExamII Preparation Exercises 1. Patrick designed an algorithm called search2d that can be used to find a target element x in a two dimensional array A of size N = n 2. The algorithm
More informationInterpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled
Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac
More informationComputer Programming: C++
The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function
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 informationInf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin
Inf1-OOP Arrays 1 Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin January
More informationObject-Oriented Programming in Java
CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio
More informationAP Computer Science Unit 1. Programs
AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated
More informationFull file at
Chapter 2 Introduction to Java Applications Section 2.1 Introduction ( none ) Section 2.2 First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler
More informationFinal Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017
Your Name: Final Exam. CSC 121 Fall 2017 Lecturer: Howard Rosenthal Dec. 13, 2017 The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have indicated
More informationInf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics
Inf1-OOP Arrays 1 Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics January 11, 2015 1 Thanks to Sedgewick&Wayne for much of this content Arrays Introduction to Arrays Arrays
More informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
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 informationMcGill 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 informationWarm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2
Warm up Exercise What are the types and values of the following expressions: 3.0+4 * (3 + 1) 3 / 2 + 1.0 1.0 / 2.0 (int)1.0 / 2 COMP-202 - Programming Basics 1 Warm up Exercise What are the types and values
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More information