1 Algorithms Basic Control Structures Comparisons and if (…) statement What is a function? Math Library Functions Character Functions Reading Sample Programs.

Slides:



Advertisements
Similar presentations
1 Demo Reading Assignments Important terms & concepts Fundamental Data Types Identifier Naming Arithmetic Operations Sample Programs CSE Lecture.
Advertisements

If Statements & Relational Operators Programming.
Computer Science 1620 Loops.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
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.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
ME 142 Engineering Computation I Excel Functions.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
CSE1222: Lecture 4The Ohio State University1. Mathematical Functions (1)  The math library file cmath Yes, this is a file with definitions for common.
CPS120: Introduction to Computer Science Decision Making in Programs.
Operations Making Things Happen. Our Scuba Program #include // cin, cout, > using namespace std; int main() { const double FEET_PER_ATM = 33.0, LBS_PER_SQ_IN_PER_ATM.
Chapter 4 Selection Structures: Making Decisions.
Basic Of Computer Science
STANDARD FUNCTIONS Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the.
CPS120: Introduction to Computer Science Decision Making in Programs.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
CSCI 125 & 161 / ENGR 144 Lecture 8 Martin van Bommel.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
1 Operations Chapter 4 & Section Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
USING & CREATING FUNCTIONS. MODULAR PROGRAMMING  Why Modular Programming?  Improves Readability & Understandability  Improve Maintainability  Allows.
CPS120: Introduction to Computer Science Decision Making in Programs.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Mathematical Manipulation Data types Operator precedence Standard mathematical functions Worked examples.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Control structure: Selections Computer and Programming Department of Computer Engineering Kasetsart University Cliparts are taken from
Simple C Programs.
Operations Making Things Happen.
The Ohio State University
Today Variable declaration Mathematical Operators Input and Output Lab
Introduction to Computer Programming
Repetitive Structures
BIL 104E Introduction to Scientific and Engineering Computing
Bill Tucker Austin Community College COSC 1315
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
The Selection Structure
Engineering Problem Solving with C++, Etter/Ingber
CSC113: Computer Programming (Theory = 03, Lab = 01)
Fundamental of Java Programming Basics of Java Programming
Math Library and IO formatting
Copyright © 2012 Pearson Education, Inc.
Compound Assignment Operators in C++
Summary Two basic concepts: variables and assignments Basic types:
Output Formatting Bina Ramamurthy 4/16/2019 BR.
Life is Full of Alternatives
Life is Full of Alternatives
Branching statements Kingdom of Saudi Arabia
Selection Control Structure
Output Formatting Bina Ramamurthy 9/25/2019 BR.
Control Structures.
Presentation transcript:

1 Algorithms Basic Control Structures Comparisons and if (…) statement What is a function? Math Library Functions Character Functions Reading Sample Programs CSE Lecture 4 – Algorithms & Decisions

2 Algorithms What is an algorithm? A precise description of the sequence of steps necessary to solve some task Your programs begin as algorithms Sample: finding absolute value 1 – prompt user and get users input value 2 – if value is negative then negate it 3 – output result

3 Converting Algorithms to Code Place algorithm in program shell as comments #include using namespace std; int main () { // 1 - prompt user and get user’s input // 2 - if input value is negative then negate it // 3 - output result return 0; }

4 Converting Algorithms to Code Then fill in C++ code for each algorithm step #include using namespace std; int main () { int value; // 1 - prompt user and get user’s input cout << “Enter an integer value: “; cin >> value; // 2 - if input value is negative then negate it if (value < 0) value = -value; // 3 - output result cout << “Its absolute value is : “ << value << endl; return 0; }

5 Basic Control of Execution There are three primary methods of controlling the flow of program execution Sequence – this is the default Selection – here a choice is made to Perform a step or not Perform one step or another Repetition – also known as Iteration Repeat a step over and over Recursion also allows us to repeat steps, but we will wait to discuss this until later

6 Control structure example Program that repeatedly calculates absolute values #include using namespace std; int main () { int value; cout << “Enter an integer value (or q to quit): “; cin >> value; while (! cin.fail()) // <-- repetition { if (value < 0) // <-- selection value = -value; cout << “Its absolute value is : “ << value << endl; cout << “Enter an integer value (or q to quit): “; cin >> value; } return 0; }

