Review for Programming Exam and Final May 4-9, Ribbon with icons for commands Quick access toolbar (more at lecture end)

Similar documents
Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014

Introduction to Arrays. Midterm Comments. Midterm Results. Midterm Comments II. Function Basics (Problem 2) Introduction to Arrays April 11, 2017

Outline. Writing Functions and Subs. Review Immediate (1-line) Errors. Quiz Two on Thursday (2/23) Same Code Without Option Explicit

Outline. Program Assignments Four and Five. OOP Examples. Object-Oriented Programming. Other Object Concepts. With-End With Structure

VBA Handout. References, tutorials, books. Code basics. Conditional statements. Dim myvar As <Type >

Outline. More on Excel. Review Entering Formulas. Review Excel Basics Home tab selected here Tabs Different ribbon commands. Copying Formulas (2/2)

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

Programming Assignment Six. Semester Calendar. 1D Excel Worksheet Arrays. Review VBA Arrays from Excel. Programming Assignment Six May 2, 2017

Introduction to VBA for Excel-Tutorial 7. The syntax to declare an array starts by using the Dim statement, such that:

Basic tasks in Excel 2013

Appendix A1 Visual Basics for Applications (VBA)

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Microsoft Office Illustrated. Getting Started with Excel 2007

Computational Mathematics/Information Technology. Worksheet 2 Iteration and Excel

Visual basic tutorial problems, developed by Dr. Clement,

Programming for Engineers Iteration

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

Language Fundamentals

Lab1: Use of Word and Excel

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

ENGR 1181 MATLAB 09: For Loops 2

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving Excel Tutorial VIII

Full file at

Introduction to TURING

CSE 123 Introduction to Computing

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Module 3 - Applied UDFs - 1

Visual C# Instructor s Manual Table of Contents

QUIZ: What value is stored in a after this

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Arithmetic expressions can be typed into Maple using the regular operators:

IDENTIFYING UNIQUE VALUES IN AN ARRAY OR RANGE (VBA)

Statements and Operators

Microsoft Excel. Part 2: Calculations & Functions. Department of Computer Science Faculty of Science Chiang Mai University

Physics 251 Laboratory Introduction to Spreadsheets

JME Language Reference Manual

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

OpenOffice.org 3.2 BASIC Guide

Full file at

1 Lexical Considerations

variables programming statements

Function Exit Function End Function bold End Function Exit Function

Microsoft Excel 2010 Level 1

Office 2016 Excel Basics 12 Video/Class Project #24 Excel Basics 12: Formula Types and Formula Elements


Outline. Debugging. In Class Exercise Solution. Review If Else If. Immediate Program Errors. Function Test Example

Excel Functions & Tables

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Learning the Language - V

Using Basic Formulas 4

KOMAR UNIVERSITY OF SCIENCE AND TECHNOLOGY (KUST)

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Business Data Analysis MA0123. Dr Gavin Shaddick Department of Mathematical Sciences 4W 5.7

Microsoft Office Excel Use Excel s functions. Tutorial 2 Working With Formulas and Functions

Status Bar: Right click on the Status Bar to add or remove features.

An Introduction to MATLAB

d2vbaref.doc Page 1 of 22 05/11/02 14:21

ME 142 Engineering Computation I. Graphing with Excel

Lecture Transcript While and Do While Statements in C++

Excel tutorial Introduction

CSE 123 Introduction to Computing

Welcome to Microsoft Excel 2013 p. 1 Customizing the QAT p. 5 Customizing the Ribbon Control p. 6 The Worksheet p. 6 Excel 2013 Specifications and

Introduction to MATLAB for Engineers, Third Edition

CS111: PROGRAMMING LANGUAGE II

Lesson 3: Basic Programming Concepts

CENTRAL TEXAS COLLEGE COSC 1315 INTRODUCTION TO COMPUTER PROGRAMMING. Semester Hours Credit: 3 INSTRUCTOR: OFFICE HOURS:

