Chapter 6: Repetition Continued. 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”);

Slides:



Advertisements
Similar presentations
Recursion. Binary search example postponed to end of lecture.
Advertisements

Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Objectives You should be able to describe:
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
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.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Chapter 8 Recursion Modified.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an instruction set Three repetition structures: while,
Chapter 5: Control Structures II
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
1 Recursion Recursive Thinking Recursive Programming Recursion versus Iteration Direct versus Indirect Recursion Reading L&C 3 rd : 7.1 – nd :
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
A First Book of ANSI C Fourth Edition
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 6 Modularity Using Functions
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
Chapter 15 Recursion.
Methods Chapter 6.
2.5 Another Java Application: Adding Integers
Chapter 5: Control Structures II
Programming Fundamentals Lecture #7 Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
Recursion Recursive Thinking Recursive Programming
Chapter 6 Repetition Objectives ❏ To understand basic loop concepts:
Recursion Chapter 11.
A First Book of ANSI C Fourth Edition
CHAPTER 6 GENERAL-PURPOSE METHODS
Unit 3 Test: Friday.
A First Book of ANSI C Fourth Edition
Dr. Sampath Jayarathna Cal Poly Pomona
The structure of programming
Thinking procedurally
Presentation transcript:

Chapter 6: Repetition Continued

2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); } While (idNum 1999);

3 Alternative Code do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); if (idNum 1999) JOptionPane.showMessageDialog(null, “Error bla bla bla”, JOptionPane.ERROR_MESSAGE); else break; // a valid id num was entered } while (true); // expression is always true

4 Recursion It is possible for a method to call itself Methods that call themselves are referred to as: –Self-referential methods –Recursive methods Direct recursion –A method invokes itself Indirect or mutual recursion –A method can invoke a second method, which in turn invokes the first method

5 Mathematical Recursion The recursive concept is that the solution to a problem can be stated in terms of “simple” versions of itself Factorial of number n: –Denoted as n!, where n is a positive integer 1! = 1 n! = n * (n * 1)! for n > 1

6 Mathematical Recursion (continued) General considerations that must be specified include: –What is the first case? –How is the nth case related to the (n - 1) case?

7 Pseudocode for Method factorial If n = 1 factorial = n Else factorial = n * factorial(n - 1)

8 Recursive Example public class Recursive { public static void main(String[] ags) { int n = 3; long result; result = factorial(n); System.out.println("The factorial of " + n + " is " + result); } public static long factorial(int n) { if (n == 1) return (n); else return (n * factorial(n-1)); } }

9 How the Computation Is Performed A Java method can call itself due to: –Java’s allocation of new memory locations for all method arguments and local variables as each method is called The allocation is made dynamically in a memory area referred to as the stack The stack is memory used for rapidly storing and retrieving data

10 Recursion Versus Iteration The recursive method can be applied to any problem in which the solution is represented in terms of solutions to simpler versions of the same problem Recursive methods can always be written in a non- recursive manner using an iterative solution

11 Recursion Versus Iteration (continued) If a problem solution can be expressed iteratively or recursively with equal ease, the iterative solution is preferable because it: –Executes faster –Uses less memory There are times when recursive solutions are preferable –Some problems are easier to visualize using a recursive algorithm –Sometimes a recursive solution provides a much simpler solution

12 Applications: Random Numbers and Simulations Random numbers –Series of numbers whose order cannot be predicted –Hard to find in practice Pseudorandom numbers –Sufficiently random for task at hand Java compilers provide general-purpose method for creating random numbers –Defined in the Math class –Named random()

13 public class RandomNumbers { public static void main(String[] args) { double randValue; int i; for (i = 1; i <= 10; i++) { randValue = Math.random(); System.out.println(randValue); } } }

14 Scaling A method for adjusting random numbers produced by a random number generator to reside within ranges, such as 1 to 100 –Accomplished using the expression: (int) (Math.random() * N)

15 Simulations Common use of random numbers: –Simulate events rather than going through time and expense of constructing a real-life experiment Coin Toss Simulation –Use random number generator to simulate coin tosses Elevator Simulation –Simulate the operation of an elevator

16 Common Programming Errors Creating a loop that is “off by one” Repetition statements should not test for equality when testing floating-point (real-values) operands Placing a semicolon at the end of either a while or for loop’s parentheses Using commas to separate items in a for statement instead of the required semicolons Omitting a final semicolon from a do-while statement

17 Summary A section of repeating code is referred to as a loop –Types of loops: while for do-while A while statement checks a condition before any other statement in a loop

18 Summary (continued) A for statement is extremely useful in creating loops that must be executed a fixed number of times A do-while statement checks its expression at the end of the loop