7 Comparisons Operators (x < y) less than (x <= y) less than or equal (x > y) greater than (x >= y) greater than or equal (x == y) equal (x != y) not equal

8 Logical (boolean) expressions Operators (x && y) x and y (x || y) x or y –- (inclusive or) (! x) not x Precedence (highest to lowest) ! >= == != && ||

9 Comparisons & Logic Comparisons and logical (boolean) expressions all evaluate to true or false In C, zero (0) takes place of false and any non-zero value can represent true Examples:x=2x=12 (x < 5)truefalse (1 <= x) && (x <= 10)truefalse (x < 1) || (10 < x)falsetrue !(x == 5) == (x != 5) truetrue

10 Boolean Operation Truth Tables x y x && y x || y ! x false false false false true false true false true true true false false true false true true true true false

11 If ( … ) statement if ( … ) allows two methods of choosing what code to execute or not This form either executes the or not, depending on the truth of the if ( ) This form executes if is true, otherwise it executes if ( ) else

12 If ( … ) statement examples cin >> value; if (value < 0) value = -value; // skipped if value not negative if ((x < 1) || (10 < x)) cout << “x is out of range\n”; else cin << “x is in range\n”;

13 Code Blocks A block of code is any sequence of statements between open and closed braces { } A block can take the place of any single statement in C or C++ A block may also have declarations of variables (objects) that exist only within the block This is called local scope Locally declared objects cease to exist when execution leaves the block

