CS 106 Introduction to Computer Science I

Similar documents
CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Introduction to Programming

CS 106 Introduction to Computer Science I

C Programming for Engineers Functions

Introduction to Computer Science Unit 2. Notes

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Object Oriented Methods : Deeper Look Lecture Three

CS 106 Introduction to Computer Science I

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Java Classes: Math, Integer A C S L E C T U R E 8

Methods (Deitel chapter 6)

Mobile App:IT. Methods & Classes

CS 106 Introduction to Computer Science I

Methods (Deitel chapter 6)

Lecture 04 FUNCTIONS AND ARRAYS

Full file at

CS 106 Introduction to Computer Science I

Chapter 3 - Functions

Lecture 5: Methods CS2301

CT 229 Java Syntax Continued

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

1001ICT Introduction To Programming Lecture Notes

CS Programming I: Primitives and Expressions

Introduction to Computer Science Unit 2. Notes

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

The Math Class. Using various math class methods. Formatting the values.

CS 206 Introduction to Computer Science II

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Variables. location where in memory is the information stored type what sort of information is stored in that memory

1 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

C++ Programming Lecture 11 Functions Part I

Array. Prepared By - Rifat Shahriyar

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

AP CS Unit 3: Control Structures Notes

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Topics. Chapter 5. Equality Operators

CS110D: PROGRAMMING LANGUAGE I

CS 206 Introduction to Computer Science II

CS 231 Data Structures and Algorithms, Fall 2016

CS111: PROGRAMMING LANGUAGE II

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Methods

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

C Functions. 5.2 Program Modules in C

CS111: PROGRAMMING LANGUAGE II

Programming Exercise 7: Static Methods

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

BM214E Object Oriented Programming Lecture 4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

CS112 Lecture: Working with Numbers

CS 206 Introduction to Computer Science II

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Reviewing all Topics this term

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

CS110: PROGRAMMING LANGUAGE I

Functions and Recursion

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 2: Data and Expressions

Pace University. Fundamental Concepts of CS121 1

CSc Introduction to Computing

Course PJL. Arithmetic Operations

&KDSWHU$UUD\VDQG9HFWRUV

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Variables and data types

Methods CSC 121 Spring 2017 Howard Rosenthal

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

M e t h o d s a n d P a r a m e t e r s