Chapter 4: Programming with MATLAB

PTC Mathcad Prime 3.0

Excel Programming with VBA (Macro Programming) 24 hours Getting Started

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

The Microsoft Excel Course is divided into 4 levels

2. INTRODUCTORY EXCEL

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

EE 301 Signals & Systems I MATLAB Tutorial with Questions

VBScript: Math Functions

CSCI 171 Chapter Outlines


Simple Java Programming Constructs 4

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

Today Function. Note: If you want to retrieve the date and time that the computer is set to, use the =NOW() function.

Advanced Econometric Methods EMET3011/8014

To be able to modify a worksheet and use functions, you will: Select ranges of cells on a worksheet by using the mouse.

Curriculum Map Grade(s): Subject: AP Computer Science

Workbooks (File) and Worksheet Handling

CS 155 Exam 2 Spring 2015

ENGI Introduction to Computer Programming M A Y 2 8, R E Z A S H A H I D I

Lesson 4: Auditing and Additional Formulas. Return to the FastCourse Excel 2007 Level 3 book page

ECE 202 LAB 3 ADVANCED MATLAB

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Microsoft How to Series

Reference Services Division Presents. Excel Introductory Course

MS Excel VBA Class Goals

Our Strategy for Learning Fortran 90

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Transcription:

Review for Programming Exam and Final Larry Caretto Mechanical Engineering 209 Computer Programming for Mechanical Engineers May 4-9, 2017 Outline Schedule Excel Basics VBA Editor and programming variables Arithmetic statements Order of precedence If Statements Looping Arrays 2 Semester Calendar Date Assignment Date Assignment May May Quiz 5 on Arrays 2 4 May 9 Assignment 6 Due May 11 May 18 Programming Exam Final Exam 12:45 to 2:45 pm 3 Ribbon with icons for commands Quick access toolbar (more at lecture end) Name box shows selected cell Final Review: Excel Basics Home tab selected here Tabs Different ribbon commands for each tab Cell E2 Formula bar Row 2 Col Formula bar E shows contents Click boxed x in lower right corner of groups for more of selected cell 4 choices Using Excel Entering and copying formulas Understanding absolute/relative references Excel functions like sin(), exp(), etc. Formatting cells Creating/modifying plots not on final Creating macros (subs without arguments) can be called from worksheet Advanced topics like data validation and range names not on final 5 Using VBA Transfer to and use of editor Writing functions and subs Functions transfer information through the argument list, based on position in list A macro is a sub with no arguments Information transfer to/from subs Range( M12 ).Value = x * y Write property Cells(12,13).Value = x * y Write property Z = Range( C5 ).Value Read property Z = Cells(5,3).Value Read property 6 ME 209 Computer Programming for Mechanical Engineers 1

Example Function Const getmolarmasserror as Double = -9999 Const universalgasconstant as Double = 8.3144621 Function idealgasdensity(substancename As _ String, pressure As Double, temperature As _ Double) As Double Computes ideal gas density =idealgasdensity( Dim molarmass As Variant B2, C3, D4) molarmass = getmolarmass(substancename) If molarmass = getmolarmasserror Then _ idealgasdensity = Masslookup error Else idealgasdensity = molarmass * pressure _ / (universalgasconstant * temperature) End If Function reference passes three inputs: name, pressure, and temperature in that order. 7 Use of Example Function Call from worksheet Order of arguments must match function header May also use constant or range name Call from other VBA procedures May use variables or constants density = idealgasdensity("nitrogen", _ 400, 350) pressure = 400 : temperature = 350 substance = "Nitrogen" density = idealgasdensity(substance, _ pressure, temperature) 8 Same Example as Sub Const getmolarmasserror as Double = -9999 Const universalgasconstant as Double = 8.3144621 Sub idealgasdensity() Dim substancename As String Will need to use Dim pressure As Double Dim temperature As Double Range().Value Dim molarmass As Variant on final substancename = Range( B2 ).Value pressure = Range( B3 ).Value temperature = Range( B4 ).Value molarmass = getmolarmass(substancename) If molarmass = getmolarmasserror Then _ Range( B5 ).Value = Masslookup error Else Range( B5 ).Value = molarmass * pressure _ / (universalgasconstant * temperature) End If 9 Generic Function Function <name> (<arguments>) As <type> <statements> <statements> must include at least one statement that sets <name> = <value> Inputs to function come from <arguments> not statements like Range.Value 10 Generic Sub Sub <name> (<arguments>) <statements> <arguments> in subs and functions is the argument list which has zero or more items like the following: <variable> As <Type> Multiple items are separated by commas 11 Declaring Variables/Consts Use the following syntax Dim x As Double Distance Dim k As Long Dim s As String, d as Date Const g As Double = 9.80665 Do not use the following syntax Dim x, y As Double Use Option Explicit to find errors in undeclared variables Note common data types 12 ME 209 Computer Programming for Mechanical Engineers 2

