Exam 1 Review - Engineering 101 Outline Lecture 1...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Exam 1 Review Lecture 6 Selection Lecture 7 Predicates and Intro to Loops What is an algorithm? A list of instructions for accomplishing a task that may be executed by a mechanism. How are algorithms invoked? Every algorithm has a caller. An algorithm is usually called by another algorithm. Caller Algorithm A How is data handled? Data is exchanged between the algorithm and its caller. Since our definition of an algorithm is that it transforms input to output there must be a way to accept input and provide output to the caller. Caller Data Data Data Algorithm A How is data sent to/from the caller? Pass-byPass-by-value copies the data from the caller to a new location in the algorithm. algorithm. Pass-byPass-by-reference gives direct access to the data in the caller's environment. environment. 1 Reading A C++ Program: ColorColor-Coded! Sequence Selection Iteration Greatest Common Factor 1: Request a value for a 2: Request a value for b 3: if a b then assign b to c 4: if a < b then assign a to c 5: while (remainder(a, c)0 OR remainder(b, c)0) 6: subtract one from c 7: return c 8: end Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops Our Algorithms Must Be Written in a Programming Language A programming language has precise syntax (grammar) and semantics (meaning). An algorithm in a programming language is called a program. program. To be used by the machine it must be translated into a native language specific to the computer's CPU (central processing unit) called machine language. language. This translation is done by a compiler. compiler. Reading A C++ Program: ColorColor-Coded! Scaffolding Identifiers Simple type Declaration set up containers for storage Form: simple_type identifiers; #include <iostream> <iostream> using namespace std; // multiply a number by 7 int main ( ) Comment { Declaration double x, y; cin >> x; y = x * 7; Expressions cout << y; return 0; } return: always ends a function Expression change and exchange data Form: expression; C++ Expressions Expressions consist of operators, literals and identifiers. operators, identifiers. Literals are direct representations of data such as 2.4, 5 2.4, or 1.0e-5 (which is the way a computer writes 1.010-5). 1.0e1.0 Identifiers are names given to data objects in declarations. In the previous program x and y were identifiers. Operators transform data. These include +(add), * (multiply), =(assign), plus many others. Operators Operators are the most interesting of the three since they transform data. operator new data Operators that operate on one operand (data object) are unary, those that operate on two operands are unary, called binary. binary. 2 Mathematical Operators Operator Meaning sign change multiplication real division integer division remainder addition subtraction Other Kinds of Operators Operator Meaning insertion extraction assignment Arity unary binary binary binary binary binary binary Placement prefix infix infix infix infix infix infix Precedence 15 13 13 13 13 12 12 Arity binary binary binary Placement infix infix infix Precedence 11 11 2 * / / % + << >> = Not all operators perform mathematical operations >> and << send output to and get input from external streams (keyboards, screens). = sets the value of an identifier. The Insertion Operator << Expects an ostream (output stream) on the left and an expression on the right. The ostream could be cout which is standard output (usually the screen) or alternately it could be a file (on a disk). A series of << operations are evaluated left to right. right. In addition to numbers the << operator can send text strings. A string literal is enclosed in "quotes". << can also send an end-of-line command, endl, so end-ofendl, that the output skips to the next line. The Extraction Operator >> Expects an istream (input stream) on the left and an identifier on the right. Obtains data from the istream and places the value into the identifier. identifier. The istream could be cin which is standard input (usually the keyboard) or alternately it could be a file (on a disk). Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops Avoid Repetition in Programs Repetition leads to errors because there are more opportunities for typos. Repetition makes debugging more difficult because mistakes are repeated. Future users find codes that involve repetition harder to read and harder to understand. understand. Functions and procedures encapsulate algorithms so they can be written once and used repeatedly. 3 Declaring Functions Functions can either be pre-defined library prefunctions or user-defined functions. userfunctions. A function declaration is of the form: T identifier (formal_parameter_list); T is a type that describes the data returned. The formal parameter list is a list of types and identifiers which enumerate the input data and the order in which that data is expected. For example: double x, int y, double z Calling Functions A function call is of the form: f (expression_list); f is a function identifier. The expression list is a list of expressions separated by commas. Each is evaluated and passed to the function as input. The function evaluates to a single data object of a type determined in its declaration. Defining Functions UserUser-defined functions must be defined before they are used. A function definition is of the form: T identifier (formal_parameter_list) compound statement The compound statement is contained in {braces} and is executed whenever the function is called. The definition must have one or more return statements that evaluate to type T. Definition Or Declaration Must Proceed Function Call Function double f( double X, double Y); int main( ){ double A = 1.0, B; double C = 5.0; B = f(C, A); double D = 3.0, E; E = f(D, A); return 0; } double f( double X, double Y){ double Z = X; Z = Z + 3; return Z * Y; } Declaration Note that Z is declared in the function definition, definition, not with the function declaration Function Calls Function Definition Functions versus Procedures Functions return data directly to the caller and take as input copies of data from the caller (call(callby-value) byProcedures do not directly return any value, but operate on data in the caller (call-by-reference). (call-by- Functions Return Information, Procedures Do Not You can declare a procedure that will not return a value by using void instead of an output type void identifier (formal_parameter_list); The definition of the procedure may then have return statements without any associated expression to return. 4 Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops Reading From Files To read from a file you first must declare a new ifstream and open it. This is done with a line of the form: ifstream infile("thisfile.txt"); This line will open a file called thisfile.txt and create a new ifstream called infile to extract input from the file by lines like: infile >> x >> y; Writing To Files To write to a file you first must declare a new ofstream and open it. This is done with a line of the form: ofstream outfile("thatfile.txt"); This line will open a file called thatfile.txt and create a new ofstream called outfile to send output to the file by lines like: outfile << "x =" << x << " and y =" << y; Opening and Closing Files Actually the line ifstream infile("thisfile.txt"); infile("thisfile.txt"); does two things: It declares a new input file stream called infile It opens the file "thisfile.txt" and associates it with this stream This can be done in two separate steps ifstream infile; infile; infile.open("thisfile.txt"); infile.open("thisfile.txt"); When we are done using a file it is good practice to close the file by a line such as: infile.close(); infile.close(); Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops while statement Iteration can be accomplished with a while statement in the form while (condition) loop_body The condition evaluates to True or False. The loop body is an expression or compound statement in {braces}. If the condition is true the loop body executes, then the condition is checked again. The loop body is repeatedly executed as long as the condition holds. holds. 5 The Heart of fact() // factorial, assumes N is positive int fact( int N){ int count=1; count=1; intialization while (count <= N){ continuation condition do something count = count + 1; increment } return f; } Relational Operators A condition is an expression that will evaluate to either true or false. false. The computer recognizes the literal expressions "true" and "false". They are Boolean values and there is a "false". simple type bool that can only adopt these two values true evaluates to 1 and false evaluates to 0. A condition typically involves a relational operator as part of an expression. expression. Relational Operators Operator Meaning less than greater than less than or equal to greater than or equal to is equal to is not equal to Relational Operators 10 10 10 10 9 9 Arity binary binary binary binary binary binary Placement infix infix infix infix infix infix Precedence < > <= >= == != The relational operators have lower precedence than the mathematical operators (+ - * /), but higher precedence than assignment (=) Note that "=" means assignment and "==" means "is equal to?" These are often confused. confused. You cannot string relational operators together in the usual way. Instead you must use a second kind of operator known as a logical operator. operator. 4 > 3 > 2 is really a shorthand for 4>3 and 3>2 all associate left-to-right Logical Operators Operator Alternate Arity unary binary binary Outline Precedence 15 5 4 Placement prefix infix infix Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops not and or ! && || and and or associate left-to-right not associates right-to-left 6 Selection Allows the selective execution of a portion of your code depending on some condition. Syntax in C++: if (condition) statement_t else statement_f Selection Allows the selective execution of a portion of your code depending on some condition. Syntax in C++: if (condition) (condition) statement_t else statement_f The statements can either be single line expressions or multiple expressions enclosed in braces. Selection Allows the selective execution of a portion of your code depending on some condition. Syntax in C++: if (condition) (condition) statement_t Selection Allows the selective execution of a portion of your code depending on some condition. Syntax in C++: if (condition1) (condition1) statement_t1 else if (condition2) (condition2) statement_t2 else statement_f The else can be entirely removed. Or you can add more else conditions in the form of `else if'. Using Selection To Check Program Status Streams are a particular case in point since whenever you try to open or read from a file you don't know if the file might not exist or be finished. ifstream infile("myfile.data"); if( infile.fail() ){ cerr << "Problem with file" << endl; exit(EXIT_FAILURE); stream.fail() can be } used with any stream infile >> x >> y >> z; and returns true if the last action failed. fail() can also be used to read files of arbitrary length int x, n=0; ifstream infile("myfile.data"); infile("myfile.data"); infile >> x; while (! infile.fail() ){ infile.fail() cout << x; n = n + 1; infile >> x; } cout << "read in " << n << " integers." << endl; endl; 7 Switch Statements A switch statement is used to decide between a number of cases switch (integer_expression){ (integer_expression){ case value: expression value: case value: expression value: default: expression } The integer expression is evaluated and the thread of execution starts from the matching case. If none matches it starts from the default. Switch Statements switch (weekday){ case 1: cout << "Monday"; break; break; case 2: cout << "Tuesday"; break; break; case 3: cout << "Wednesday"; break; break; case 4: cout << "Thursday"; break; break; case 5: cout << "Friday"; break; break; default: cout << "Weekend"; } breaks are needed. Otherwise switch drops through to next expression. Outline Lecture 1 Introduction to Algorithms and Programs Lecture 2 C++ Basics and Input/Output Lecture 3 Functions and Procedures Lecture 4 File Streams Lecture 5 Iteration and Conditionals Lecture 6 Selection Lecture 7 Predicates and Intro to Loops Predicates Functions that return bool (Boolean) values are called predicates. Example: return true if an input intege is divisible by either 2, 3 or 5 bool twothreefive return ((x % 2 == (x % 3 == (x % 5 == } (int x){ 0) or 0) or 0)); Analyzing Loops Loops provide the means to reach the solution to a problem by successive approximation. Start Factorial Function int fact( int N){ int count=1, f=1; while (count < N){ f = f * (count + 1); count = count + 1; } return f; } Start The loop body moves the data toward the goal Goal f = N! ? Goal 8 Factorial Function int fact( int N){ int count=1, f=1; while (count < N){ f = f * (count + 1); count = count + 1; } return f; } Start The loop invariant is preserved after each iteration Goal f = N! Factorial Function int fact( int N){ Start int count=1, f=1; while (count < N){ invariant f = f * (count + 1); f = count! count = count + 1; } return f; After each iteration count has advanced } Goal by 1 and the invariant f = N! is preserved. Factorial Function int fact( int N){ Start f = 1! int count=1, f=1; while (count < N){ invariant f = f * (count + 1); f = count! count = count + 1; } return f; The initialization condition } establishes the truth of Goal the invariant before f = N! the loop commences Example: Power xy // Compute x to the y power double power(double x, int y){ double z=1 int n=0; while (n < y){ z=z*x; n=n+1; } return z; } initialization: n == 0, z == x0 loop invariant: z == xn termination: n == y Good luck on the exam! 9 ...
View Full Document

Ask a homework question - tutors are online