Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

Java Coding OOP David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Towards Event-driven programming &
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Java Coding 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Decisions, decisions…!
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Java Programming: From the Ground Up
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Syntax for Variables & Constants Input,
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Lecture 7: Menus and getting input. switch Multiple-selection Statement switch Useful when a variable or expression is tested for all the values it can.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
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.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java Coding – part 2 David Davenport Computer Eng. Dept.,
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Chapter 5: Control Structures II
Java Coding 3 David Davenport Computer Eng. Dept.,
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
CSS161: Fundamentals of Computing
Control Statements Loops.
Java Coding 6-extra David Davenport Computer Eng. Dept.,
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Repetition Statements
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 6 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!

IMPORTANT… Students… This presentation is designed to be used in class as part of a guided discovery sequence. It is not self- explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David. David

Repetition Java repetition statements do statement; while (condition); while (condition) statement; where statement is any Java statement condition is a boolean expression for ( init; condition; update) statement;

The while statement Does statement while condition true does statement 0 or more times while (condition) statement; statement condition true false loop

Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop… starsPrinted is 0 while starsPrinted < 5 do print a star add 1 to starsPrinted print “done” * * * * * done

Examples (1) Print 5 stars (asterisk characters) Use 5 println statements! Use a single println statement! Use repetition (a loop…) * * * * * done starsLeftToPrint is 5 while there are starsLeftToPrint do print a star subtract 1 from starsLeftToPrint print “done”

Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop… count = 0; while ( count < 5 ) { System.out.println( “*”); count = count + 1; } System.out.println( “done”); If you print out count as well as the star, what do you get? * * * * * done

Read & sum 5 values by analogy! read value add value to sum report sum Examples (2) sum is 20 sum is 0 sum is 0 while __________ do read value add value to sum report sum sum is 0 count is 0 while count < 5 do read value add value to sum add 1 to count report sum

Examples (2) Read & sum 5 values sum is 20 sum = 0; count = 0; while ( count < 5 ) { value = scan.nextInt(); sum = sum + value; count = count + 1; } System.out.println( “sum is ” + sum); Named constant or ask for & get value from user

Examples (3) Extract design patterns/templates Counting loop… Count, sum or product in loop… count is 0 while count < numberOfRepetitions process to repeat add 1 to count Immediately initialize to 0 (1) before loop

Generic form of while What happens if you fail to… Initialise loop variables Unpredictable behaviour Update loop variables Infinite loop! (in console app’s use Ctrl-C to exit) In general… condition must be falsifiable by applying update to initial values… need proof! initialise any variables in condition while (test condition variable) do statement & update condition variables;

Proving loops terminate (1) Do these print “done”? i = 1; while ( i != 50 ) { System.out.println( i); i = i + 2; } System.out.println( “done”); count = 0; while ( count < 5 ) { System.out.println( “*”); count = count - 1; } System.out.println( “done”);

Proving loops terminate (2) What about this one? i = scan.nextInt(); while ( i != 1 ) { if ( i % 2 == 0) i = i / 2; else i = 3 * i + 1; } System.out.println( “done”); Proof that cannot write program to determine whether every algorithm will halt or not. (ref. Halting Problem – Alan Turing.)

Reading a set of data Three approaches How many? sum is 20 More? Y 3 More? Y 5 More? Y 7 More? Y 4 More? Y 1 More? N sum is sum is 20 Sentinel value non-data value marks end of list Must say “no more”

Sentinel-controlled input Sum set of values terminated by -1 sum = 0 read value while value is not the sentinel do add value to sum read next value print sum read value while value is not the sentinel process the value read next value Extract another design pattern

Examples (sentinel input) Find the average of set of exam scores. Allow user to enter any number of scores; stop and report the average when a negative score is entered. Write a program that allows the user to enter a set of values. When the user enters zero it should stop and report the number of positive and the number of negative values entered. 5, 3, -7, 2, -4, 0  3 positive & 2 negative values entered. 0  0 positive & 0 negative values entered. 9, 2, 8, 0  3 positive & 0 negative values entered. -4, -8, -3, -5, 0  0 positive & 4 negative values entered.

Examples (sentinel input) Allow user to enter a limit value, followed by a set of positive values terminated by a zero. After the user enters zero, print a message to say whether any of the values exceeded the given limit or not. Enter limit: 10 Enter values (0 to stop): Limit WAS exceeded. Enter limit: 8 Enter values (0 to stop): Limit NOT exceeded.

Questions (1) Read a set of positive values & report their maximum after the user enters a negative value. Extend to minimum. Allow the user to enter a set of positive values & report whether they were in ascending order or not. Write a program that asks the user to enter an integer number N, then prints a triangle with N lines of stars or numbers. For example, if N is 4 * *** ***** *******

Questions (2) Compute PI using the series expansion by evaluating: (a) a fixed number of terms (b) enough terms until a specified accuracy is achieved, e.g. until the value changes < For intervals of 0.1 seconds, compute and print the height of a mass falling from a given initial height, until it hits the ground. PI = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 …)

FOR & DO-WHILE …other forms of repetition in Java

Java for statements Same as while loop! Use as short-hand counting style loop for ( init; condition; update) statement; statement condition true false update init Example: for ( i = 0; i < 5; i = i + 1) System.out.println( “*”);

Questions (1) Write a program that asks the user to enter an integer number N, then prints a triangle with N lines of stars or numbers. For example, if N is 4 * *** ***** ******* ******* ***** *** *

Example Ask the user for their name, print it out one character per line, then print “done”. Enter your name: David D a v i d done. print 1 st char in name “ 2 nd “ “ “ “ 3 rd “ “ “ “ : “ “ “ “ last “ “ “ print charAt 0 in name “ “ 1 “ “ “ “ 2 “ “ “ “ : “ “ “ “ last “ “ for index = 0 to ___________ print charAt index in name for (index = 0; index < name.length(); index++) System.out.println( name.charAt( index) );

Using Java methods… To use, need to know Method name Inputs & their types Output type answer = f( x, y, z ); input parameters output result type Method name // in String class… public String substring( int beginIndex, int endIndex) // usage… shortString = longString.substring( 1, 3); // in Math class public static double sin( double d) double d = Math.sin( 0.5); Use ClassName.method(…) for “static” methods varName.method(…) for non-static methods

Example Ask the user for their name, print it out one character per line, then print “done”. Enter your name: David D a v i d done. Enter your name: David d i v a D done. now do it in reverse! Finally… From either sequence of characters, construct a String, reverseName

Question Given an integer, print its digits in reverse sequence, one per line. Enter integer: done. Enter an integer: 372 Reversed is: 273 Now reconstruct the reverse integer Note: you are not allowed to use the power function!

Java do-while statements Repeat 1 or more times do statement; while (condition); statement condition true false Example: i = 0; do { System.out.println( “*”); i++; } while ( i < 5);

Examples (do-while) Data validation e.g. Read positive value from user do { System.out.print( “Enter positive value: ”); value = scan.nextInt(); } while ( value 0 do ask for “a positive value” and get value while value is not positive

Examples (do-while) Menus - set of options for user to select from ABC Trading Co – sales 2 – stock 3 – admin Select (0 to exit) : _ do display menu get selection from user perform selection while selection is not exit print “goodbye” if selection is SALES then // do sales things else if selection is STOCK then // do stock things else if selection is ADMIN then // do admin things else if selection is not EXIT then print “invalid selection” msg

More practice? Process characters in String Use stringVariable.charAt( int pos) & stringVariable.length() Process digits in an int Use / & % to split it up Compute PI & e using sequence Compute square root (Newton Raphson) Print table of projectile motion Print calendar for given month