Lecture 1 -- 1Computer Science I - Martin Hardwick How do Calculators Computer Square Roots? rWhen you enter 29 into your calculator and push the square.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Lecture Computer Science I - Martin Hardwick Arithmetic Expressions With Integers rOperators:result is always an integer SymbolNameExampleValue (x.
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Lecture Computer Science I - Martin Hardwick Odds And Ends – Switch Statement rIt is often necessary in programs to set up a set of cases, where.
Lecture Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient.
Lecture Computer Science I - Martin Hardwick Bubble Sort bool bubble_once( vector &list, int top) // Perform one bubble iteration on a list { bool.
Lecture Computer Science I - Martin Hardwick Recursion rA recursive function must have at least two parts l A part that solves a simple case of the.
Lecture Computer Science I - Martin Hardwick Streams In C++ rA stream is a sequence that you either read from or write to. l example – cin is a stream.
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Computer Science 1620 Math Library. Remember this program? suppose that I invest $25000 into a mutual fund that returns 8% per year. Write a program to.
Roundoff and truncation errors
CSC 221: Computer Programming I Fall 2001  conditional repetition  repetition for: simulations, input verification, input sequences, …  while loops.
Lecture Notes 3 Loops (Repetition)
Lecture Computer Science I - Martin Hardwick Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order.
LECTURE 1 CMSC 201. Overview Goal: Problem solving and algorithm development. Learn to program in Python. Algorithm - a set of unambiguous and ordered.
Bisection Method (Midpoint Method for Equations).
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
Iterative Constructs – chapter 4 pp 189 to 216 This lecture covers the mechanisms for deciding the conditions to repeat action. Some materials are from.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
1 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
1 CS150 Introduction to Computer Science 1 Exponents & Output page & Section 3.8.
1 9/26/07CS150 Introduction to Computer Science 1 Exponents & Output page & Section 3.8.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Approximate computations Jordi Cortadella Department of Computer Science.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
CSC 211 Data Structures Lecture 13
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Even more problems.. Mean (average) I need a program that calculates the average of student test scores. I need a program that calculates the average.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
Control Structures Repetition or Iteration or Looping Part II.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Today’s class Numerical differentiation Roots of equation Bracketing methods Numerical Methods, Lecture 4 1 Prof. Jinbo Bi CSE, UConn.
Overview Go over parts of quiz? Another iteration structure for loop.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Recursive Methods for Finding Roots of Functions Bisection & Newton’s Method.
April 11, 2005 More about Functions. 1.Is the following a function call or a function header? calcTotal(); 2.Is the following a function call or a function.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
Chapter five exercises. a. false; b. true; c. false; d. true; e. true; f. true; g. true; h. false.
LESSON 5 Loop Control Structure. Loop Control Structure  Operation made over and over again.  Iterate statement.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Numerical Methods Some example applications in C++
while Repetition Structure
Some problems for your consideration
COMS 261 Computer Science I
Let’s all Repeat Together
Let’s all Repeat Together
(Dreaded) Quiz 2 Next Monday.
Presentation transcript:

Lecture Computer Science I - Martin Hardwick How do Calculators Computer Square Roots? rWhen you enter 29 into your calculator and push the square root button, how does the calculator compute ? r Consider the function x 2 – 29 = 0. l it crosses the x-axis when x = l so, to compute the we need to compute exactly where the function x 2 – 29 crosses the x-axis r We will use an iterative method l we know the function crosses the x -axis somewhere between 0 and 29 l compute the midpoint of the interval 0 to 29 l decide whether the function crosses the x -axis before the midpoint or after the midpoint l repeat for the half of the interval in which the function crosses the x -axis l do this until the interval is very small ( ) – the midpoint of the final interval is an approximation to the square root of 29

Lecture Computer Science I - Martin Hardwick Computing Square Roots (1) #include using namespace std; double f(double x, double num) { return (x*x - num); } rGoal – find the square root of a number using the iterative Bisection Method. l root is where x 2 - number = 0 rWe need a function that computes x 2 – number every time that we need it l this is the job of function f(x) rFunction f(x): l has two arguments, which are type double l produces a result which is type double

Lecture Computer Science I - Martin Hardwick Computing Square Roots (2) int main () { // number to find root of doublenum; // end points for search doubleleft, right; // mid point of interval doublemidpoint; // error bound doubleepsilon; // size of interval doubleinterval; // flag to terminate iteration booldone; // Get number to find root of cout << "Enter number to find "; cout << "square root of: "; cin >> num; // Initialize for iteration left = 0.0; right = num; epsilon = 5E-11; //calculator has 10 digits rSearch for a root between left and right end points that keep moving closer together. rSince the root is always within the interval, when the size of the interval gets sufficient small (i.e., less than epsilon) we can stop. root left right interval size

Lecture Computer Science I - Martin Hardwick Root Finding (2) // Initialize for the iteration loop interval = right - left; done = false; // Iterate to find square root while ((interval > epsilon) && !done) { midpoint = (left + right)/2; if (f(midpoint, num) == 0.0) { done = true; } else if (f(midpoint, num)*f(left, num) < 0.0) { right = midpoint; } else { left = midpoint; } interval = right – left; } // Display square root that was found cout << Root is: " << midpoint << endl; return 0; } rCompute the midpoint of the current interval. l if the midpoint is not the root, then the root is either in the left half or the right half of the original interval l if f(midpoint) and f(left) have different signs, then the root is in the left half left rightmidpoint f(midpoint) f(left)

Lecture Computer Science I - Martin Hardwick While Loops rAlternative to the For loop for situations when you do not know before the loop begins how many iterations of the loop will be needed. rSyntax: while (condition) { statement; … } body of loop any valid logical expression with relational and logic operators condition statement … true start done false

Lecture Computer Science I - Martin Hardwick What Is Displayed By Each Code Segment ? pWhat is displayed when the user types the numbers 1, 2, …, 10 ? cin >> num; while (num < 10) { cout << num*num << endl; cin >> num; } rWhat is displayed when the user types the numbers 2, 4, 6, 0 cin >> num; while (num > 0) { for (i = 1; i <= num; i++) { cout << num; } cout << endl; cin >> num; }

Lecture Computer Science I - Martin Hardwick Infinite Loops rConsider the following loop; what happens when it is executed? // sum the odd numbers up to 100 sum = 0; n = 1; while (n != 100) { sum = sum + n; n = n + 2; } This is an example of an infinite loop that never terminates or terminates only when an error condition occurs. click on the window close button (i.e., the button in the upper right corner of a window with an x in it) Rule of Thumb: dont use != conditions in a while loop, use, = instead.

Lecture Computer Science I - Martin Hardwick For loop or While loop? rWe do not need both types of loops rThis For loop for(expr1 ; expr2 ; expr3) {... } rTranslates into this while loop expr1; while (expr2) { {… } expr3; } rWhat matters is writing code that is clear and easy to read. rSo we use a For loop when the limit is relatively fixed (e.g 5 or N) rAnd we use a While loop when it depends on convergence, or data entered by the user

Lecture Computer Science I - Martin Hardwick Debugging rThe square root program is quite complex – suppose it is wrong rHow do we debug rMethod 1 l Add code to the program to print out values as it executes l This is a good way to look at trends in the code l You can look at the values and try to find something unexpected l If you are quick you can start and stop the code using ctrl s and ctrl q rMethod 2 l Use the debugger l Put break points into the code l We will look at the debugger next week

Lecture Computer Science I - Martin Hardwick while ((interval > epsilon) && !done) { midpoint = (left + right)/2; if (f(midpoint, num) == 0.0) { done = true; } else if (f(midpoint, num)*f(left, num) < 0.0) { right = midpoint; } else { left = midpoint; } interval = right – left; // debugging code cout << left = << left << endl; cout << right = << right << endl; cout << interval = << interval << endl; } Debugging – Method 1 This debugging method is simple but effective Works with any compiler and machine Programmers often leave the debugging code in the program and comment it out while it is not being used. Be careful because bad or sloppy debugging code can waste time Finding the wrong errors Finding errors in the debug code itself Sloppy debugging code will make other programmers distrust your programs. Good debugging code helps someone else understand your program