Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

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

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

Introduction to the Java Basics: Control Flow Statements

Iteration statements - Loops

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Repetition, Looping. While Loop

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Loops. CSE 114, Computer Science 1 Stony Brook University

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II

Chapter 4: Control structures. Repetition

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

More Programming Constructs -- Introduction

Chapter 4: Control structures

Top-Down Program Development

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CompSci 125 Lecture 11

Repetition CSC 121 Fall 2014 Howard Rosenthal

The Java language has a wide variety of modifiers, including the following:

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Introduction to Java & Fundamental Data Types

The Basic Parts of Java

Prof. Navrati Saxena TA: Rochak Sachan

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Loops / Repetition Statements

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Example: Monte Carlo Simulation 1

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

Control Structures in Java if-else and switch

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

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

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

Repetition Structures

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

Programming with Java

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Repetition, Looping CS101

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

Programming for Engineers Iteration

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

JAVA OPERATORS GENERAL

STUDENT LESSON A12 Iterations

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Question: Total Points: Score:

What did we talk about last time? Examples switch statements

Chapter 3. Selections

CMPT 125: Lecture 4 Conditionals and Loops

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Course Outline. Introduction to java

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Operators in java Operator operands.

LECTURE 5 Control Structures Part 2

204111: Computer and Programming

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

COMP-202 Unit 4: Programming with Iterations

Control Structures in Java if-else and switch

CS313D: ADVANCED PROGRAMMING LANGUAGE

REPETITION CONTROL STRUCTURE LOGO

Warmup : Name that tune!

Control Statements. Musa M. Ameen Computer Engineering Dept.

Last Class. While loops Infinite loops Loop counters Iterations

Introduction. C provides two styles of flow control:

Recap: Assignment as an Operator CS 112 Introduction to Programming

More on control structures

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Bjarne Stroustrup. creator of C++

Chapter 4: Loops and Files

CS1150 Principles of Computer Science Loops (Part II)

Object Oriented Programming. Java-Lecture 6 - Arrays

C++ Programming: From Problem Analysis to Program Design, Third Edition

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Introduction to Computer Science Unit 2. Notes

Flow Control. CSC215 Lecture

Important Java terminology

Chapter Goals. Contents LOOPS

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

COMP 202 Java in one week

CS 112 Introduction to Programming

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Object-Oriented Programming

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Full file at

Warm-Up: COMP Programming with Iterations 1

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

Transcription:

Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October 2007 Ariel Shamir 1 Method Call System.out.print( hello ); Is a call to the (static) method print of some class (System.out). The usual syntax is: <classname>.<methodname>(<parameters>); When you are inside the same class as the method called, there is no need to use the class name. 27 October 2007 Ariel Shamir 2 Method Parameters If the method requires parameters, they come inside the parentheses as a list. The order and type of parameters must be the same as required by the method. System.out.println(... ) Requires one parameter of type String. 27 October 2007 Ariel Shamir 3 1

Math Methods double d1, d2, d3, d4, d5; d2 = 99.7; d1 = Math.ceil(d2); d3 = Math.sqrt(d1); d4 = Math.sin(Math.PI*2); d5 = Math.min(d1,d3); 27 October 2007 Ariel Shamir 4 Statements We Know int number = 0; // declaration statement number = 25; // assignment statement System.out.println( hello ); // method call int i = myscanner.nextint(); //? 27 October 2007 Ariel Shamir 5 Control Structures and Statements There are several types of statements: Declaration statements Assignment statement Method call statement Expression statements Iteration statements Selection statements Control flow statements 27 October 2007 Ariel Shamir 6 2

Control Flow Statements The control structures affect the flow of control in a program. Control flow statements can be divided into two types: selection statements iteration statements if switch for while do while 27 October 2007 Ariel Shamir 7 If & If..Else Statements statement statement false If? true statement true If..else? false statement statement statement statement 27 October 2007 Ariel Shamir 8 Switch Statement The switch statement is a choice between doing several things (usually more then two things). The switch statement evaluates an expression, then attempts to match the result to one of a series of values. Execution transfers to statement list associated with the first value that matches. 27 October 2007 Ariel Shamir 9 3

