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

Size: px
Start display at page:

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

Transcription

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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: 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 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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 October 2007 Ariel Shamir 48 16

17 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

18 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

19 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) { 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

20 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

21 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

22 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

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

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

More information

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

Iteration statements - Loops

Iteration statements - Loops Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

More information

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

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

More information

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Chapter 4: Control structures. Repetition

Chapter 4: Control structures. Repetition Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

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

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Chapter 4: Control structures

Chapter 4: Control structures Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

CompSci 125 Lecture 11

CompSci 125 Lecture 11 CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

More information

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

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

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

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

More information

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

Introduction to Java & Fundamental Data Types

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

The Basic Parts of Java

The Basic Parts of Java Data Types Primitive Composite The Basic Parts of Java array (will also be covered in the lecture on Collections) Lexical Rules Expressions and operators Methods Parameter list Argument parsing An example

More information

Prof. Navrati Saxena TA: Rochak Sachan

Prof. Navrati Saxena TA: Rochak Sachan JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

More information

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Example: Monte Carlo Simulation 1

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

Jump 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. 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 information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

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

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

More information

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

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

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

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

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Programming with Java

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

More information

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

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else

More information

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

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

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Jump 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. 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 information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

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

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables Java Program Structure // comments about the class public class MyProgram { Java Review class header class body Comments can be placed almost anywhere This class is written in a file named: MyProgram.java

More information

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

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks: كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this

More information

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that

More information

Question: Total Points: Score:

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

More information

What did we talk about last time? Examples switch statements

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

Chapter 3. Selections

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

More information

CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

More information

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

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Course Outline. Introduction to java

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

More information

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Operators in java Operator operands.

Operators in java Operator operands. Operators in java Operator in java is a symbol that is used to perform operations and the objects of operation are referred as operands. There are many types of operators in java such as unary operator,

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

204111: Computer and Programming

204111: Computer and Programming 204111: Computer and Programming Week 4: Control Structures t Monchai Sopitkamon, Ph.D. Overview Types of control structures Using selection structure Using repetition structure Types of control ol structures

More information

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

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

COMP-202 Unit 4: Programming with Iterations

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

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2016 February 2, 2016 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Warmup : Name that tune!

Warmup : Name that tune! Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Recap: Assignment as an Operator CS 112 Introduction to Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming Recap: Assignment as an Operator CS 112 Introduction to Programming q You can consider assignment as an operator, with a (Spring 2012) lower precedence than the arithmetic operators First the expression

More information

More on control structures

More on control structures Lecture slides for: Chapter 5 More on control structures Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

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

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer

More information

Università 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 Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Bjarne Stroustrup. creator of C++

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

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do-while Loop

More information

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Loops (Part II) CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

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

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection) Control Structures A computer can proceed: In sequence Selectively (branch) - making

More information

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

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

More information

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

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

More information

Introduction to Computer Science Unit 2. Notes

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

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Important Java terminology

Important Java terminology 1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

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

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

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition Statements Animated Version required for reproduction or display. Chapter 6-1 Objectives After you have read and studied this chapter, you should be able to Implement repetition control

More information

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

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths. Loop Control There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first,

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #7: Variable Scope, Constants, and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

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

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

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

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Warm-Up: COMP Programming with Iterations 1

Warm-Up: COMP Programming with Iterations 1 Warm-Up: Suppose I have a method with header: public static boolean foo(boolean a,int b) { if (a) return true; return b > 0; Which of the following are valid ways to call the method and what is the result?

More information

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

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

More information