Moving from C++ to VBA



Similar documents
VB.NET Programming Fundamentals

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Moving from CS 61A Scheme to CS 61B Java

Lecture 2 Notes: Flow of Control

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

6. Control Structures

Conditions & Boolean Expressions

Chapter 5 Functions. Introducing Functions

Answers to Review Questions Chapter 7

Goals for This Lecture:

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Example of a Java program

Comp151. Definitions & Declarations

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Object Oriented Software Design

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Passing 1D arrays to functions.

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

PIC 10A. Lecture 7: Graphics II and intro to the if statement

While Loop. 6. Iteration

Common Beginner C++ Programming Mistakes

C++ INTERVIEW QUESTIONS

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter One Introduction to Programming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Informatica e Sistemi in Tempo Reale

Chapter 8 Selection 8-1

Basics of I/O Streams and File I/O

In this Chapter you ll learn:

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Appendix K Introduction to Microsoft Visual C++ 6.0

C++ Language Tutorial

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Ch 7-1. Object-Oriented Programming and Classes

OpenOffice.org 3.2 BASIC Guide

Chapter 5. Selection 5-1

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Data Structures using OOP C++ Lecture 1

The While Loop. Objectives. Textbook. WHILE Loops

The if Statement and Practice Problems

13 Classes & Objects with Constructors/Destructors

TIP: To access the WinRunner help system at any time, press the F1 key.

Introduction to Matlab

SAPScript. A Standard Text is a like our normal documents. In Standard Text, you can create standard documents like letters, articles etc

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

Sources: On the Web: Slides will be available on:

7.7 Case Study: Calculating Depreciation

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

UEE1302 (1102) F10 Introduction to Computers and Programming

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Compiler Construction

COMPUTER SCIENCE 1999 (Delhi Board)

Chapter 9 Text Files User Defined Data Types User Defined Header Files

5 Arrays and Pointers

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

This copy of the text was produced at 20:37 on 4/10/2014.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

AP Computer Science Java Subset

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

An Incomplete C++ Primer. University of Wyoming MA 5310

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Computer Organization

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Visual Basic Cheat Sheet

Chapter 2 Introduction to Java programming

Variables, Constants, and Data Types

Changing the Display Frequency During Scanning Within an ImageControls 3 Application

Visual Basic Programming. An Introduction

if and if-else: Part 1

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Formatting Numbers with C++ Output Streams

Introduction to Visual C++.NET Programming. Using.NET Environment

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

Introduction to Java

Using Casio Graphics Calculators

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Visual Logic Instructions and Assignments

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

«W3Schools Home Next Chapter» JavaScript is THE scripting language of the Web.

C PROGRAMMING FOR MATHEMATICAL COMPUTING

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

JavaScript: Control Statements I

T-SQL STANDARD ELEMENTS

PL / SQL Basics. Chapter 3

