Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:

Slides:



Advertisements
Similar presentations
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Advertisements

Moving To Code 3 More on the Problem-Solving Process §The final step in the problem-solving process is to evaluate and modify (if necessary) the program.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
The switch statement: an N-way selection statement.
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Using the Java programming language compiler. Review of relevant material from previous lectures From previous lectures: A computer can only execute machine.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
Shorthand operators.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
The character data type char
 The pool rack example could be implemented using a for loop.  It is also possible to write recursive methods that accomplish things that you might.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
Parameter passing mechanism: pass-by-value. Introduction In the last webpage, we discussed how to pass information to a method I have kept it (deliberately)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Input & Output In Java. Input & Output It is very complicated for a computer to show how information is processed. Although a computer is very good at.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
What does a computer program look like: a general overview.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSci 111 – computer Science I Fall 2014 Cynthia Zickos WRITING A SIMPLE PROGRAM IN JAVA.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
The if-else statement. The if-else statement in Java The if-else statement is the second conditional statement in Java The if-else statement selects one.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Mixing integer and floating point numbers in an arithmetic operation.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
CS110 Programming Language I Lab 4: Control Statements I Computer Science Department Spring 2014.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Variable scope. Variable Scope Variables do not live forever. Failing to take that into account leads to problems. Let's look at an example. Let's write.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
The need for Programming Languages
TK1114 Computer Programming
Comp Sci 200 Programming I Jim Williams, PhD.
The Boolean (logical) data type boolean
Self study.
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
CIS 110: Introduction to Computer Programming
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
The for-statement.
Presentation transcript:

Writing algorithms using the while-statement

Previously discussed Syntax of while-statement:

Previously discussed (cont.) Statements discussed so far: Assignment statement: variable = expression ;

Previously discussed (cont.) Conditional statements: if ( condition ) statement if ( condition ) statement1 else statement2

Previously discussed (cont.) Loop (while) statements: while ( condition ) { statement1 statement2... }

Combining different types of statements Computer Science Fact: Every programming language (including Java) has 3 types of statements: Assignment statements Conditional statements Loop statements

Combining different types of statements (cont.) The good news is: you have learned all of them now ! However, you still need to learn how to use them effectively

