ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions
|
|
- Rachel Wells
- 5 years ago
- Views:
Transcription
1 ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions ENGG1811 UNSW, CRICOS Provider No: 00098G1 W7 slide 1
2 References Chapra (Part 2 of ENGG1811 Text) Topic 19 (chapter 12) Loops Topic 17 (section 10.1) Strings Topic 16 (section 9.2) Built-in Functions ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 2
3 Iteration (Repetition) Very often need to execute statements repeatedly Loops are statements that can do this Process is called iteration Kinds of loop: For (iterate a fixed number of times) While (iterate as long as something is True) Do-Loop (general iteration) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 3
4 A motivating example (1) Let us say you want to use VBA to compute the sum Two cumbersome programs: sum1() and sum2() Sub Sum1() 'A cumbersome program to compute the sum 'This is to motivate for loop Dim sum As Integer sum = Debug.Print "(Sum1) Sum of 1 to 10 is "; sum End Sub ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 4
5 A motivating example (2) Sum2() is also cumbersome but helps you to see the repetition and to progress to Sum3() Sub Sum2() Dim sum As Integer sum = 0 sum initialised to zero sum = sum + 1 sum is 1 after this line sum = sum + 2 sum is after this line sum = sum + 3 sum is after this line sum = sum + 4 sum = sum + 5 sum = sum + 6 sum = sum + 7 sum = sum + 8 sum = sum + 9 sum = sum + 10 VBA (as well as many other computer languages) has a number of constructions to deal with repetitions Sum3() (to be developed in the lecture) uses for-loop Debug.Print "(Sum2) Sum of 1 to 10 is "; sum End Sub ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 5
6 Iteration For For statement sets a loop variable to each value in a range and executes statements forming the loop body for each value: optional For intvar = start To finish Step amount statements Next intvar Loop body start and finish are expressions, evaluated once Step amount is optional (default 1) statements may use (but not change) the value of the loop variable loop must terminate (VBA checks consistency of start, finish and amount) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 6
7 For loop examples ' 1. factorial (assume n is set beforehand) fact = 1 For i = 1 To n fact = fact * i Next i ' fact = n! ' 2. sum = sum of the first n squares (reverse order!) sum = 0 For k = n To 1 Step - 1 sum = sum + k*k Next k ' 3. Compound interest without exponentiation ' (principal P, interest rate r (%), n years) balance = P For y = 1 To n balance = balance * (1.0 + r*0.01) Next y ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 7
8 Iteration While While statement continues to execute statements as long as a Boolean expression is True While boolean-expression statements Wend* Loop guard is evaluated If it is True execute the loop body and go back to start of loop to re-test the guard Otherwise (i.e., it is False) exit loop and continue with rest of program Loop body must change state so that loop guard can eventually become False (else infinite loop) * Why not End While? Beats me. Loop body Loop guard ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 8
9 While loop examples (1) ' 1. Print all powers of 2 less than LIMIT Sub DemoWhile() Const LIMIT = 12 Dim x As Integer End Sub x = 1 While x < LIMIT Debug.Print (x), x = 2 * x Wend Question: What is the output of the following program? Sub QuestionWhile() Const LIMIT = 8 Dim x As Integer End Sub x = 1 While x < LIMIT x = 2 * x Debug.Print (x), Wend (a) (b) 2 4 (c) (d) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 9
10 Iterative algorithms For-loops and While-loops (iterations) are extensively used in computation Excel Goal-Seek and Solver use iterations We will use iterations to find the square root of a real number k x = k Initialise x to k If you repeat the following calculation many times, you will find that x will eventually equal to the square root of k x = x - (x ^ 2 k) / (2 * x) x = x - (x ^ 2 k) / (2 * x) x = x - (x ^ 2 k) / (2 * x) x = x - (x ^ 2 k) / (2 * x) x = x - (x ^ 2 k) / (2 * x) Implementation with for numiter specifies the number of iterations Function SquareRootFor x = k For i = 1 To numiter x = x - (x ^ 2 - k) / (2 * x) Next i SquareRootFor = x ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 10
11 While loop examples Problem: You need to specify the number of iterations in the for-loop. Need trial and error. Better method: Specify an acceptable error and terminate the calculations when error is small enough ' 2. approximation to square root: k for any k >= 0 ' Algorithm: Newton- Raphson. For theory see Wikipedia or ' x 1 = x 0 - f (x 0 ) / f '(x 0 ), where f (x) = x 2 - k and thus f '(x) = 2x Dim x As Double Dim lastx As Double ' current estimate ' previous estimate x = k: lastx = 0 ' guesses While Abs(x lastx) > EPSILON lastx = x x = x - (x ^ 2 k) / (2 * x) Wend ' x k Constant: tiny value representing acceptable error ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 11
12 Pseudocode and refinement How did we come up with the square root solution? Initial version is statement of purpose set x to within EPSILON of k using Newton-Raphson algorithm Express algorithm using English statements and VB control structures (If, While etc): pseudocode Indent subsidiary statements Refine to subprograms and VB statements set initial guess and last guess to suitable starting values While current guess and last guess are too far apart Wend recalculate guess using N-R formula ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 12
13 Pseudocode and refinement Refined pseudocode: remember to update the variable holding the last guess before updating the current guess; Also choose a safe value for the initial guesses set current guess (x) to k [or 1, k/100, any > EPSILON] set last guess (lastx) to 0 While the abs val of the difference is > EPSILON update lastx update x using the formula Wend (when loop exits, x is an excellent approximation to k) Demo: use this loop in a subprogram to show convergence ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 13
14 Other kinds of loop Do-Loop statement is similar to While, but the loop body is always executed at least once: Do statements Loop body Loop While boolean-expression Alternative form uses complemented guard: Do statements Loop Until boolean-expression Can terminate the loop early with the statement Exit Do (also Exit While and Exit For) Loop guard ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 14
15 Excel object model (simplified) VBA programs can interact with the data on a worksheet, create new sheets etc. Workbook, sheets, cells form a hierarchy of objects, manipulated like ordinary variables (can use and/or change) Simplest reference to cells is via top-level Application object: Application.ActiveCell Application.ActiveSheet.Cells(row,col) any integer expression for row and col row counts from 1 to 65535* col counts from 1 (= A) to 255* Can omit Application. Prefix * Excel accepts a wider range than this ENGG1811 UNSW, CRICOS Provider No: 00098G W5 slide 15
16 Excel object model, cont. Each cell has a large number of attributes or properties, recording its contents and appearance. Most can be changed. Most important properties from our viewpoint are Value and Formula, the two attributes easily changed by the user Value is a variant (untyped value) Formula is a string (as it would appear in the formula bar) both can be assigned ENGG1811 UNSW, CRICOS Provider No: 00098G W5 slide 16
17 Worksheet Programming We can use values on the active worksheet as inputs to a program, and overwrite cells to show output and calculated values We can iterate over rows or columns of data We can detect empty cells to stop the iteration Example: running sum to the right of a column (defective subprogram over, to be corrected in the lecture) Developer Macros AddRunningSum ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 17
18 Example: Running sum ' WARNING: contains a deliberate error Sub AddRunningSum() Dim row As Integer ' index always integral Dim col As Integer Dim sum As Double ' numeric values normally real row = 2: col = 1: sum = 0 ' FYI, the : symbol separates multiple simple statements While ActiveSheet.Cells(row, col).value <> "" Wend End Sub sum = sum + ActiveSheet.Cells(row, col).value ActiveSheet.Cells(row, col+1).value = sum ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 18
19 Debugging Loops If a program fails to terminate, press Ctrl-Alt-Break (Break may be labelled Pause), or Esc in the labs VBA interpreter pauses, shows program state: current execution point Hover mouse over variable to show current value Is there a general principle you can apply to all loops? ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 19
20 Iteration termination Loop body must change state so that loop guard can eventually become False (else we have produced an infinite loop) MC Escher (1948) Handteckning [Drawing Hands]; lithograph ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 20
21 Procedures Functions and Subprograms are together called procedures Functions return a single value, should not change program state Subprograms can change state by altering variables outside the procedure altering files outside the application communicating with other applications changing the values of arguments passed by reference (next slide) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 21
22 Calling sub Assuming that you have a sub: Sub SampleSub(x1 as integer, x2 as integer) You can call this sub in another program using either one of the following two methods SampleSub 3 5 Call SampleSub(3,5) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 22
23 Parameters revisited Values passed to procedures are called arguments Variables defined to hold these values are called parameters Parameters are local variables, like ones declared using Dim Data can be passed in two different ways: by value (argument is expression, only value transferred) by reference (argument is variable, parameter acts as a temporary alias) keywords ByVal and ByRef specify which (ByRef is assumed if omitted) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 23
24 Reference Parameters ByRefDemo1 in The workbook Sub halve1(byval x As Double) x = x / 2 End Sub Sub halve2(byref x As Double) x = x / 2 End Sub y = 6.4: z = 6.4 halve1 y ' what is the value of y? halve2 z ' what is the value of z? The keyword ByRef (or none) passes a reference to the argument rather than its value. x becomes an alias for z and changes to x also affect z immediately. With ByVal, or if the argument is not a variable, x is an independent local variable initialised by the argument (6.4). Changing it has no effect outside the procedure. ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 24
25 Example: Swapping values ByRefDemo2 in The workbook Sub Swap(ByRef x1 As Variant, ByRef x2 As Variant) Dim tmp As Variant End Sub tmp = x1 x1 = x2 x2 = tmp Motivation: imagine exchanging the positions of an apple and an orange on the table in front of you. Now do it again using just one hand! y = : z = 6 Swap y, z ' what are the values of y and z? We used the Variant type so the procedure can be used to exchange the contents of variables any type. This is the only recommended use for Variants. Unfortunately, the following does NOT work Swap ActiveSheet.Cells(1,1), ActiveCell ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 25
26 Named Arguments For procedures with long argument lists (especially built-in procedures), arguments can be specified in any order using the notation paramname:=argument Example (see MsgBox Function in VBA Help) Example: ByRefDemo3 in the workbook ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 26
27 Sequential Algorithms VBA is particularly useful for tasks such as Processing rows or columns on one pass Locating cells with particular characteristics Identifying extreme values (max/min) These are called sequential tasks, because they treat the data as a sequence of items, usually stored in cells Standard sequential algorithms can be adapted to solve these kinds of problems ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 27
28 Simple Scans The simplest cases just process each element of a sequence in order (for convenience) Elements are independent End of sequence normally marked by empty cell Pseudocode: column scan set col to the required column number set row to the row where the sequence starts While ActiveSheet.Cells(row, col) is not empty Wend apply required step to this cell move row one cell down ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 28
29 State-based Scans Other cases accumulate history in variables during the scan Element order may or may not matter Variables need to be correctly initialised Examples: AddRunningSum, maximum or minimum calculation, run of equal values, merging ordered sequences, mode of an ordered sequence (you are not likely to need the last few). ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 29
30 Maximum/minimum FindMax in The workbook Max/min calculations maintain a best so far variable May also need to know the position of the (first or last occurrence of) the maximum Pseudocode for maximum of a column: Only works if the column is NOT EMPTY set col to the required column number set row to the row where the sequence starts set max to the value in that cell While ActiveSheet.Cells(row,col) is not empty Wend If cell value is greater than max Then set max to cell value End If move row one cell down ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 30
31 Maximum/minimum, continued If the problem is to highlight all extreme (max or min) values, need two passes First pass finds the extreme value (prev slide) Second pass processes each cell whose value matches the extreme value Next week we will see how cell appearance can be altered (more general than conditional formatting) Macro Recorder used to capture relevant code ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 31
32 Maximum/minimum, continued If the problem is to find min/max for only some cells, can t initialise from the first cell as usual use a Boolean variable to record whether a min/max has been found after the loop the variable tells you whether there was a min/max at all If you need to find out more than one piece of info about a list of values, consider whether you can perform multiple actions on a single pass example: min + max, or min/max + count etc ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 32
33 Example: min of positive values only Problem: Find where the smallest positive value (if any) is in the column containing the active cell Pseudocode, first attempt may or may not work set col to the column containing the active cell set row to the starting row set rowmin to zero ' = undefined minimum position While the cell at (row, col) contains a number If the cell value is positive Then If rowmin = 0 Or cell value < value at (rowmin, col) Then set rowmin to row ' now valid End If End If move row one cell down Wend (Solution developed in lecture) ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 33
34 Strings A string is a sequence of characters Strings in VBA can be of virtually any length (including zero, of course) Components are characters represented internally as codes with numeric value from 0 to 255 each code is interpreted by an output device as a graphic character or special action functions Chr and Asc convert between character and numeric code ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 34
35 Literal Strings String constants are enclosed in double-quote characters " " (not single quotes) How to include a double-quote as a member of the string (the delimiter-as-data problem)? Write it twice, as in "Reference: ""Excel for Experts""" Empty string is denoted by "" ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 35
36 String Operators & concatenates (joins) two strings "c" & "at" (= "cat") "cat" & "ch" & "-22" relational (comparison) operators compare individual characters, so "cat" < "dog" (because "c" < "d") "cat" < "cave" (because "t" < "v") "cat" < "catastrophe" (prefix) "Cat" < "cat" (case sensitive) can change to case-insensitive comparison (to make "Cat" = "cat") by placing Option Compare Text at the top of the module ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 36
37 String Matching The Like operator allows a string expression to be tested against a pattern that includes wildcards strdata Like "pattern" The pattern consists of? any single character # any digit character * zero or more characters [list] any character in list [!list] any character not in list Important notation! Same notation as Access query partial match ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 37
38 String Matching Examples Assume the following values str1 = "cat": str2 = "Route66": str3 = "2*3" Expression Value Reason str1 Like "cat" True ordinary chars OK str1 Like "c?t" True? matches the character a str1 Like "c" False must match whole of string str2 Like "*##" True ends in two digits str2 Like "[A- Z]*" True [A- Z] matches any capital str2 Like "*[!6]" False can't match non-6 at end str2 Like "*[!6]*" True (you work it out!) str3 Like "*3" True * matches 2* str3 Like "#[*]?" True to match special chars * [? literally, enclose in [ ] ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 38
39 Select Case Multiway selection with a common expression: VBA has a simpler way than many If statements any number of each of these can occur Select Case expression Case value statements Case value 1, value 2 statements Case value 1 To value 2 statements Case Is > value statements Case Else statements End Select evaluated first, then matched against each label single value multiple values grouped inclusive range of values open range of values all unmatched values ENGG1811 UNSW, CRICOS Provider No: 00098G W5 slide 39
40 Select Case example Classify a single-character string c Select Case UCase(c) Case "A","E","I","O","U" sym = "vowel" Case "0" To "9" sym = "digit" Case "A" To "Z" sym = "consonant" Case "" sym = "empty Case Else sym = "punctuation" End Select use of UCase saves repeating upper and lower case letter rules ' or Case Like "[A- Z]" ENGG1811 UNSW, CRICOS Provider No: 00098G W5 slide 40
41 Built-in Functions VBA includes a range of mathematical, string and conversion functions Accept one argument (sometimes more than one) and return exactly one value Mathematical functions include Sin, Cos, Tan, Atn (arctangent), all in radians Abs, Sgn, Int (largest int ), Fix (truncate towards 0), Round (to any number of decimal places, including neg) Sqr ( ), Exp (e x ), Log (ln x) Rnd (pseudo-random number) Look up Math Functions in VBE's Help ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 41
42 Built-in Functions, cont. Can also use any* function available to worksheet formulas, using Application.WorksheetFunction.name(args ) Examples (Application. can be omitted): angle = WorksheetFunction.Radians(- 90) payment = WorksheetFunction.PMT(rate, numperiods, _ curvalue) code = WorksheetFunction.Replace(text, start, 3, _ "***") Some expect Range objects (described in a later lecture) as their data sources Look up Worksheet Functions in VBE's Help * except if there s a direct equivalent in VBA, like sin ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 42
43 String and Character Functions Function call Len(str) Mid(str,start,len) Asc(str) Chr(code) LCase(str) Trim(str) Returns number of characters in str len-char substring of str, start; also Left(str,len) and Right(str,len) char code for first char in str Unit string containing char with code str with all upper-case chars converted to lower case (also UCase) str with spaces removed from both ends (also LTrim, RTrim) InStr(str,match) first position in str where match occurs, or 0 Replace(str,match,r epl) String(str,n) str with all occurrences of match replaced by repl (other args possible) n copies of first char of str ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 43
44 Type Conversion Functions Can mix up numeric types (angle + intoffset is evaluated as Double) When explicit conversion is needed, use function: Function name Accepts as argument Returns CStr number String (also Format next slide) CLng number or string Long Integer (rounded if from Double) CDbl number or string Double Val string Integer or Double, ignores trailing junk Round(v,d) number v Rounded to d decimal places Hex integer Hexadecimal string form ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 44
45 Format Function Specialised formatting of numbers and dates Format(expr, fmt) returns a formatted string fmt mixes ordinary characters and formatting codes: Predefined code Displays 0 digit or zero # digit or nothing % percentage placeholder ( 100, show %) e+ e- E+ E- scientific single char or space < > force lower-case or upper-case ddd mmm yy hh nn date/time components (see text) Can also use predefined formats such as Scientific, Percent, Long Date etc. See VBE Help for details ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 45
46 Summary Reference parameters allow a subprogram to change the value of variables declared outside Use pseudocode to express algorithm prior to coding in VB Active sheet and its cells can be addressed directly Sequential algorithms process a row or column of data systematically Some algorithms accumulate values, others process cells locally and order-independently Strings store simple character sequences Built-in functions evaluate commonly-required quantities (string and numeric) Relatively complex tasks can usually be subdivided into easily managed subtasks and solutions combined ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 46
References. Iteration For. Iteration (Repetition) Iteration While. For loop examples
References ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions Chapra (Part 2 of ENGG1811 Text) Topic 19 (chapter 12) Loops Topic 17 (section 10.1)
More informationReferences. Iteration For. Iteration (Repetition) Iteration While. For loop examples
ENGG1811 UNSW, CRICOS Provider No: 00098G W6 slide 1 References ENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Strings and Built-in Functions Chapra (Part 2 of ENGG1811 Text)
More informationReferences. Iteration For. Iteration (Repetition) Iteration While. For loop examples
References ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions Chapra (Part 2 of ENGG1811 Text) Topic 19 (chapter 12) Loops Topic 17 (section 10.1)
More informationENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Processing Cells
ENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Processing Cells ENGG1811 UNSW, CRICOS Provider No: 00098G1 W6 slide 1 Why loops in programming? Let us hear from Mark Zuckerberg
More informationPosition at 3pm. 2-3pm: Moved 50km North. Position at 2pm. Sum3 captures the regular pattern of Sum2 in a new statement, For.
Dead Reckoning ENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Processing Cells Dead reckoning is a navigation technique which computes the current position from The last known
More informationReferences. Parameters revisited. Reference Parameters. Example: Swapping values. Named Arguments
References ENGG1811 Computing for Engineers Week 8 Objects and Collections; Using the Macro Recorder; Shapes Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder ENGG1811 UNSW, CRICOS Provider
More informationENGG1811 Computing for Engineers Week 5 Control Structures for Programming: Selection, Functions
ENGG1811 Computing for Engineers Week 5 Control Structures for Programming: Selection, Functions ENGG1811 UNSW, CRICOS Provider No: 00098G W5 slide 1 The Story So Far You should have some understanding
More informationVBA Handout. References, tutorials, books. Code basics. Conditional statements. Dim myvar As <Type >
VBA Handout References, tutorials, books Excel and VBA tutorials Excel VBA Made Easy (Book) Excel 2013 Power Programming with VBA (online library reference) VBA for Modelers (Book on Amazon) Code basics
More informationThe University of New South Wales SAMPLE Final Examination. November 2008 ENGG1811 Computing for Engineers
Family Name: Given Names: Student Number: Signature: The University of New South Wales SAMPLE Final Examination November 2008 ENGG1811 Computing for Engineers Time allowed: 2 hours Total number of questions:
More informationReferences. Parameters revisited. Reference Parameters. Example: Swapping values. Named Arguments
References ENGG1811 Computing for Engineers Week 7 Objects and Collections; Using the Macro Recorder; Shapes Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder ENGG1811 UNSW, CRICOS Provider
More informationThis Week. Trapezoidal Rule, theory. Warmup Example: Numeric Integration. Trapezoidal Rule, pseudocode. Trapezoidal Rule, implementation
This Week ENGG8 Computing for Engineers Week 9 Recursion, External Application Interfacing Monday: numeric integration example, then first part of the material Wednesday 9am: rest of the new material Wednesday
More informationENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder. Examples
References ENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder Week 8 Objects and Collections; Using the Macro Recorder; Shapes ENGG1811 VBA Reference
More informationLanguage Fundamentals
Language Fundamentals VBA Concepts Sept. 2013 CEE 3804 Faculty Language Fundamentals 1. Statements 2. Data Types 3. Variables and Constants 4. Functions 5. Subroutines Data Types 1. Numeric Integer Long
More informationPhụ lục 2. Bởi: Khoa CNTT ĐHSP KT Hưng Yên. Returns the absolute value of a number.
Phụ lục 2 Bởi: Khoa CNTT ĐHSP KT Hưng Yên Language Element Abs Function Array Function Asc Function Atn Function CBool Function CByte Function CCur Function CDate Function CDbl Function Chr Function CInt
More informationSt. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5
Computing Science Software Design & Development (Part 1 Computer Programming) National 5 VARIABLES & DATA TYPES Variables provide temporary storage for information that will be needed while a program is
More informationOutline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014
Midterm Review Larry Caretto Mechanical Engineering 209 Computer Programming for Mechanical Engineers April 4, 2017 Outline Excel spreadsheet basics Use of VBA functions and subs Declaring/using variables
More informationPython allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:
1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,
More informationENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing
ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 1 This Week Wednesday am: Will include discussion about assignment
More informationOutline. Data and Operations. Data Types. Integral Types
Outline Data and Operations Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Data and Operations
More informationDOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES
Chapter 1 : Examples of commonly used formulas - Office Support A collection of useful Excel formulas for sums and counts, dates and times, text manipularion, conditional formatting, percentages, Excel
More informationMacro Programming Reference Guide. Copyright 2005 Scott Martinez
Macro Programming Reference Guide Copyright 2005 Scott Martinez Section 1. Section 2. Section 3. Section 4. Section 5. Section 6. Section 7. What is macro programming What are Variables What are Expressions
More informationENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder. Examples
References ENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder Week 8 Objects and Collections; Using the Macro Recorder; Shapes Note: there is very limited
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationLong (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000.
QuickCalc User Guide. Number Representation, Assignment, and Conversion Variables Constants Usage Double (or DOUBLE ) floating-point variables (approx. 16 significant digits, range: approx. ±10 308 The
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More information1. Introduction to Microsoft Excel
1. Introduction to Microsoft Excel A spreadsheet is an online version of an accountant's worksheet, which can automatically do most of the calculating for you. You can do budgets, analyze data, or generate
More informationStrings in Visual Basic. Words, Phrases, and Spaces
Strings in Visual Basic Words, Phrases, and Spaces Strings are a series of characters. Constant strings never change and are indicated by double quotes. Examples: Fleeb Here is a string. Strings are a
More informationFunctions. Lecture 6 COP 3014 Spring February 11, 2018
Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its
More informationHigher Computing Science Software Design and Development - Programming Summary Notes
Higher Computing Science Software Design and Development - Programming Summary Notes Design notations A design notation is the method we use to write down our program design. Pseudocode is written using
More informationReferences. Notices Week 5. A Note on the Textbook. Algorithms and programs. Context
ENGG1811 Computing for Engineers Week 5 Introduction to Programming and Visual Basic for Applications References Chapra (std text Part 2), Topics 8, 9 (Chapters 1, 2). Some of this week s material is derived
More informationVisual Basic for Applications
Visual Basic for Applications Programming Damiano SOMENZI School of Economics and Management Advanced Computer Skills damiano.somenzi@unibz.it Week 1 Outline 1 Visual Basic for Applications Programming
More informationLanguage Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */
Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,
More informationReferences. Arrays. Default array bounds. Array example. Array usage. Shepherd, pp (Arrays) Shepherd, Chapters 12, 13
ENGG1811 UNSW, CRICOS Provider No: 00098G W7 slide 1 References ENGG1811 Computing for Engineers Week 7 Arrays, Objects and Collections; Using the Macro Recorder Shepherd, pp.20-22 (Arrays) Shepherd, Chapters
More informationVBA Collections A Group of Similar Objects that Share Common Properties, Methods and
VBA AND MACROS VBA is a major division of the stand-alone Visual Basic programming language. It is integrated into Microsoft Office applications. It is the macro language of Microsoft Office Suite. Previously
More informationFunction Exit Function End Function bold End Function Exit Function
The UDF syntax: Function name [(arguments) [As type] ] [As type] [statements] [name = expression] [Exit Function] [statements] [name = expression] - name the name of the function - arguments a list of
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationFANF. programming language. written by Konstantin Dimitrov. Revision 0.1 February Programming language FANF 1 / 21
programming language FANF written by Konstantin Dimitrov Revision 0.1 February 2014 For comments and suggestions: knivd@me.com Programming language FANF 1 / 21 Table of Contents 1. Introduction...3 2.
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationThe$University$of$New$South$Wales$ SAMPLE'Final$Examination$ Semester$1,$2016$ '' ENGG1811'Computing'for'Engineers'
FamilyName: GivenNames: ' B' StudentNumber: Signature: TheUniversityofNewSouthWales SAMPLE'FinalExamination Semester1,2016 2017 Semester 2, 2017 '' ENGG1811'Computing'for'Engineers' Timeallowed:2'hours'
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationCivil Engineering Computation
Civil Engineering Computation First Steps in VBA Homework Evaluation 2 1 Homework Evaluation 3 Based on this rubric, you may resubmit Homework 1 and Homework 2 (along with today s homework) by next Monday
More informationLong (LONGMATH) variables may be used the same as short variables. The syntax is the same. A few limitations apply (see below).
Working with Long Numbers. Long Variables Constants You define a long variable with the LONG statement, which works similar to the DIM statement. You can define long variables and dimension long variable
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationL4X v2.0 Reference. (v December 2008) David Fowle
L4X v2.0 Reference (v2.0.0.4-01 December 2008) http://www.pdfing.com/l4x 2 L4X v2.0 Reference Table of Contents Foreword Part I L4X Language Summary. 1 1 Importing... Strings of Text. 1 2 Importing...
More informationLSP 121. LSP 121 Math and Tech Literacy II. Topics. Loops. Loops. Loops
LSP 121 Math and Tech Literacy II Greg Brewster DePaul University Topics The FOR loop Repeats a set of statements a fixed number of times The WHILE loop Repeats a set of statements until a condition is
More informationActive Planner. How to Create and Use Database Query Formulas
Active Planner How to Create and Use Database Query Formulas Table of Contents Introduction... 1 Database Query Part 1 - The Basics... 2 Database Query Part 2 Excel as the Data source... 12 Database Query
More informationSWITCH(DatePart("w",DateOfYear) IN(1,7),"Weekend",DatePart("w",DateOfYear) IN(2,3,4,5,6),"Weekday") AS DayType,
SeQueL 4 Queries and their Hidden Functions! by Clark Anderson A friend recently exclaimed Can you really use this function in SQL! In this article of my series I will explore and demonstrate many of the
More informationCHAPTER 4: MICROSOFT OFFICE: EXCEL 2010
CHAPTER 4: MICROSOFT OFFICE: EXCEL 2010 Quick Summary A workbook an Excel document that stores data contains one or more pages called a worksheet. A worksheet or spreadsheet is stored in a workbook, and
More informationIFA/QFN VBA Tutorial Notes prepared by Keith Wong
IFA/QFN VBA Tutorial Notes prepared by Keith Wong Chapter 5: Excel Object Model 5-1: Object Browser The Excel Object Model contains thousands of pre-defined classes and constants. You can view them through
More informationEnableBasic. The Enable Basic language. Modified by Admin on Sep 13, Parent page: Scripting Languages
EnableBasic Old Content - visit altium.com/documentation Modified by Admin on Sep 13, 2017 Parent page: Scripting Languages This Enable Basic Reference provides an overview of the structure of scripts
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration
ENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 1 References & Info Chapra (Part 2 of ENGG1811 Text) Topic 21 (chapter
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationUnit-II Programming and Problem Solving (BE1/4 CSE-2)
Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite
More informationNumerical Methods in Scientific Computation
Numerical Methods in Scientific Computation Programming and Software Introduction to error analysis 1 Packages vs. Programming Packages MATLAB Excel Mathematica Maple Packages do the work for you Most
More informationVBSCRIPT - INTERVIEW QUESTIONS
VBSCRIPT - INTERVIEW QUESTIONS http://www.tutorialspoint.com/vbscript/vbscript_interview_questions.htm Copyright tutorialspoint.com Dear readers, these VBScript Interview Questions have been designed specially
More informationCOMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.
COMP1730/COMP6730 Programming for Scientists Data: Values, types and expressions. Lecture outline * Data and data types. * Expressions: computing values. * Variables: remembering values. What is data?
More informationArrays Structured data Arrays What is an array?
The contents of this Supporting Material document have been prepared from the Eight units of study texts for the course M150: Date, Computing and Information, produced by The Open University, UK. Copyright
More informationLESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long
LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be
More informationMicrosoft Office Excel Use Excel s functions. Tutorial 2 Working With Formulas and Functions
Microsoft Office Excel 2003 Tutorial 2 Working With Formulas and Functions 1 Use Excel s functions You can easily calculate the sum of a large number of cells by using a function. A function is a predefined,
More informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features
More informationLECTURE 0: Introduction and Background
1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationCondition Controlled Loops. Introduction to Programming - Python
Condition Controlled Loops Introduction to Programming - Python Decision Structures Review Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected!
More informationFunctional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute
Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute Module # 02 Lecture - 03 Characters and Strings So, let us turn our attention to a data type we have
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationLecture 2 FORTRAN Basics. Lubna Ahmed
Lecture 2 FORTRAN Basics Lubna Ahmed 1 Fortran basics Data types Constants Variables Identifiers Arithmetic expression Intrinsic functions Input-output 2 Program layout PROGRAM program name IMPLICIT NONE
More informationVISUAL BASIC 6.0 OVERVIEW
VISUAL BASIC 6.0 OVERVIEW GENERAL CONCEPTS Visual Basic is a visual programming language. You create forms and controls by drawing on the screen rather than by coding as in traditional languages. Visual
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence
More informationAgenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals
Agenda & Reading COMPSCI 80 S Applications Programming Programming Fundamentals Data s Agenda: Data s Value s Reference s Constants Literals Enumerations Conversions Implicitly Explicitly Boxing and unboxing
More informationIntroduction to: Computers & Programming: Review prior to 1 st Midterm
Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in
More informationDATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)
Technology & Information Management Instructor: Michael Kremer, Ph.D. Database Program: Microsoft Access Series DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6) AGENDA 3. Executing VBA
More informationlab MS Excel 2010 active cell
MS Excel is an example of a spreadsheet, a branch of software meant for performing different kinds of calculations, numeric data analysis and presentation, statistical operations and forecasts. The main
More informationvariables programming statements
1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual
More informationIntroduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur
Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture - 23 Introduction to Arduino- II Hi. Now, we will continue
More informationMarch 28, Excel Essentials. Jim Snediker. Suzi Huisman
March 28, 2019 Excel Essentials Jim Snediker Suzi Huisman 1 What is a Spreadsheet? A spreadsheet is the computer equivalent of a paper ledger sheet. Worksheet new name for Spreadsheet Workbook one file
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationegrapher Language Reference Manual
egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction
More informationComputer Programming
Computer Programming Introduction Marius Minea marius@cs.upt.ro http://cs.upt.ro/ marius/curs/cp/ 26 September 2017 Course goals Learn programming fundamentals no prior knowledge needed for those who know,
More informationPublic Function randomdouble(lowerbound As Double, upperbound As Double) As Double On Error Resume Next
Table of Contents Introduction...1 Using VBA Functions...1 Accessing Visual Basic in Excel...2 Some Example Functions...3 Random Numbers...4 RandomDouble...4 randomint...4 Using the random numbers...5
More informationITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University
ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs
More informationTable : IEEE Single Format ± a a 2 a 3 :::a 8 b b 2 b 3 :::b 23 If exponent bitstring a :::a 8 is Then numerical value represented is ( ) 2 = (
Floating Point Numbers in Java by Michael L. Overton Virtually all modern computers follow the IEEE 2 floating point standard in their representation of floating point numbers. The Java programming language
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationThe$University$of$New$South$Wales$ SAMPLE'Final$Examination$ Semester$1,$2016$ '' ENGG1811'Computing'for'Engineers'
FamilyName: GivenNames: ' B' StudentNumber: Signature: TheUniversityofNewSouthWales SAMPLE'FinalExamination Semester1,2016 2017 '' ENGG1811'Computing'for'Engineers' Timeallowed:2'hours' Readingtime:10'minutes
More informationDATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan
DATA 301 Introduction to Data Analytics Microsoft Excel VBA Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca DATA 301: Data Analytics (2) Why Microsoft Excel Visual Basic
More informationVBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide
VBA Visual Basic for Applications Learner Guide 1 Table of Contents SECTION 1 WORKING WITH MACROS...5 WORKING WITH MACROS...6 About Excel macros...6 Opening Excel (using Windows 7 or 10)...6 Recognizing
More informationAdding records Pasting records Deleting records Sorting records Filtering records Inserting and deleting columns Calculated columns Working with the
Show All About spreadsheets You can use a spreadsheet to enter and calculate data. A spreadsheet consists of columns and rows of cells. You can enter data directly into the cells of the spreadsheet and
More informationDownloaded from Chapter 2. Functions
Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create
More information6/14/2010. VBA program units: Subroutines and Functions. Functions: Examples: Examples:
VBA program units: Subroutines and Functions Subs: a chunk of VBA code that can be executed by running it from Excel, from the VBE, or by being called by another VBA subprogram can be created with the
More informationENGG1811 Computing for Engineers
Family Name: Given Names: B Student Number: Signature: The University of New South Wales SAMPLE Final Examination Semester 2, 2015 ENGG1811 Computing for Engineers Time allowed: 2 hours Reading time: 10
More informationAppendix A1 Visual Basics for Applications (VBA)
Credit Risk Modeling Using Excel and VBA with DVD By Gunter Löffler and Peter N. Posch 2011 John Wiley & Sons, Ltd. Appendix A1 Visual Basics for Applications (VBA) MACROS AND FUNCTIONS In this book, we
More informationIntroduction to the Java Basics: Control Flow Statements
Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared
More informationPA R T. A ppendix. Appendix A VBA Statements and Function Reference
PA R T V A ppendix Appendix A VBA Statements and Reference A d Reference This appendix contains a complete listing of all Visual Basic for Applications (VBA) statements (Table A-1 ) and built-in functions
More informationFormulas, LookUp Tables and PivotTables Prepared for Aero Controlex
Basic Topics: Formulas, LookUp Tables and PivotTables Prepared for Aero Controlex Review ribbon terminology such as tabs, groups and commands Navigate a worksheet, workbook, and multiple workbooks Prepare
More informationUsing Custom Number Formats
APPENDIX B Using Custom Number Formats Although Excel provides a good variety of built-in number formats, you may find that none of these suits your needs. This appendix describes how to create custom
More informationCS 115 Lecture 4. More Python; testing software. Neil Moore
CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement
More informationFunctions in Excel. Structure of a function: Basic Mathematical Functions. Arithmetic operators: Comparison Operators:
Page1 Functions in Excel Formulas (functions) are equations that perform calculations on values in your spreadsheet. A formula always starts with an equal sign (=). Example: =5+2*7 This formula multiples
More information