Assignment Statements Assigns a value to a variable Examples shown below degreestoradians = PI / 180 force = mass * accel What is really being done here? Names refer to computer memory locations The value of the expression on the right of the = sign is assigned to the memory location of the variable on the left Can have statements like x = x + 1 13 String Variables String variables hold text information Declare string variables using Dim <variable> As String E. g.: Dim s As String, msg as String String constants defined with quotation marks: ME 209 is a string constant String assignment: s = ME 209 Concatenate (join) two strings with the concatenation (&) operator msg = This course is & s 14 Operators in Precedence Order Parentheses ( Evaluate me first ) Exponentiation ^ Unary minus (E.g. x) Multiply/Divide * / Integer Division \ Mod (remainder, e.g. 7 Mod 4 = 3) Addition/Subtraction + String concatenation & Relational < <= = >= > <> Logical in following order: Not And Or 15 Writing Equations Important to remember operator precedence rules On final do not use [] in place of () and write Use parentheses to get desired result Example: formulas as z = (a+b)/(c+d) instead of z Write a statement to compute z z = (p + q * z) / (s^2 * r + cos(y)) Write statement on one line (or continuation) Use x*y to multiply x times y Parentheses for multiplication/division 16 Relational/Logical Operators Relational operators compare other variables and have true or false results VBA operators are <, <=, =, >, >=, <> Not equal <> is less than or greater than Logical operators (Not, And, Or) combine Boolean (true/false) results x And y is true if both x and y are true x Or y is true if either x or y is true Not x is true if x is false; is false if x is true 17 If Else If A <condition> is If <condition1> Then TRUE or FALSE <Statements done if condition1 is true> ElseIf <condition2> Then <Statements done if condition2 is true> ElseIf <condition3> Then <Statements done if condition3 is true> <May be other conditions> May have zero or Else many ElseIf s <Statements done if all conditions false> End If Else statement is optional <Execute here after any statements done> 18 ME 209 Computer Programming for Mechanical Engineers 3

