EXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W

Similar documents
Exercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012

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

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

Fundamentals of Programming Data Types & Methods

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Arrays. Eng. Mohammed Abdualal

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Program Fundamentals

Full file at

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

COE318 Lecture Notes Week 4 (Sept 26, 2011)

PROGRAMMING FUNDAMENTALS

CHAPTER 7 OBJECTS AND CLASSES

Selected Questions from by Nageshwara Rao

Example: Computing prime numbers

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Lexical Considerations

Instructor: Eng.Omar Al-Nahal

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Chapter 6 Introduction to Defining Classes

( &% class MyClass { }

CS 231 Data Structures and Algorithms, Fall 2016

Lecture Set 4: More About Methods and More About Operators

Lecture Set 4: More About Methods and More About Operators

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

CHAPTER 7 OBJECTS AND CLASSES

THE CONCEPT OF OBJECT

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Software and Programming 1

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

3. Java - Language Constructs I

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computational Expression

Getting started with Java

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

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Array. Prepared By - Rifat Shahriyar

Array. Array Declaration:

Programming with Java

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

Introduction to Programming Using Java (98-388)

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

1 Lexical Considerations

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Introduction to Java

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Java Bytecode (binary file)

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Chapter 9 Introduction to Arrays. Fundamentals of Java

Motivation was to facilitate development of systems software, especially OS development.

Java Coding 3. Over & over again!

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CSC Java Programming, Fall Java Data Types and Control Constructs

Exercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

COP 3330 Final Exam Review

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Lexical Considerations

DM550 Introduction to Programming part 2. Jan Baumbach.

PieNum Language Reference Manual

Defining Classes and Methods

Simple Java Reference

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

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

Chapter 2: Using Data

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

COMP6700/2140 Data and Types

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Introduction to Object-Oriented Programming

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Software and Programming 1

Programming Lecture 3

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Motivation was to facilitate development of systems software, especially OS development.

Building Java Programs

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

COMP 202 Java in one week

Example: Monte Carlo Simulation 1

An overview of Java, Data types and variables

CS171:Introduction to Computer Science II

CS 106 Introduction to Computer Science I

Java Primer 1: Types, Classes and Operators

Java Notes. 10th ICSE. Saravanan Ganesh

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Introduction to Java & Fundamental Data Types

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Ex: If you use a program to record sales, you will want to remember data:

CSE 114 Computer Science I

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

Transcription:

EXERCISES SOFTWARE DEVELOPMENT I 04 Arrays & Methods 2018W

Solution First Test

DATA TYPES, BRANCHING AND LOOPS Complete the following program, which calculates the price for a car rental. First, the program reads the user's driving license number ("Führerscheinnummer") and the desired number of days for the rental, until the input is valid. The company has currently a special offer: If a car is rented for full weeks (i.e. exactly 7, 14, 21,.. days), one day per week is for free. Consider the following: The price per day is 30.5. The number of days for a car rental must be greater than 0. Make sure that the license number follows the format 2018xxx, where xxx stands for three arbitrary numbers. Valid examples are therefore 2018000, 2018123 or 2018955, while 2019555 or 123456 are invalid. Use Input.readInt() to read in an integer value. TODO Software Development I // 2018W // 3

DATA TYPES, BRANCHING AND LOOPS Complete the following program, which calculates the price for a car rental. First, the program reads the user's driving license number ("Führerscheinnummer") and the desired number of days for the rental, until the input is valid. The company has currently a special offer: If a car is rented for full weeks (i.e. exactly 7, 14, 21,.. days), one day per week is for free. Consider the following: The price per day is 30.5. The number of days for a car rental must be greater than 0. Make sure that the license number follows the format 2018xxx, where xxx stands for three arbitrary numbers. Valid examples are therefore 2018000, 2018123 or 2018955, while 2019555 or 123456 are invalid. Use Input.readInt() to read in an integer value. Software Development I // 2018W // 4

Arrays in Java (Part I)

ARRAYS :: DATA STRUCTURE Problem: So far only primitive variables (int age, float value, etc.) Data structures for large number of elements Example: Hotel Venetian in Las Vegas has 7128 rooms; Reservation system which room is available? boolean availroom1, availroom2,..., availroom7128; Feasible structures for associated data needed Example: date (14. 11. 2018: day, month, year) int day, month, year - this declaration does not allow to infer the relation between these variables In the given notation, a second date would be declared as int day2, month2, year2 - not very intuitive to read or use Better: The entire date should form a coherent unit 'Date' should be usable as a single parameter like a primitive variable Solution: Arrays An array is a container object that holds a fixed number of values of a single type date-array, availroomsarray, etc. Software Development I // 2018W // 6

I ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Each item in an array is called an element, and each element is accessed by its numerical index The length of an array is established when the array is created; i.e., after creation its length is fixed Example: Declare date as array of three integer values int[] date = new int[3]; // indices from 0 to 2 date[0] = 14; date[1] = 11; assigning values date[2] = 2018; Example 2: Second date array int[] date2 = new int[3]; // a second date Explicit allocation with new operator The array is of type int[] Software Development I // 2018W // 7

ARRAYS :: GENERAL INFORMATION An array has a fixed: Name Type Length Array sizes cannot be changed during the execution of the code Array variables do not contain the array itself, but a reference to a space in the main memory 14 11 2018 date 0 1 2 date has room for three elements (day, month, year) Elements have same data type! The elements are accessed by their index (0 2) In Java, array indices start at 0 (last element = length 1) Length can be determined via date.length Software Development I // 2018W // 8

ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Declaration and initialization can be done separately int[] date; // data array with 3 elements (e.g., day, month, year) date = new int[3]; // not fixed; can be redeclared to store 6 elements, // e.g., day, month, year, hour, minute, second date = new int[6]; // 'old' date array: garbage collector! Initialization can be also done at declaration time int[] date = { 14, 11, 2018 ; // length implicit, fixed int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30, 31 Software Development I // 2018W // 9

ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. Example: Declaration and allocation of an integer array int[] numbers; numbers = new int[100]; Interpretation Each array has: - name - type - length The new operator allocates memory to hold 100 integer values (100 x 32 bits = 100 x 4 bytes = 400 bytes) In Java the new operator initializes all the array elements automatically numeric data types: 0 or 0.0 boolean type: false character types: '\0' reference types: null Software Development I // 2018W // 10

ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Additional examples Declaration only float[] annualrain; char[] text; int[] studnumbers; // A float array // A char array // An int array Declaration + allocation // allocate space for 90 floats float[] annualrain = new float[90]; // allocate space for 10000 characters char[] text = new char[10000]; // allocate space for 100 integers int[] studnumbers = new int[100]; Software Development I // 2018W // 11

ARRAYS :: OPERATING WITH INDICES Declare and initialize an integer array of length 12 which stores the number of days for each month: int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; What about the following statement? daysofmonth[m % 12]; // m-1...current month // (m-1)+1 = m...next month Results in number of days of the next month How many days does a month 'm' have? (1 <= m <= 12) daysofmonth[m - 1]; // [0]...[11] Software Development I // 2018W // 12

ARRAYS :: OPERATING WITH INDICES Declare and initialize an integer array of length 12 which stores the number of days for each month: int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; Array indices does not have to be a fixed integer value; it can be an arbitrary complex expression, e.g., a[i*3/2+3] = j; Software Development I // 2018W // 13

ARRAYS :: INDEXING PROBLEMS 14. 11. 2018 (DIN 1355-1) == November 14, 2018 (US) == 2018-11-14 (ISO 8601) Assignment of month November (11) to the date array date[1] = 11; Which date format, i.e., Day? Month? Year? One has to remember which index stores which value Possible solution: Use constants to refer to indices static final int DAY_INDEX = 0; // or DAY static final int MONTH_INDEX = 1; // or MONTH static final int YEAR_INDEX = 2; // or YEAR Utilization date[day_index] = 14; date[month_index] = 11; date[year_index] = 2018; Software Development I // 2018W // 14

ARRAYS :: GENERAL INFORMATION 'Array' is the first complex (i.e., reference ) data type A variable of primitive data type (int, char, float, etc.) contains its value Array variables do not contain (store) the array itself but reference a space in the main memory (RAM) that was allocated explicitly using the new operator Example: int[] array = new int[10]; or implicitely Example: int[] date = { 14, 11, 2014 ; Consequence: Its not possible to compare arrays (as you compare primitive vars.) if(array1 == array2) {... An array is a list with a fixed size and it contains 1 or more elements of same data type Does not compare array elements but address reference Software Development I // 2018W // 15

ARRAYS :: MEMORY ORGANIZATION int[] daysofmonth = new int[12]; Memory addresses 78 232 232 236 240 244 248 252 256 260 264 268 272 276 0 0 0 0 0 0 0 0 0 0 0 0 daysofmonth array[3] array[7] array[11] Address of the first element of the array in memory array[0] array[1] array[2] array[4] array[5] array[6] array[8] array[10] array[9] Software Development I // 2018W // 16

ARRAYS :: MEMORY ORGANIZATION int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; Memory addresses 78 232 232 236 240 244 248 252 256 260 264 268 272 276 31 28 31 30 31 30 31 31 30 31 30 31 daysofmonth array[3] array[7] array[11] Address of the first element of the array in memory array[0] array[1] array[2] array[4] array[5] array[6] array[8] array[10] array[9] Software Development I // 2018W // 17

ARRAYS :: EXAMPLE Given: A float[] storing X values to describe the rainfall in the last X years Calculate the total and average rainfall over the entire time // Declare and fill the array with the appropriate data float[] annualrain = getannualrain(); float total = 0.0f; for (int year = 0; year < annualrain.length; year++) { // Each array element is a "float" total = total + annualrain[year]; // for year System.out.println("Total: " + total); System.out.println("Average: " + total / annualrain.length); Software Development I // 2018W // 18

ARRAYS :: EXAMPLE Given: A float[] storing X values to describe the rainfall in the last X years Calculate the total and average rainfall over the entire time // Declare and fill the array with the appropriate data float[] annualrain = getannualrain(); float total = 0.0f; for (int year = 0; year < annualrain.length; year++) { // Each array element is a "float" total = total + annualrain[year]; // for year System.out.println("Total: " + total); System.out.println("Average: " + total / annualrain.length); Software Development I // 2018W // 19

ARRAYS :: BOUNDS Remember: Indices range from 0 to length 1 public class ArrayBounds { public static void main(string[] args) { int[] array; // declaration array = new int[10]; // creation for (int i = 1; i < array.length + 1; i++) { array[i] = i * 2; System.out.println(array[i]); Software Development I // 2018W // 20

Methods for Structual Programming Spaghetti code is a pejorative phrase for source code that has a complex and tangled control structure,. It is named such because program flow is conceptually like a bowl of spaghetti, i.e. twisted and tangled. https://en.wikipedia.org/wiki/spaghetti_code

I METHODS :: OVERVIEW Collection of statements that are grouped together to perform a certain operation Examples System.out.println() Input.readInt() Purpose of Methods Reuse code that is frequently used Structuring program code, high level of readability Methods are testable units Verified Units must not be considered in Debugging Divide & Conquer Approach Complex Problems are just a combinations of simple problems Complex Problems are split into sub problems until we can solve them Public static void main(string[] arg) { method(); static void method() { Software Development I // 2018W // 22

I METHODS :: DEFINITION public static int sum(int a, int b) { // method body return a+b; Method declarations have several components Modifiers such as private, public, static etc. Return Type the data type of the value returned by the method, or void Method Name Parameter List A comma-seperated list of input parameters, preceded by their data types, enclosed in parentheses (), or empty parentheses if no parameters Method Body The code, enclosed between braces Naming a method By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase readint(), print(), isempty(),.. Software Development I // 2018W // 23

METHODS :: DEFINITION public static int sum(int a, int b) { // method body return a+b; Calling a method When method is called, program control gets transferred to the called method This called method returns control to the caller in two conditions, Return statement is executed It reaches the method ending brace Examples System.out.println( This method does not have any return value ); int result = sum(5,5); Software Development I // 2018W // 24

METHODS :: DEFINITION public static void printsum(int a, int b) { // method body System.out.println(a+b); Calling a method When method is called, program control gets transferred to the called method This called method returns control to the caller in two conditions, Return statement is executed It reaches the method ending brace Examples System.out.println( This method does not have any return value ); int result = sum(5,5); printsum(5,5); Software Development I // 2018W // 25

METHODS :: STRUCTURING PROGRAM CODE Sum() sum = 0 read( number) while number > 0 sum = sum + number read( number) write( sum) public class Sum { public static void main(string[] args) { int sum = 0; int number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); while (number > 0) { sum = sum + number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); System.out.print("Sum of numbers: "); System.out.println(sum); Repeated Code! Software Development I // 2018W // 26

METHODS :: STRUCTURING PROGRAM CODE Sum() sum = 0 read( number) while number > 0 sum = sum + number read( number) public class Sum { public static void main(string[] args) { int sum = 0; int number; number = enternumber(); while (number > 0) { sum = sum + number; number = enternumber(); System.out.print("Sum of numbers: "); System.out.println(sum); public static int enternumber() { write( sum) Software Development I // 2018W // 27 int number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); return number; Repeated code is now extracted as method

I METHODS :: JAVA SPECIFICATION EXTRACT public static int readint() { {MethodModifier MethodHeader Methodbody Result Identifier ( [FormalParameterList] ) int readint () Attention: If result is not void your method body has to have a return statement. Java Language Specification (Version 8 Page 228) http://docs.oracle.com/javase/specs/jls/se8/jls8.pdf Software Development I // 2018W // 28

I METHODS :: RETURN VALUE public class Input { Result is of Type int // Numbers returned will be within [-2147483648, 2147483647]. public static int readint() { int n = 0; boolean valid = false; do { try { n = Integer.parseInt(nextLine()); valid = true; catch (NumberFormatException e) { System.out.print("Not a valid int, please try again: "); while (!valid); return n; Return value is of Type int Software Development I // 2018W // 29

I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number while number > 0 write( sum) public class Sum { public static void main(string[] args) { // Init int number = 0; int sum = 0; // Read In do { System.out.println("Enter positive number or 0 to quit: "); number = Input.readInt(); sum += number; while (number > 0); // Output printsum(sum); Attention: Program works for number >= 0 but not for number < 0 Software Development I // 2018W // 30

I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number while number > 0 public class Sum { public static void main(string[] args) { // Init int number = 0; int sum = 0; // Read In do { System.out.println("Enter positive number or 0 to quit: "); number = readnumbergreaterorequalzero(); sum += number; while (number > 0); // Output printsum(sum); write( sum) Software Development I // 2018W // 31

I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number private static int readnumbergreaterorequalzero() { int n = 0; n = Input.readInt(); while (n < 0) { System.out.print("Int below zero, please try again: "); n = Input.readInt(); return n; private static void printsum(int sum) { System.out.println("Summe ist: " + sum); while number > 0 write( sum) Software Development I // 2018W // 32

I METHODS :: RE-STRUCTURING CODE Extract Methods Separate Method for each block Consider Return Type Return Value Formal Parameters Actual Parameters Method Modifiers public class CheckDigit { public static void main(string[] args) { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < 100000 baseid > 999999); System.out.printf("Base ID : %d\n", baseid); Software Development I // 2018W // 33

METHODS :: RE-STRUCTURING CODE Extract Methods Return Type int Return Value baseid Formal Parameters None Actual Parameters None Method Modifiers private static public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < 100000 baseid > 999999); return baseid; Software Development I // 2018W // 34

METHODS :: RE-STRUCTURING CODE Extract Methods Return Type void Return Value None Formal Parameters int mybaseid Actual Parameters baseid Method Modifiers private static public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static void printbaseid(int mybaseid) { System.out.printf("Base ID : %d\n", mybaseid); Software Development I // 2018W // 35

O FURTHER REFINEMENT :: GENERALISATION Generalize Methods Think what would change if the digit would have size 5, 7, Consider Return Type Return Value Formal Parameters Actual Parameters Method Modifiers public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < 100000 baseid > 999999); return baseid; Software Development I // 2018W // 36

FURTHER REFINEMENT :: GENERALISATION Generalize Methods Return Type int Return Value baseid Formal Parameters int digits, lower, upper Actual Parameters 6, 100000, 999999 Method Modifiers private static Software Development I // 2018W // 37 public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { return readbaseid(6, 100000, 999999); private static int readbaseid(int digits, int lower, int upper) int baseid = 0; do { System.out.printf("Enter a BaseId with %d digits" baseid = Input.readInt(); +" (no preceding zero): \n", digits); while (baseid < lower baseid > upper); return baseid;

I FURTHER METHODS Multiple Return Values Arrays as a Return Type Manipulate Input Pass-By-Reference Software Development I // 2018W // 38 private static int[] calcsumandaverage(int[] array){ int sum=0; for (int i = 0; i < array.length; i++) { sum+=array[i]; return new int[]{sum,sum/array.length; private static void replacenegative(int[] array, int replace) { for (int i = 0; i < array.length; i++) { if (array[i] < 0) { array[i] = replace;

EXERCISES SOFTWARE DEVELOPMENT I 04 Arrays & Methods 2018W