Transcription:

Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry Caretto Moving from to These notes are intended to ease the transition between and for students who are moving between these two languages. The next page shows the same program in both languages. You may want to look at those listings to get an overview of what the differences are before reading the detailed description of the differences below. Entering the program Both languages allow you to (a) enter a statement on one line, (b) to continue a statement over several lines, and (c) to enter more than one statement on a line. The different ways in which this is done are summarized in the table below. (<Enter> denotes the Enter key.) End of statement at end of line ;<Enter> <Enter> End of line for statement continued to next line (see note below) <Enter> _<Enter> End of statement before another statement on the same line ; : Note: To continue to another line in enter a space then the underscore before <Enter>. commands are all typed in lower case and the language is case sensitive. That is, you can have test and Test as different variables in. is not case sensitive. Test and test are the same variable. You can enter variables and keywords in all lowercase, all uppercase or any combination. The Visual Basic Editor (VBE) will set keywords into particular cases and will give the variables you declare the same case structure as they have in your Dim statements. Multiple Statements in a Control Structure In braces () are used to define the start and end of a group of statements in a particular control structure. This includes the complete set of all statements in a function, statements in various parts of an If-Else If block, statements in a for loop and statements in while loops. (Braces are not needed if there is only one statement in the structure.) In the multiple statements do not use braces. Instead, there is an additional statement to terminate the control structure: End Function, End If, Next (to end a For loop), and Loop to end a conditional loop that starts with Do. Comments In, single line comments start with a double forward slash (//). In single line comments start with an apostrophe ( ). There is no equivalent to s multiline comment that starts with a /* and end with an */. In a single line comment may be placed at the end of a line that is not the end of a statement (a line that ends without a semicolon.) This cannot be done in ; a statement that is continued to the next line (with the space+underscore) cannot have a comment following the underscore. Data types and have similar data types, but they do not all have the same names. The table below shows some equivalent data types in the two languages. int double string bool No Equivalent Long Double String Boolean Date Jacaranda (Engineering) 3314 Mail Code Phone: N/A Email: lcaretto@csun.edu 8348 Fax: 818.677.7062

Moving from to ME309, L. S. Caretto, Spring 2014 Page 2 #include <iostream> #include <cmath> using namespace std; int main() cout << "Enter the argument, x, to compute exp(x): "; double x; cin >> x; const int maxn = 100; // avoid infinite loop const double maxerror = 1e-12; // desired error bool converged = false; // loop control var double term = 1; // initial exp(x) term double sum = term; // initialize sum int n = 0; // initialize counter while (!converged && n < maxn) // start loop n++; // increment counter term *= x / n; // get new term sum += term; // update partial sum converged = fabs(term) // convergence cond <= maxerror * fabs( sum ); if (converged) // output value cout << "sin(" << x << //if solution is ") = " << sum << "\n"; // converged or // error message else cout << "No convergence\n"; return EXIT_SUCCESS; Option Explicit Sub getexpx() Dim x As Double x = InputBox("Enter x to compute exp(x)") Const maxn As Integer = 100 Const maxerror As Double = 1e-12 Dim converged As Boolean converged = False Dim term As Double term = 1 Dim sum As Double sum = term Dim n As Integer n = 0 Avoid infinite loop desired error loop control variable General series term Running series sum Do While (Not converged And n < maxn) Loop n = n + 1 term = term * x / n sum = sum + term converged = Abs(term) <= _ maxerror * Abs(sum) If converged Then Else End If End Sub MsgBox "exp(" & x & ") = " & sum MsgBox "No convergence in getexpx" Convergence condition

Moving from to ME309, L. S. Caretto, Spring 2014 Page 3 Declaring variables Declaration statements in start with the variable type and several variables can be assigned the same type in a single statement; e.g., double x, y, z Declaration statements in start with the word Dim followed by the variable name followed by the keyword As followed by the data type. Although several variables can be declared in one statement, the data types must be repeated for each variable. Two examples are shown below. Dim x As Double, y as double, z As Double Dim s As String, k As Integer, R As Double Operators The following arithmetic and relational operations are the same in and : + * < <= => and >. Also both languages use the equal sign as the assignment operator (x = y + z). In the forward slash division operator (/) always produces a real result, even if the two operands are integers. To get integer division in one has to use the backslash operator (\). In there is only one division operator, the forward slash. It produces a real result if either the numerator or denominator is real. If both the numerator and denominator are integer, the result is an integer. The following operators are different in the two languages. The third entry (fourth column) shows the string concatenation operator, an & in and a + in. (The + can also be used in.) Compute x y Misc Relational equal/not equal Logical Operators pow(x,y) & + ==!= &&! x^y Mod & = <> And Or Not The combination operators (++, --, +=, -=, /=, *=, etc.) do not exist in. Procedures In, there are only function procedures. In there are two types of procedures: functions and subs. A sub procedure in is like a void function in ; neither returns a value to the calling program through the procedure name. functions return a value to the program that calls the function by setting the function name equal to a value. functions use a return statement in the function to return a value to the program that calls them. Because all procedures are functions, there is no need to use the word function in the function header. The pattern for a function header <function type> <function name> ( <argument list> ) The argument list for a function consist of zero or more entries like the following <data type> <variable name> When there is more than one variable in the argument list, all variables, except the last one, are followed by commas. Examples of function headers are shown below: bool leap( int year ) int getvalidint( int xmin, int xmax, string name ) The header for a function is shown below: Function <function name> ( <argument list> ) As <function type> The argument list for a function consist of zero or more entries like the following <variable name> As <data type> Like the argument list in, when there is more than one variable in the argument list, all variables, except the last one, are followed by commas. The function headers that would be used in place of the function headers shown above are given below:

Moving from to ME309, L. S. Caretto, Spring 2014 Page 4 Function leap( year As Long ) As Boolean Function getvalidint(xmin As Long, xmax As Long, name As String ) As Long The full code for a function that inputs a year and returns true if the year is a leap year (or false if it is not) is shown below for (on the left) and. bool leap( int year) return ( year % 4 == 0 ) && ( year % 100!= 0 ) ( year % 400 == 0 ); Passing function parameters by value or by reference Function leap( year As Long ) As _ Boolean leap = ( year Mod 4 = 0 ) And ( year Mod 100 <> 0) Or ( year Mod 400 = 0 ) End Function There are two ways to pass a variable to a function (or sub in ). The first, known as pass-byreference, is to pass the memory location of the variable. In this case any changes to the corresponding variable in the function (or sub) take place in the corresponding variable in the calling program. In the alternative, pass-by-value, only the value of the variable in the calling program is passed to the function (or sub). Any changes to the variable in the function (or sub) do not affect the corresponding variable in the calling program. In the default is pass-by- value; in the default is pass-by-reference. These defaults and the changes required to obtain the alternative as compared in the table below. Pass-by-value bool f(double x) Function bool (ByVal x as Double) as Boolean Pass-by-reference bool f (double& x) Function bool ( x as Double) as Boolean If else if statements There are several minor differences between these choice statements in and as shown in the comparison below. In both languages the final else block is optional. if (<condition1>) <statements done if condition1 is true> else if ( <condition2> ) <statements done if condition2 is true> else if ( <condition3> ) <statements done if condition3 is true> <other possible else if statements> else <statements done if all conditions false> The conditions are placed in parentheses. The word then is not used after the conditions. Statements are placed in braces. Use two separate words: else if There is no end if. The words if and else must be lower case. Count-controlled looping If <condition1> Then <statements done if condition1 is true> ElseIf <condition2> Then <statements done if condition2 is true> ElseIf <condition3> Then <statements done if condition3 is true> <other possible ElseIf statements> Else <statements done if all conditions false> End If The conditions are not placed in parentheses. The word Then is used after the conditions. Statements are not placed in braces. ElseIf is one word. An End If is required. The words else, if elseif and end can be typed in any case; the editor will format them as shown. Both and use a for loop, but there is no direct comparison because the for loop in is much more powerful (and more complex) than the one in. The comparison below shows the for loop and its equivalent in. The general structures are shown in the first row and the two code versions for a specific example are shown in the second row.

Moving from to ME309, L. S. Caretto, Spring 2014 Page 5 for ( <index> = <start>; <index> <= <end>; <index>+=<increment> ) <loop statements that can use index> for (k = 1; k <= 10; k += 2) cout >> k >> endl; cout >> 2 * k >> endl;. Conditional looping For <index> = <start> To <end> Step <increment> <loop statements that can use index> Next <index> For k = 1 to 10 Step 2 msgbox k msgbox 2 * k Next k has more forms of conditional looping than. Both have loops on while conditions where the loop continues so long as the condition is true. also has a loop on an until condition in which the loop continues while the condition is false. Each language has two while loops. One starts with a test and will not be executed if the condition is false at the start of the loop. The other has its test at the end of the loop so that the loop code will always execute at least once. These two loops are compared below. Arrays while ( <condition> ) <loop statements > do <loop statements > while ( <condition> ); Do While <condition> < loop statements > Loop Do < loop statements > Loop While <condition> The basic notational differences between different array types are shown in the table below. Notation for one-dimensional arrays A[k] A(k) Notation for two-dimensional arrays A[k][m] A(k,m) Default lowest subscript 0 0 (or Option Base 1) Can redefine lowest subscript for each array No Yes The size of an array is declared in the same statements used to declare a variable. An example of this in is: double x(10), b(10), A(10,10). Note that the number 10 in this example represents the number of elements in the array. The array index runs from 0 to 9. The same statement in, assuming the default minimum subscript of zero, is: Dim x(9) as Double, b(9) as Double, A(9,9) as Double. Note that in the dimension information represents the maximum subscript. can redefine the default minimum subscript as one by placing the statement, Option Base 1, in the declarations section of the module. can also specify both the minimum and maximum subscript for each array by a statement of the following form: Dim y(2 To 7) as Double, B(3 to 8, -9 To -4) As Double. Passing arrays to functions is compared in the table below. The use of the global variable, LIM, is required in to maintain consistency in array dimensions between the calling program and the function. It is not required in. In both the and statements below the array index can run from 0 to 9. This is the difference between the practice of setting the number of array component in the dimension information and the practice of setting the maximum subscript in the dimension information. Global variable const int LIM = 10 const LIM as Long = 9 Calling program int a[lim]; int b[lim][lim]; f = fun(a, b); Dim a(0 to LIM) As Double Dim b(0 To LIM,0To LIM) As Double f = fun(a,b) Function header Int f( int a[], int b[][lim] ) Function f ( A() As Long, B() ) As Long