Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Algorithms Basic Control Structures Comparisons and if (…) statement What is a function? Math Library Functions Character Functions Reading Sample Programs."— Presentation transcript:

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

2 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 21 Reading (revised) Continue reading in Deitel … Week 2 Sections 2.5-2.7, 6.1-6.6 (also Ch4 sections below) Appendices B, C, E.1-E.2 Week 3 Sections 4.1-4.12, 15.1-15.8 Appendices F.1-F.3

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

23 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 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 * 3.14159 / 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 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 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 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 28 Quadratic Polynomial Roots // roots.cpp – JHS - 2003 #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 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 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; }


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

Similar presentations


Ads by Google