Boolean Variables Boolean variables have two possible values: TRUE or FALSE Can set Boolean variables equal to a relational or logical expression Declare variables as Boolean Dim converged As Boolean Example of use converged = diff < abserr Or _ diff < relerr * Abs(reference) 19 The Do While Loop The Do While <condition> loop executes as long as the <condition> is true The Do While x < 10 ends only when x 10 at the start of the loop In the operation of the loop, a new value of x is tested before the loop starts Once the loop starts all statements before the Loop statement are completed until a new test is made unless there is a conditional exit 20 Loop Until Command An alternative to the Do While Loop Starts with the command Do Followed by loop body with all code executed in loop Concludes with Loop Until <condition> Loop continues as long as <condition> is false Loop is exited when <condition> is true Loop Until condition opposite of Do While 21 Count-controlled Loops Modified structure of VBA For loop For <counter> = <start> To _ <finish> Step <increment> <statements> Next <counter> Step usually omitted if <increment> = 1 Here <counter> is changed by <increment> each time through loop Loop is executed ntimes times where ntimes = Int((<finish> <start>) / <increment>) + 1 Not executed if ntimes 0 Executed once if <start> = <finish> 22 Do While Example Function mysqrt(a As Double) As Variant Const and Dim statements omitted mysqrt = 1: iterations = 0: converged = False Do While Not converged And _ iterations < maxiterations mysqrt = mysqrt / 2 + A / (2 * mysqrt) iterations = iterations + 1 converged = Abs(mySqrt ^ 2 - A) < _ maxrelerr * Abs(A) Loop If Not converged Then mysqrt = _ "No Convergence" 23 Same Example With Loop Until Function mysqrt2(a As Double) As Variant Const and Dim statement omitted iterations = 0 : mysqrt = 1 Do mysqrt2 = mysqrt2 / 2 + A / (2 * mysqrt2) iterations = iterations + 1 converged = Abs(mySqrt2 ^ 2 - A) < _ maxrelerr * Abs(A) Loop Until converged Or iterations >= _ maxiterations If Not converged Then mysqrt2 ="No Convergence" Opposite of Do While condition 24 ME 209 Computer Programming for Mechanical Engineers 4

Same Example With For Loop Function mysqrt3(a As Double) As Variant Const and Dim statements omitted mysqrt = 1 No other initializations For iteration = 1 To maxiterations mysqrt3 = mysqrt3 / 2 + A / (2 * mysqrt3) If Abs(mySqrt3 ^ 2 - A) < maxrelerr * _ Abs(A) Then Exit Function Next iteration maxiterations exceeded if we get here mysqrt3 ="No Convergence" 25 Tracing Loops x = 1 : term = x : sum = term For n = 1 to 10 term = term * x / n sum = sum + term Exercise: Show that sum for n = 6 is 1957/720 Initialization: x = 1 term = x = 1 sum = term = 1 n=1: term = 1 * 1 / 1 = 1; sum = 1 + 1 = 2 n=2: term = 1 * 1 / 2 = 1/2; sum = 2 + 1/2 = 5/2 n=3: term = 1/2 * 1 / 3 = 1/6; sum = 5/2 + 1/6 = 16/6 n=4: term: 1/6 * 1 / 4 = 1/24; sum: 16/6 +1/24 = 65/24 n=5: term ;1/24*1/5=1/120;sum: 65/24+1/120=163/60 26 Math x 1 x 2 x 3 x 4 x 5 x 6 VBA x(1) x(2) x(3) x(4) x(5) x(6) VBA Arrays Math notation, x i, is replaced by VBA notation x(i) Name for (i) is index or subscript View this one-dimensional array as one row or one column of data Must declare maximum array size 27 Declaring Arrays Use Dim with array size Usual statement: Dim x As Array statement: Dim x(<size>) As <size> specifies maximum subscript May be done for individual arrays where <size> is <minimum> To <maximum> May use <size> as <maximum> In this case default <minimum> is normally zero Can change default <minimum> to one with statement: Option Base 1 28 Using Array Variables We can use individual array elements like any other programming variable E = stress(3)/strain(3) k = 3 : E = stress(k)/strain(k) For k = 1 To N : sum = sum + x(k) : j = 2 : power(j) = current(j) * voltage(j) Dim pressure(1 to 10) as Double meanpressure = Application. _ Worksheetfunction.Average(pressure) 29 For Loops and Arrays A common application of arrays uses for loops to set elements in an array For k = 1 To 10 x(k) = cos(k*pi/10) Can sum all elements in an array sum = x(1) For k = 2 To NX sum = sum + x(k) 30 ME 209 Computer Programming for Mechanical Engineers 5