Switch Syntax switch(exp){ case value1: statement1; break; case valuen: statementn; break; default: defaultstatement; break; 27 October 2007 Ariel Shamir 10 Choice of Execution If the value of exp equals to value1 then statement1 is performed. If the value of exp equals to valuen then statementn is performed. If the value of exp is different from value1,..., valuen then defaultstatement is performed. 27 October 2007 Ariel Shamir 11 Switch Statement Details exp can be an integer variable or an expression that evaluate to an integer value. statementn can be empty or can be a set of instructions. A default case can be added to the end of the list of cases, and will execute if no other case matches. 27 October 2007 Ariel Shamir 12 4

The Break Statement The break statement is usually used to terminate the statement list of each case. This causes the control to jump to the end of the switch statement and continue. Note: if the break statement is omitted execution continues ( falls ) to the next case! 27 October 2007 Ariel Shamir 13 Example switch(item) { case 0: case 1: // do something break; default: // do something break; case 2: // do something break; case 8: // do something break; 27 October 2007 Ariel Shamir 14 Example switch(letter) { case a : System.out.println( The letter was a ); add(); break; case d : System.out.println( The letter was d ); delete(); break; default: System.out.println( Illegal input ); break; 27 October 2007 Ariel Shamir 15 5

More Operators Conditional (ternary? : ) Assignment (binary += ) Increment & decrement (unary ++) 27 October 2007 Ariel Shamir 16 The Conditional Operator The conditional operator evaluates a Boolean condition that determines which of two expressions is evaluated. condition? exp1 : exp2 If condition is true, exp1 is evaluated; if it is false, exp2 is evaluated. The result of the chosen expression is the result of the entire conditional operator. 27 October 2007 Ariel Shamir 17 Conditional Operator Usage The conditional operator is similar to an if-else statement, except that it is an expression that returns a value: int max = (a > b)? a : b; If a is greater that b, then a is assigned to max; otherwise, b is assigned to max. The conditional operator is ternary, meaning it requires three operands 27 October 2007 Ariel Shamir 18 6

Conditional Operator Example System.out.println ("Your change is " + count + ((count == 1)? Shekel" : " Shekels )); If count equals 1, Shekel" is printed, otherwise Shekels" is printed The conditional operator can be nested: int max = (a > b)? ((a > c)? a : c) : ((b > c)? b : c) ; 27 October 2007 Ariel Shamir 19 More Assignment Operators Often we perform an operation on a variable, then store the result back into that variable. Java provides assignment operators that do just this. Instead of : sum = sum + value; you can write: sum += value; 27 October 2007 Ariel Shamir 20 Assignment Operators List Operator += -= *= /= %= = &= Example x += y; x -= y; x *= y; x /= y; x %= y; x = y; x &= y; Equivalent To x = x + y; x = x y; x = x * y; x = x / y; x = x % y; x = x y; x = x & y; 27 October 2007 Ariel Shamir 21 7

Right Hand Side Expression The right hand side of an assignment operator can be a complete expression. The entire right-hand expression is evaluated first, then combined with the additional operation. result /= (total-min) % n; is NOT equivalent to: result = result/(total-min) % n; but equivalent to result = result / ((total-min) % n); 27 October 2007 Ariel Shamir 22 Unary Increment and Decrement Operators The ++ and -- are the increment and decrement operators. For example the expression j++ is equivalent to j=j+1. The increment and decrement operators can be used as: Prefix appears before what they operate on. Postfix appears after what they operate on. 27 October 2007 Ariel Shamir 23 Increment, Decrement Operators Usage Operator Use Description ++ ++ -- -- j++ ++j j-- --j evaluates to the value of j before it was incremented increments j by 1 increments j by 1 evaluates to the value of j after it was incremented evaluates to the value of j before it was decremented decrements j by 1 decrements j by 1 evaluates to the value of j after it was decremented 27 October 2007 Ariel Shamir 24 8

Inc/Dec Example class IncDecExample { public static void main(string args[]) { int i0,i1,i2,j=5; i0 = ++j; i1 = j++; i2 = j--; System.out.println(i0+ +i1 + +i2); 27 October 2007 Ariel Shamir 25 Inc/Dec Example (Cont) The output is: 6 6 7 i0 = ++j; j is pre-incremented to 6 and assigned to i0. i1 = j++; j is first assigned to i1 (as 6) and then post-incremented to 7. i2 = j--; j with a value of 7 is assigned to i2 and then post-decremented to 6. 27 October 2007 Ariel Shamir 26 More Control Flow What if we want to repeat some sequence of statements many times? statement statement statement statement 27 October 2007 Ariel Shamir 27 9

Iteration Statements Iteration statements are also called loop control structures. A loop is a repetition of certain pieces of the code several times. In Java there are Three types of Loops: for loop, while loop, do loop. 27 October 2007 Ariel Shamir 28 For Statement for( start; limit; step_exp) { statement; start is a statement that initializes the loop. limit is a Boolean statement that determines when to terminate the loop. It is evaluated before each iteration. 27 October 2007 Ariel Shamir 29 For Statement (Cont.) When limit is true statement is performed, when it is false the loop is terminated. step_exp is an expression that is invoked after each iteration of the loop and is called the step of the loop. The for loop is often used for counting from start to limit by a step size. 27 October 2007 Ariel Shamir 30 10

For Diagram Start Limit Condition true false Statement Step 27 October 2007 Ariel Shamir 31 For Example class For_Example { public static void main(string[] args){ int fact = 1; for(int k=1; k<5; k++) { fact *= k; System.out.println( The factorial of + k + is: + fact); 27 October 2007 Ariel Shamir 32 While Statement while( Boolean_cond) statement; The value of Boolean_cond can be: true and than the statement is performed false and than loop terminates The statement is executed over and over until the boolean_condition becomes false. 27 October 2007 Ariel Shamir 33 11

While Diagram Boolean Condition false true Statement 27 October 2007 Ariel Shamir 34 While Example class While_Example { public static void main(string[] args){ int sum=0,k=0; while(sum<100) { sum=sum+k; System.out.print( the sum of 0 to + k + is + sum); k++; 27 October 2007 Ariel Shamir 35 Do.. While Statement do { statement; while (Boolean_cond); First, the statement performed once! Then, the Boolean_cond is checked. If it is true the next iteration of the loop is performed. If it is false, the loop terminates. 27 October 2007 Ariel Shamir 36 12

Do.. While Diagram Statement true Boolean Condition false 27 October 2007 Ariel Shamir 37 Infinite Loops If Boolean_cond in one of the loop structures is always true then loop will be executed forever - it is unbounded. Such a loop is called an infinite loop. The infinite loop will execute until the program is interrupted. 27 October 2007 Ariel Shamir 38 Infinite Loop Example // Two infinite loops program Class Infinity { public static void main(string[] args){ int count=0; for( ; ; ) System.out.print( Infinity ); while(count<10) { System.out.println( Another infinite loop ); System.out.println( The counter is +counter); 27 October 2007 Ariel Shamir 39 13

Nested Loops Example for (int row = 1; row <= numrows; row++) { for (int column = 1; column <= numcolumns; column++) { System.out.print(row * column + ); System.out.println(); Can you make this code more efficient? 27 October 2007 Ariel Shamir 40 Break inside a Loop The break statement, (already used within the switch statement), can also be used inside a loop When the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again) 27 October 2007 Ariel Shamir 41 Continue inside a Loop A similar statement to the break is continue inside loops When the continue statement is executed, control jumps to the end of the loop and the condition is evaluated (possibly entering the loop statements again) 27 October 2007 Ariel Shamir 42 14

Break and Continue Example for (;;) { Scanner sc = new Scanner(System.in); int n = sc.nextint(); if (n == 0) break; if (n%2 == 1) continue; sum += n; System.out.print( Can you modify it to get rid of the break and continue? The sum of all input even numbers is + sum); 27 October 2007 Ariel Shamir 43 Division Into Methods Complicated tasks or tasks that occur often within a class should be wrapped in a method It is helpful when implementing algorithms, or when we need helper methods in classes. This will increase the readability and manageability of the code 27 October 2007 Ariel Shamir 44 Sub Tasks Example Task: calculate & print the average and median of all students: Get the grades of a student Calculate the average Calculate the median Outer Loop On Students Inner Loops On Grades 27 October 2007 Ariel Shamir 45 15

Sub Tasks Example Task: calculate & print the average and median of all students: Get the grades of a student Calculate the average Calculate the median Outer Loop On Students Define as methods 27 October 2007 Ariel Shamir 46 Defining Methods Simplify and structure the program code using sub-tasks Reuse of the same piece of code (the method) in many places 27 October 2007 Ariel Shamir 47 Example 1: Finding Primes // Prints all the prime numbers in a range public class Primes { public static final int RANGE = 1000; public static void main(string[] args) { int number = 0; while (number < RANGE) { number = number + 1; for (int n = 0 ; n < number ; n++) { //...check if n divides number... 27 October 2007 Ariel Shamir 48 16

Example 1 (Cont.) // Prints all the prime numbers in a range public class Primes { public static final int RANGE = 1000; public static void main(string[] args) { int number = 0; while (number < RANGE) { number = number + 1; if (isprime(number)) out.println(number); 27 October 2007 Ariel Shamir 49 Example 1 (Cont.) // Prints all the prime numbers in a range public class Primes { public static void main(string[] args) { //... if (isprime(number)) //... // Returns true iff number is prime public static boolean isprime(int number) { // determines if number is prime 27 October 2007 Ariel Shamir 50 Example 2: Magic Number A magic number is a number who s sum of cubes of digits equals itself: XYZ = X 3 + Y 3 + Z 3 Finding all magic numbers in the range 1-M: For each n in the range 1-M: Compute the sum of cubes of digits of n Check if this sum equals n 27 October 2007 Ariel Shamir 51 17

SumofCubes Method Finding all magic numbers in the range 1-M: For each n in the range 1-M: Compute the sum of cubes of digits of n Check if this sum equals n /** * Returns the sum of cubes of digits of n */ static int sumofcubesofdigits(int n) { // 27 October 2007 Ariel Shamir 52 Method Header We declare methods in a similar way to the way the method main was declared: public static void main(string[] args) { // the code public static double average(int num1,int num2) { // the code return type name parameters 27 October 2007 Ariel Shamir 53 Methods Modifiers The modifier public denotes that the method is exposes to outside world (more on this later) The modifier static denotes that this method can be called without creating an object of this type (more on this too, later) 27 October 2007 Ariel Shamir 54 18

Return Types The return type of a method indicates the type of value that the method sends back to the calling client. The return-type of average() is double. When a client calls the method average() it will get the answer as a double value. The keyword void denotes that the method has no return value (main()) 27 October 2007 Ariel Shamir 55 Method Return Types public static double average(int num1,int num2) {... public static int sumofcubesofdigits(int n) {... public static boolean isprime(int number) {... public static void main(string[] args) {... 27 October 2007 Ariel Shamir 56 Return Statement return <expression>; In the method definition, the return statement specifies the value that should be returned, which must conform with the return type of the method. If the method returns void you can just use return; or you can omit the statement (and reach the end of all the method statements) 27 October 2007 Ariel Shamir 57 19

Using the Return Value double avg; // more code avg = average(33,56); The parameters sent to average It will return a value which is assigned to avg The average method will be invoked 27 October 2007 Ariel Shamir 58 Method Parameters To invoke a method you must use the correct 1. Number of parameters 2. Type of parameters 3. Order of parameters Sometimes there are several methods with the same name be careful! 27 October 2007 Ariel Shamir 59 Passing Parameters When a parameter is passed, a copy of the value is made and assigned to the formal parameter: double avg; avg = average(33,56); public static double average(int num1,int num2) 27 October 2007 Ariel Shamir 60 20

Code Example Parameters can be used as any other variable The return expression must match the return type public static double average(int num1,int num2) { return (num1 + num2)/2.0; 27 October 2007 Ariel Shamir 61 Method control flow Instead of writing a long list of instructions we write a collection of methods and invoke (or call) them one after another. main() Main invokes M1 M1 invokes M2 Main invokes M1()... M2() 27 October 2007 Ariel Shamir 62 Control Flow Chart We decomposed a problem into series of simpler methods. The invoked method could be part of another class or object. main M1 M2 obj.m1(); M2(); 27 October 2007 Ariel Shamir 63 21

The Random Class A program may need to produce a random number (DiceSimulation.java). The Random class provides methods to simulate a random number generator. The nextint method returns a random number from the entire spectrum of int values. Usually, this number is be scaled and shifted to the desired range. 27 October 2007 Ariel Shamir 64 Random Class Example import java.util.random; // This program simulates a tossing of a dice class DiceSimulation { static final int NUMBER_OF_TOSSES = 10; public static void main(string[] args) { int sum = 0; int count = 0; Random rndgen = new Random(); 27 October 2007 Ariel Shamir 65 Random Class Example while(count<=number_of_tosses) { int result = Math.abs(rndGen.nextInt())%6+1; sum = sum + result; count = count + 1; System.out.println( The sum of tosses is +sum); 27 October 2007 Ariel Shamir 66 22