( &% class MyClass { }

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

STUDENT LESSON A12 Iterations

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

What did we talk about last time? Examples switch statements

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

Lesson 05 Methods. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CIS 110: Introduction to Computer Programming

Control Structures in Java if-else and switch

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CSE123. Program Design and Modular Programming Functions 1-1

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Transcription:

CS 106 Introduction to Computer Science I 02 / 21 / 2014 Instructor: Michael Eckmann

Today s Topics Comments and/or Questions? Arrays multidimensional Math class methods Programmer defined methods Michael Eckmann - Skidmore College - CS 106 - Spring 2014

Two dimensional arrays int student_hw_grades [] [] = new int [ 17 ] [ 10 ]; // The outer loop will be for the 17 students and the inner loop will // be for the 10 hw's. for (int row = 0; row < array2d.length; row++) { for (int col = 0; col < array2d[row].length; col++) { user_str = JOptionPane.showInputDialog( "Enter student " + row + "'s homework #" + col + "grade"); } student_hw_grades[ row ] [ col ] = Integer.parseInt(user_str); } // note the use of.length in the two loop conditions

Multi-dimensional arrays Not only can we have one dimensional, and two dimensional arrays but we can have n dimensional arrays, where n is any positive integer. Example when n=3: double temperatures[][][] = new double [12][31][24]; take a guess as to what might be stored in this array and what the indices mean

Multi-dimensional arrays Unfortunately the first index must go from 0 to 11, the second from 0 to 30 and the third from 0 to 23. What if we wanted the index to represent exactly the month (1 to 12), day (1 to 31) and hour (0 to 23)? Is there anything we could do to this line? double temperatures[][][] = new double [12][31][24];

Math class Let's look at the Java API for the Math class. Specifically these methods: abs guess what this does. cos, sin, tan ceil returns smallest whole number >= parameter. pow takes two parameters raises first to second and returns the result. random returns random # in the range: [0.0, 1.0) sqrt Michael Eckmann - Skidmore College - CS 106 - Spring 2014

A few more methods in the Math class max ( x, y ) method that returns the larger of x and y min ( x, y ) method that returns the smaller of x and y There are versions of these methods that work for x and y being floats, doubles, ints and longs and return a result that is same type.

example calls to static methods in the Math class double w = 5.1, z = 10.56, a, b, c; a = Math.max ( w, z ); // what value would a have? a = Math. max ( z, w ); // what value would a have, now? b = Math. min ( z, w ); c = Math. sqrt ( z );

random( ) method in the Math class double rand_num; rand_num = Math.random ( ); // what value might rand_num have after this line of code? // is 0.34452 a possible value? // is 2 a possible value? // is -14.555423 a possible value?

random( ) method in the Math class random ( ) returns a double whose value is >= 0 and < 1, but sometimes we want a random integer How might we do that?

random( ) method in the Math class random ( ) returns a double whose value is >= 0 and < 1, but sometimes we want a random integer One way to do that is to first multiply the result by some integer to get a value that isn t necessarily between 0 and 1. Then, cast this new value to an int by using the (int) cast operator.

random( ) method in the Math class // example: int some_random_int; double some_random_dbl; some_random_dbl = Math.random ( ) * 25; // this will result in a value >= 0 and < 25. some_random_int = (int) (Math.random ( ) * 25); // what is the range of values for some_random_int here?

random( ) method in the Math class int random_card_value; int random_card_suit; random_card_value = 1 + (int) (Math.random ( ) * 13); random_card_suit = (int) (Math.random ( ) * 4); Let s put this code in a program and execute it.

random( ) method in the Math class What if I put the cast to int without using parentheses around the rest of the expression? e.g. random_card_suit = (int) Math.random ( ) * 4;

random( ) method in the Math class What if I put the cast to int without using parentheses around the rest of the expression? e.g. random_card_suit = (int) Math.random ( ) * 4; since the cast operator (int) has higher precedence than the multiplication operator *, it would be done first, which means what?

random( ) method in the Math class random_card_suit = (int) Math.random ( ) * 4; the Math.random() method call would return a double value and immediately this value would be cast to an int. Casting a double to an int causes the truncation of any decimal portion. Recall that the double that is returned by Math.random() is >= 0.0 and < 1.0 So, what's the possible values of (int) Math.random()?

random( ) method in the Math class (int) Math.random( ) would always be zero.

what is a method A method is small piece of a program designed to achieve some specific task and usually returns some piece of information. A method is invoked by a method call. To call a method, you provide its name and the correct arguments that are necessary for the method to execute. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

methods Here s a good analogy of a worker and boss to describe methods and their callers. A boss (the caller) asks a worker (the method that is called) to perform a task (the code in the method) and report (return results) back when the task is done. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

methods All methods are defined within some class. we have seen the main method defined in the class of every application so far. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

other methods we ve used We have used other methods available in the Java API, methods like parseint and parsefloat and println are available to us to use in their respective classes Integer, Float and System.out The methods in the Math class are other examples. These methods were defined for us to do a specific task. We call them when we need them. e.g. in the case of Integer.parseInt --- it s task is to convert a String into an int. It takes a String as an argument (parameter) and returns a value of type int. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

other methods we ve used e.g. in the case of Integer.parseInt --- it s task is to convert a String into an int. It takes a String as an argument (parameter) and returns a value of type int. example of a call to this method: some_int = Integer.parseInt( some_str ); In this example, some_str is the argument that is being passed in to the parseint method and some_int is the variable that will get set to the value returned by the method. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

methods We can create our own methods that we can call to perform specific tasks. Let s say we re writing a program to handle employee s salaries. We might need to compute a salary after a raise. This example method would need to have access to the current salary and the raise percentage. It would then calculate the salary after the raise and return this value. Michael Eckmann - Skidmore College - CS 106 - Spring 2014

example of a programmer-defined method we might name this method salary_after_raise we need to take in two values, one for the current salary and one for the raise percentage. What primitive type might these be? we also need to return the salary that is computed. What primitive type might this returned value be? Michael Eckmann - Skidmore College - CS 106 - Spring 2014

example of a programmer-defined method so, this method could look like: public static double salary_after_raise(double curr_sal, double raise_pct ) { double new_sal; new_sal = curr_sal * ( 1 + raise_pct / 100 ); } return new_sal; Michael Eckmann - Skidmore College - CS 106 - Spring 2014

example of a programmer-defined method to call this method from some other method within the same class do the following: // example variable declarations... double new_salary; double old_sal = 35000; double raise = 4.5; // our call to the salary_after_raise method new_salary = salary_after_raise( old_sal, raise ); Michael Eckmann - Skidmore College - CS 106 - Fall 2010

example of a programmer-defined method Let s look at a complete program that contains this method and calls it several times. Michael Eckmann - Skidmore College - CS 106 - Fall 2010

example of a programmer-defined method When certain code can be used in several places in a program, you may want to create a method containing that code. Then, wherever that code would have been, a simple method call appears. Programmer defined methods also aid in the ability to understand a program (readability) and make changes (maintainability). Michael Eckmann - Skidmore College - CS 106 - Fall 2010

when does a method end it s execution? when it hits a return; statement when it hits a return some_expression; statement or, when it hits the right curly brace of the method whichever comes first. when the method ends its execution, the program execution continues back at the method call (from where the method was called)

more about methods methods that do not return a value are of type void (like the main method.) Methods can have 0 or more parameters separated by commas. Those with 0 parameters are defined with nothing between the parentheses to call a method with no parameters, you must still use the parentheses but with nothing between them Note that the return type of a method can be different than any or all of the types of parameters that get passed in.

example method that returns nothing and has no parameters public static void print_error_msg() { System.out.println( Invalid entry. ); System.out.println( You must reenter. ); } how to call this method: note that there are no arguments passed in nor is there a variable to which to assign the returned value (because it doesn t return a value.) print_error_msg();

example method that returns nothing but has one parameter public static void print_msg(string the_msg) { System.out.println( The message is: + the_msg); // note: no return statement since nothing to return // The return type of this method is void. } how to call this method: print_msg( Good afternoon gentlemen. I am a HAL 9000 computer. );

example method that returns a String but has no parameters public static String random_string() { int num = (int) (Math.random() * 3); if (num == 0) return Hello ; if (num == 1) return Goodbye ; if (num == 2) return $#@&!* ; } how to call this method: System.out.println( the random string is: + random_string());

reasons to create and use methods separation and modularization of ideas is helpful when writing large programs because smaller parts of a problem are easier to solve the individual methods can be tested and confirmed correct to reduce debugging woes methods lend themselves to software reuse less code repetition more readable, better designed code