V(1) V(2) V(3) V(4) Two-dimensional Arrays View as two-dimensional table of data Row and column subscripts Must set both subscripts in Dim statement Dim e(1 to 4,1 To 6) As Double Same default minimum behavior as 1D I(1) I(2) I(3) I(4) I(5) I(6) e(1,1) e(1,2) e(1,3) e(1,4) e(1,5) e(1,6) e(2,1) e(2,2) e(2,3) e(2,4) e(2,5) e(2,6) e(3,1) e(3,2) e(3,3) e(3,4) e(3,5) e(3,6) e(4,1) e(4,2) e(4,3) e(4,4) e(4,5) e(4,6) 31 Two For Loops for 2D Arrays Two-way table from two-dimensional arrays and nested for loops Need to define P(k) and T(j) arrays prior to executing this code For k = 1 to 10 For j = 1 to 20 rho(i,j) = M*P(k) / (R*T(j)) Next j 32 Worksheets and Arrays Can replace x = Range( A1:T10 ).Value by code below (using numbers only) Const NX As Long = 10, NY As Long = 20 Dim row As Long, col as Long Dim x(1 to NX, 1 To NY) For row = 1 To NX For col = 1 To NY Cells(row,col).Value= x(row,col) Next col Next row Note use of Const for array bounds and for loop limits. Changes to NX or NY can be done by changing Const values 33 The Mysterious Variant Type Variant Variables, declared as scalars, can be equated to an array They then become arrays Used for getting cell data to VBA 34 The Mysterious Variant II Can use array created from variant like any other array Simple input/ output example 35 Worksheet Range to 1D Array Sub exercisea() Dim I As Variant Dim V As Variant I = Range("B1:G1").Value V = Range("A2:A5").Value Setting a Variant to a single row or column gives a two-dimensional array 36 ME 209 Computer Programming for Mechanical Engineers 6

Cells Method for 1D Array Sub exerciseb() Dim I(1 to 6) As Double Dim V(1 to 4) As Double Dim k As Integer For k = 1 To 6 I(k) = Cells(1,k+1).Value For k = 1 To 4 V(k) = Cells(k+1,1).Value 37 Worksheet Range to 2D Array Sub exercisec() Dim e As Variant e = Range("B2:G5").Value Here e is declared as a scalar variant, but becomes an array when set to a worksheet range 38 Cells Method for 2D Array Sub exercised() Dim e(1 To 4, _ 1 To 6) As Double Dim k As Long Dim m As Long For k = 1 To 4 For m = 1 To 6 e(k, m) = Cells(k + 1, _ m + 1).Value Next m 39 LBound and UBound These VBA functions get lower and upper bounds for array dimensions Recall arrays can have more than one dimension, e.g. p(k,m) The arguments are (<array Name>, <dimension>) where dimension = 1, 2, etc. for the first, second, etc. dimension Only look at one- and two-dimensional arrays in this course If <dimension> is omitted it has a value of 1 40 Review Arrays to Procedures When passing arrays to procedures it is not necessary to Dim the array Instead, the argument to handle an array is written with empty parentheses Function mean(x() as Double) As Double Dim k as Long mean = 0 For k = LBound(x) To UBound(x) mean = mean + x(k) mean = mean /(UBound(x) -LBound(x) + 1) 41 Adjustable Size Arrays Two steps needed if we do not know the maximum size of the array First declare array without size: Dim() <ArrayName> As <Type> When size is known use ReDim ReDim(<size>) <ArrayName> Dim x() As Double, N As Long N = InputBox( Enter Size: ) ReDim x(1 To N) 42 ME 209 Computer Programming for Mechanical Engineers 7

Programming Exam Thursday, May 11, 12 1:25 pm Write/debug a simple program using all items except arrays covered during the semester Some students will complete work, many will not Objective is to see how well you can take an assignment, turn it into code, debug the code, and get an operating program Can use text and online help, but cannot use internet to search for code 43 Final Exam Friday, May 18, 12:45 to 2:45 pm Will have questions similar to midterm and quizzes Closed book with same information sheet on commands provided for midterm and quizzes 44 ME 209 Computer Programming for Mechanical Engineers 8