Combining different types of statements (cont.) Rule of programming languages: Whenever you see a statement in a syntax construct, you can use any type of statement !!! Example: while ( condition ) while ( condition ) { { statement ===> if ( condition2 ) } { statement1 } else { statement2 }

Combining different types of statements (cont.) Here, we used an if-else (conditional) statement as the statement in the while-body In fact, the statement1 and statement2 in the then-part and else-part of the if-else (conditional) statement can themselves be a assignment statement, a conditional statement, or a loop statement !!! Therefore, you can create very complex programs

Combining different types of statements (cont.) Advice: The point of computer programming is not writing complex programs... but write out an algorithm in simple steps for a dumb machine (computer). There are many different ways to write the same computer program, some ways can be very convoluted than others. You should keep the structure of computer programs simple

Combining different types of statements (cont.) We will now learn how to use the power of a programming language (Java) by combining (nesting) different statements

Developing computer algorithms Pre-requisite to developing a computer algorithm: Before you can write a computer program to solve a problem, you yourself must know what you need to do Because: Programming a computer = tell a computer what to do to solve a problem If you don't know what to do, you cannot tell someone else (or something else like a computer) what to do.... (A blind cannot lead a blind...)

Developing computer algorithms (cont.) Developing a computer algorithm: Develop a computer algorithm = Write down the steps that a human must do to solve a problem in such a detail than a dumb machine (computer) can do it !!!

Programming example 1: find all divisors of a number Problem description: Write a Java program that reads in an integer n... and prints all its divisors

Programming example 1: find all divisors of a number (cont.) A concrete example: Input: n = 12 Output: 1, 2, 3, 4, 6, 12

Programming example 1: find all divisors of a number (cont.) What would you do to solve this problem ? Suppose: n = 12 Check if 12 is divisible by 1 Check if 12 is divisible by 2... Check if 12 is divisible by 12

Programming example 1: find all divisors of a number (cont.) Note: When the remainder of the division is equal to 0, we print out the divisor We do not need to check numbers > 12 because only number ≤ 12 can be divisors !

Programming example 1: find all divisors of a number (cont.) Algorithm: The algorithm contains some abstract steps that need to be fleshed out (work out the details)

Programming example 1: find all divisors of a number (cont.) We have learned the programming technique (trick) to test for divisibility previously: if ( n % a == 0 ) n is divisible by a; else n is not divisible by a;

Programming example 1: find all divisors of a number (cont.) Apply this programming technique to obtain a refined algorithm: Now the algorithm contain only (concrete) steps that can be easily translated into a Java program !!!

Programming example 1: find all divisors of a number (cont.) Java program: import java.util.Scanner; public class Divisors01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int a; System.out.print("Enter a number n: "); n = in.nextInt(); // Read in number

Programming example 1: find all divisors of a number (cont.) a = 1; while ( a <= n ) // Run a = 1, 2,..., n { if ( n % a == 0 ) { // a is a divisor of n System.out.println(a); // Print a (because it's a divisor) } a++; // Make sure we more to the next number !! // or else: infinite loop !!! }

Programming example 1: find all divisors of a number (cont.) Example Program: (Demo above code) –Prog file: Divisors01.java How to run the program: Right click on link and save in a scratch directory To compile: javac Divisors01.java To run: java Divisors01

The brute force search method: a commonly used solution method in computer algorithms The previous algorithm is an example of the brute force search method The general form of the Brute force search method: for every possible value x do { if ( x is a solution ) print x; }

The brute force search method: a commonly used solution method in computer algorithms (cont.) Pre-conditions for using the brute force search method: The number of possible values that needs to be searched must be finite (I.e.: a finite search space) There is a method to determine if a value x is a solution

Programming example 2: find all common divisors of 2 numbers Problem description: Write a Java program that reads in 2 numbers x and y... and prints all numbers that are divisors of both x and y

Programming example 2: find all common divisors of 2 numbers (cont.) A concrete example: Input: x = 24 and y = 16 Output: 1, 2, 4, 8

Programming example 2: find all common divisors of 2 numbers (cont.) What would you do to solve this problem ? Suppose: x = 24 and y = 16 The lesser of the values is 16 Therefore, all divisors are ≤ 16

Programming example 2: find all common divisors of 2 numbers (cont.) Check if 16 and 24 are divisible by 1 Check if 16 and 24 are divisible by 2... Check if 16 and 24 are divisible by 16 When the remainder of both divisions are equal to 0, we print out the divisor

Programming example 2: find all common divisors of 2 numbers (cont.) Rough algorithm: input x, y; min = min(x, y); // this is the range of the brute force search for every value a = {1, 2,...., min} do { if (x and y are divisible by a) { print a; }

Programming example 2: find all common divisors of 2 numbers (cont.) Algorithm (structured diagram):

Programming example 2: find all common divisors of 2 numbers (cont.) Java program: import java.util.Scanner; public class Divisors02 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x, y, a, min = 0; x = in.nextInt(); // Read in x y = in.nextInt(); // Read in y if ( x < y ) // Find min(x,y) min = x; else min = y;

Programming example 2: find all common divisors of 2 numbers (cont.) a = 1; while ( a <= min ) // Run a = 1, 2,..., min(x,y) { if ( x % a == 0 && y % a == 0 ) { // a is a divisor of x and y System.out.println(a); // Print a (because it's a common divisor) } a++; // Make sure we move to the next number !! // or else: infinite loop !!! }

Programming example 2: find all common divisors of 2 numbers (cont.) Example Program: (Demo above code) –Prog file: Divisors02.java How to run the program: Right click on link and save in a scratch directory To compile: javac Divisors02.java To run: java Divisors02

Programming example 3: factor a number (into prime factors) Problem description: Write a Java program that reads in an integer number x.... and prints the prime factorization of the number x

Programming example 3: factor a number (into prime factors) (cont.) A concrete example: Input: x = 420 Output: 2, 2, 3, 5, 7 (because 2 x 2 x 3 x 5 x 7 = 420 and all factors are prime numbers)

Programming example 3: factor a number (into prime factors) (cont.) What would you do to solve this problem ? Suppose: x = 420 Factorization algorithm taught in High Schools: The number 420 is divisible by 2. Factor out the number 2: / 420

Programming example 3: factor a number (into prime factors) (cont.) The number 210 is divisible by 2. Factor out the number 2: / 210

Programming example 3: factor a number (into prime factors) (cont.) The number 105 is not divisible by 2 ==> try 3 !!! The number 105 is divisible by 3. Factor out the number 3: / 105

Programming example 3: factor a number (into prime factors) (cont.) The number 35 is not divisible by 3 ==> try 4 !!! The number 35 is not divisible by 4 ==> try 5 !!! The number 35 is divisible by 5. Factor out the number 5: / 35

Programming example 3: factor a number (into prime factors) (cont.) The number 7 is not divisible by 5 ==> try 6 !!! The number 7 is not divisible by 6 ==> try 7 !!! The number 7 is divisible by 7. Factor out the number 7: / 7

Programming example 3: factor a number (into prime factors) (cont.) Rough algorithm: input x; a = 2; <---- Try use a = 2 as factor for x as long as x is not equal to 1 do { if (x is divisible by a) { // a is a factor of x !!! print a; (Because we have found another factor) Remove factor a from the number x (and continue) } else { Try use a+1 as factor }

Programming example 3: factor a number (into prime factors) (cont.) Algorithm (structured diagram):

Programming example 3: factor a number (into prime factors) (cont.) Check for correctness !!! This algorithm is complicated enough to warrant a correctness check We do so using a small example: suppose x = 12

Programming example 3: factor a number (into prime factors) (cont.) Execution of the algorithm: Iteration 1 through the while-loop: It has printed the factor 2 and starts a new loop with x = 6

Programming example 3: factor a number (into prime factors) (cont.) Iteration 2 through the while-loop: (notice that x = 6 in this iteration !) It has printed another factor 2 and starts a new loop with x = 3

Programming example 3: factor a number (into prime factors) (cont.) Iteration 3 through the while-loop: (notice that x = 3 in this iteration !) Because a = 2 is not a factor of x = 3, the else-part is executed. A new iteration is started with a = 3 (we are trying a new factor)

Programming example 3: factor a number (into prime factors) (cont.) Iteration 4 through the while-loop: (notice that a = 3 in this iteration !) It has printed the factor 3 and starts a new loop with x = 1

Programming example 3: factor a number (into prime factors) (cont.) Iteration 5 through the while-loop: (notice that x = 1 in this iteration !) The loop-continuation-condition is not true !!! The while-loop terminates

Programming example 3: factor a number (into prime factors) (cont.) Result: The program has printed the factors 2, 2, 3 (Which is correct !!!)

Programming example 3: factor a number (into prime factors) (cont.) Java program: import java.util.Scanner; public class Factor01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x; int a; System.out.print("Enter a number x: "); x = in.nextInt(); // Read in number

Programming example 3: factor a number (into prime factors) (cont.) a = 2; while ( x > 1 ) { if ( x % a == 0 ) { // a is a factor of x System.out.println(a); // Print a (because it's a divisor) x = x / a; // Remove factor a from x } else { a++; // Use next number as factor }

Programming example 3: factor a number (into prime factors) (cont.) Example Program: (Demo above code) –Prog file: Factor01.java How to run the program: Right click on link and save in a scratch directory To compile: javac Factor01.java To run: java Factor01