Advanced Arithmetic, Conditionals, and Loops INFSY 535.

Slides:



Advertisements
Similar presentations
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
© 2006 Pearson Education Arithmetic1 of 21 Working With Base Types (or built-in types) –not objects or references: Java has special syntax to deal with.
A First Book of C++ Chapter 5 Repetition.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Application development with Java Lecture 6 Rina Zviel-Girshin.
CS-1010 Dr. Mark L. Hornick 1 Selection and Iteration and conditional expressions.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Repetition Statements b Repetition statements allow us to execute a statement multiple times repetitively b They are often simply referred to as loops.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Looping Increment/Decrement Switch. Flow of Control Iteration/Switch Statements.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 4 Repetition Statements (loops)
Methods Chapter 6.
Chapter 6 More Conditionals and Loops
Loop Structures.
MSIS 655 Advanced Business Applications Programming
CSS161: Fundamentals of Computing
OPERATORS (2) CSC 111.
Outline Altering flow of control Boolean expressions
3.5- The while Statement The while statement has the following syntax:
Repetition Statements
Chap 7. Advanced Control Statements in Java
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

Advanced Arithmetic, Conditionals, and Loops INFSY 535

The Math Class Examples (each returns a number of type double) Math.sqrt (double); Math.pow((double),double power); Math.random (); And more!

Java Math Class Math also defines two symbolic constants: E = PI = Methods in Math are not instantiated? methods are static !

static Class Methods static methods are invoked on behalf of an entire class, not on a specific instance of class. Typically each instance of a class has different copies of instance variables No instance variables allowed to be used for access In Math class, methods are declared: public static double sin(double a) {... }

When calling static method: do not instantiate class, send message to class _number = (int)Math.round(x); Double expressionIntegerCasting

public class ContrivedExample { private static int _numberOfInstances; public ContrivedExample() { // we want to keep a tally of all the // ContrivedExamples that we create _numberOfInstances++; } // now every instance of ContrivedExample // can access _numberOfInstances to see how // many contrived examples have been // created }

static Class Methods Other examples: (int)(math.random () * (high-low)) _randomNumber= (int)(Math.random() * (limit)) +1;

Mixing Integers and Fractional #s public class MyMathClass { public void reassign() { int myInt = 4; double myDouble = 2.64; myInt = myDouble; // can’t assign a double to an int } } Change above assignment to: myDouble = myInt; May use different types of numbers together, but be careful! Go from less to more precise, not the other way around!

Mixing Integers and Fractional #s We can force Java to convert double to int called casting or coercion loss of precision myInt = (int) myDouble; // myInt is now 2

Casting: general form of conversion What is Casting? Format: (data type) expression; Example: int money; ans=(float) money;

Arithmetic Conversion Advice! Do not assign a floating point expression to an int Convert the float to an int through casting: int (varName); Rounding in conversion: int x = int (varName +.5);

Using Interfaces with Constants interfaces to declare methods interfaces to declare constants What if many classes use same constants? Can put constants in an interface and have classes implement it! then public, static, and final are implicit

public interface PhysicsConstants { // speed of light (hundred-million meters // per second double LIGHT_SPEED = 2.998; // more constants, if we want... } Now all classes that implement the PhysicsConstants interface have access to LIGHT_SPEED

Complex Choices: Nested if statements Each Expression is evaluated in sequence, until some Expression is found that is true Only the specific Statement following that particular true Expression is executed If no Expression is true, the statement following the final else is executed

Example: Nested if Statement if (weight >= 30) { if (item == ‘L’) { System.out.println(“You have a heavy load of laundry.”); } else { System.out.println(“ It is heavy, but not laundry”); } else { System.out.println(“ It is not that heavy.”); }

if (weight >= 30) { if (item == ‘L’) { System.out.println(“You have a heavy load of laundry.”); } else { System.out.println(“ It is heavy, but not laundry”); } else { System.out.println(“ It is not that heavy.”); } Given: weight=30; item=“M” What is printed on the console?

Nested Statements Always line up if with corresponding else Compiler always matches else with nearest previous if Indentation will not make a difference except for logical understanding of code! Braces/brackets work like parentheses in logical expressions; forces statement to be evaluated the way you want

Looping

 while loop  for loop

LOOP Statement... false true WHILE Condition Condition

Iteration Loop: A portion of a program that repeats itself a number of times Body: Repeated group of statements Iteration: Each repetition

boolean variable or expression: boolean expression: evaluates to true when it is satisfied evaluates to false when it is not satisfied returns an integer value; 0 represents false and any non-zero value represents true

When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the loop body false true body statement Boolean Expression While loop

While revisited: sentinel controlled loop final int LIMIT = 10; int count = 1; while (count <= limit) { System.out.println (count); count + +; } Control variable Changed as last Statement Use of increment Will be true or false

25 Infinite Loops The body of a while loop eventually must make the condition false If not, it is an infinite loop, i.e. will not end Always double check to ensure that your loops will terminate normally

Nested Loops Similar to nested if statements The body of the loop contains another loop Each time through the outer loop, the inner loop goes through its full set of iterations

Nested loop design Example X=6; while (x >=4) { y = 3; while (y <=6) { y++; System.out.println(y + “ “ + x); } x--; } What will be printed on the console?

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } for (init exp; test; increment) { statement(s); }

For Loop Continued for ( ; ; ; ;<increment/decrement) { stmt(s) stmt(s) } n Initializing expression, is executed n Expression evaluated for true/false; terminates if false n Otherwise statements are executed n After execution, Increment/decrement is executed

Iteration: for loop example for (init exp; test; increment) { statement(s); } sum=1; for (int i = 10;i > 0; i- -) { sum=sum + i }

Choosing a Loop Structure When you can’t determine how many times you want to execute the loop body, use a while statement If you can determine how many times you want to execute the loop body, use a for statement