14 Code Block Example cout << “Enter a non-negative value: “; cin >> value; if (value < 0) { // give user a chance to correct the input cout << “That value is negative\n” << “Please enter a non-negative value: “; cin >> value; }

15 Nesting Since if ( … ) is a statement itself, it can be nested inside other if statements if (a < 0) cout << “is negative”; else if (a > 0) cout << “is positive”; else cout << “is zero”;

16 Nesting Warning The else is always paired with the closest preceding unpaired if The following does not perform as the indentation would lead you to believe When A is -15 output is is negative is very negative When A is -8 output is is negative is non-negative When A is 10 output is is non-negative if (A < 0) cout << “ is negative”; if (A < -10) cout << “ very negative”; else cout << “ is non-negative”;

17 Nesting Warning The code below “fixes” the confusion, associates the else with the first if, and outputs appropriate descriptions of A When A is -15 output is is negative is very negative When A is -8 output is is negative When A is 10 output is is non-negative if (A < 0) { cout << “ is negative”; if (A < -10) cout << “ very negative”; } else cout << “ is non-negative”;

18 What is a function? A function is a named, parameterized block of code that computes a value or performs a task We invoke a function by using its name with appropriate parameters as a statement in our code, or as part of an expression Example: double sqrt(double v); // prototype The square root function from the math library It computes the square root of the value of the parameter v and returns the result to the calling context y = sqrt(x+37.5); // invocation

19 Math Library Functions #include abs(x) – absolute value of x sqrt(x) – square root of x pow(x,y) – x y ceil(x) – smallest integer larger than x floor(y) – largest integer smaller than x exp(x) - e x log(x) – natural log of x – ln(x) log10(x) – log 10 (x) sin(x) – sine of x, range +/- 1.0, x in radians cos(x) – cosine of x, range +/- 1.0, x in radians tan(x) – tangent of x, x in radians asin(x) – arcsine of x, range +/- PI/2 acos(x) – arccosine of x, range 0 to PI atan(x) – arctangent of x, range +/- PI/2 atan2(x,y) – arctangent of x,y, range +/ PI

20 Character Functions #include toupper(ch) – returns upper case equiv. of ch tolower(ch) – returns lower case equiv. of ch isalpha(ch) – true if ch is a letter a..z, A..Z isdigit(ch) – true if ch is a digit 0..9 There are more …

21 Reading (revised) Continue reading in Deitel … Week 2 Sections , (also Ch4 sections below) Appendices B, C, E.1-E.2 Week 3 Sections , Appendices F.1-F.3

22 Trajectories Range = vx0 * tof vy0 vx0 v0 Height = vy0 * tmid * g * tmid 2 vy(tmid) = 0 = vy0 + g * tmid So, tmid = -vy0 / g g = ft/sec 2 General Position Calculations x = x0 + vx0 * t y = y0 + vy0 * t * g * t 2 vy = vy0 + g * t tof = 2 * tmid

23 Calculating Range of a Projectile This is a parabolic trajectory under the influence of Earth gravity, but no air Algorithm 1 – prompt user and read launch angle in degrees 2 – prompt user and read initial velocity in ft/sec 3 – calculate vx & vy (initial velocity components) 4 – calculate time of flight (no air, gravity -32 ft/s/s) 5 – calculate range 6 – output results

24 Calculating Range of a Projectile // range.cpp – JHS – 8/29/06 – CSE Notre Dame #include using namespace std; int main () { const double g = -32.0; const double rads_per_degree = 2 * / 360.0; double thetaD, thetaR, v0, vx0, vy0, t, time_of_flight; // 1 – prompt user and read launch angle in degrees cout << “ Enter angle of barrel above horizon (in degrees): “; cin >> thetaD; thetaR = thetaD * rads_per_degree; // convert to radians // 2 – prompt user and read initial velocity in ft/sec cout << “ Enter initial velocity of projectile (in ft/sec): “; cin >> v0;

25 Calculating Range of a Projectile // 3 – calculate vx & vy (initial velocity components) vx0 = v0 * cos(thetaR); vy0 = v0 * sin(thetaR); // 4 – calculate time of flight (no air, gravity -32 ft/s/s) t = -vy0 / g; time_of_flight = 2.0 * t; // 5 – calculate range, etc, and output results cout << fixed << setprecision(2); cout << “Projectile firing: Initial conditions\n”; cout << setw(10) << thetaD << “ degrees above horizon\n”; cout << setw(10) << v0 << “ ft/sec muzzle velocity\n”; cout << “Trajectory characteristics:\n”; cout << setw(10) << time_of_flight << “ seconds in flight\n”; cout << setw(10) << (vx0*time_of_flight) << “ feet down range\n”; cout << setw(10) << (vy0*t + 0.5*g*t*t) << “ feet max height\n”; return 0; }

26 Quadratic Polynomial Roots Find solutions (roots) to 0 = ax 2 + bx + c There are several different cases 1: a == 0, b != 0, there is one real root x = -c/b 2: a == 0, b == 0, c != 0, nonsense equation with no roots 3: a == 0, b == 0, c == 0, every value of x is a root 4: a != 0, x = (-b +/- sqrt(b 2 - 4ac))/2a, potentially two roots (A) (b 2 - 4ac) < 0, roots are complex not real (B) (b 2 - 4ac) == 0, there is one real root x = -b/2a (C) (b 2 - 4ac) > 0, there are two real roots  x 1 = (-b + sqrt(b 2 - 4ac))/2a  x 2 = (-b - sqrt(b 2 - 4ac))/2a

27 Quadratic Polynomial Roots Algorithm: 1 - prompt user and read three coeficients (a,b,c) 2 - determine which case above (1,2,3,4) 3 - in cases 1, 2, & 3 computer root and output result or output appropriate message 4 - in case 4, calculate the value of b 2 - 4ac and determine which case applies (A,B,C) 5 - in case A output message 6 - in cases B & C calculate root(s) and output results

28 Quadratic Polynomial Roots // roots.cpp – JHS #include using namespace std; int main( ) { double a,b,c; // coefficients of quadratic equation double rad; // will be the value under the square root double root1,root2; cout << "Enter the values of a, b, and c for" << " the quadratic equation\n"; cout << " (ax^2 + bx + c) = 0\n"; cout "; cin >> a >> b >> c; cout << "\nFor the equation (" << a << "x^2 + " << b << "x + " << c << " = 0)\n";

29 Quadratic Polynomial Roots if (a == 0.0) { if (b == 0.0) if (c == 0.0) cout << "Any value is a root of this equation\n"; else cout << "There is no root of this equation\n"; else { root1 = -c / b; cout << “One real root (x = " << root1 << ")\n"; } else { rad = b * b - 4 * a * c;

30 Quadratic Polynomial Roots if (rad < 0.0) cout << " There are only complex roots\n"; else if (rad == 0.0) { root1 = -b / (2 * a); cout << “One real root (x = " << root1 << ")\n"; } else { root1 = (-b - sqrt(rad)) / (2 * a); root2 = (-b + sqrt(rad)) / (2 * a); cout << “Two real roots (x = " << root1 << " and x = " << root2 << ")\n"; } return 0; }