Programs and programming A program is a very
















































- Slides: 48

Programs and programming A program is a very specific set of rules that tell the computer what to do. It is a sequence of primitives to be executed by a computer in order to automate a certain business, industrial or scientific task. n The process of creating a program is called programming. n The computer only knows what it is told through programs, so they must be accurate and very specific. n

Common computer primitives: ¨ Calculating an arithmetical or a logical expression and generating a value ¨ Storing/retrieving a value into/from the memory ¨ Comparing the contents of two memory locations and selecting one of two alternatives ¨ Accepting a value from an input device ¨ Sending a value to an output device ¨ Sending and receiving of audio and video streams ¨ repeating a group of primitives

Steps in programming n n n Deciding if there is a task to be accomplished or problem to be solved using a computer, eg, is there a need for a program? Determining the nature of the task or problem, eg, what must the program do? Developing a plan that will accomplish the task or solve the problem, eg, generating the step-by-step process that the program will follow (algorithm) Converting the plan into a computer language program Implementing the program to accomplish the task or solve the problem Testing the program to ensure it accomplishes task or solves problem defined earlier

Types of programming and languages Procedural: Monolithic programs that run from start to finish with no intervention from user other than input. Uses variables, structures, and functions. There is a root function. Other functions are called inside. n Languages: ¨Basic, COBOL, FORTRAN, C, Pascal n

Types of programming and languages Object-oriented: Apart from variables, structures, and functions used in procedural programs, it also uses classes. A class contains a collection of variables (properties) and functions (methods). n Languages: ¨C++, Object Pascal, Java, Eiffel n

Types of programming and languages Object Oriented/Event Driven (OOED) or Visual: Programs that use objects which respond to events. Special classes are used to represent visual objects. Small segments of code are associated with each object. n Languages: ¨Visual Basic, Delphi, Visual C++ n

Levels of computer languages n n n Low Level: at the level of the computer, that is, in binary (0 -1) format Intermediate level: close to the computer but uses English words or mnemonics, eg, Assembler, that is converted directly into binary High Level: at the level of the programmer using English words and clearly defined syntax; must be converted or translated into binary for computer to implement it, eg, Visual Basic Computer can execute only a binary form of a program Need a software program to handle the conversion of high-level into binary

Language translation process Total = 0 10111000 11011000 Current = 10 10110001 00000100 Do while current <> 0 11100010 10101000 Total = Total + Current 11100011 0001 Current = Current – 1 Loop Translation Program 10111000 110110001 00000100 11100010 10101000 11100011 0001 High level language program 11100010 10101000 Machine language program

Translating from High-level Language to Binary Interpreted: each statement translated as it is executed--slow but easy to use while developing programs n Compiled: entire program is converted to binary--executes faster, but more difficult to use (. exe files are compiled programs) n VB is interpreted during creation and testing but can then be compiled into an. exe file n

Languages used in this course Visual Basic. For the demonstration purposes. Some examples demonstrated. n Visual Basic for Applications (VBA). Subset of full-fledged Visual Basic adapted to the applications of Microsoft Office. Used to solve many business problems. n

Variables n n Named memory locations where you can store data values Can imagine them as buckets with a label on them 5 Age

Variables (Cont. ) Contain values that are expected to change n When a variable changes, it is similar to taking the current item out of the bucket and replacing it with a new item n 8 5 Age

Variables n n n Variables are named locations in memory (memory cells) in which we store data that will change at run time Variable names in Visual Basic VB: ¨ Must begin with letter ¨ can’t include period ¨ can’t be over 255 characters ¨ are not case-sensitive ¨ Contain only letters, numbers, and underscore character ( _ ), No spaces, punctuation marks ¨ Be any word except a VB reserved word, E. g. End or Sub Example variable names: ¨ Video. Price for Video Rental Price ¨ Taxes for taxes on this price ¨ Amount. Due for sum of price and taxes ¨ YTDEarnings for year to date earnings ¨ Emp. Last. Name for employee’s last name

Variable Name Example (Yes or No? ) Radius n 8_student n Number_1 n Number 2 n Hours_worked n Gross Pay n Net/Pay n

Data Types n n A data type specifies the type of data that is assigned to a variable or constant Two primary types of data in VB ¨ n numeric and string Numeric data can be used in arithmetic operations String data should not be used in arithmetic Numeric data types can be subdivided into specific types: - currency $55, 567. 78 - integer 255 - single 567. 78 - long (integer) 35, 455 - double 567. 78129086 - Boolean True or False

Data types Numeric Range Data Type Single 1. 4 E-45 to 3. 4 E 38 and -3. 4 E 38 to -1. 4 e-45 Precision Number of Bytes Double 4. 9 E-324 to 1. 8 E 38 and -1. 8 E 308 to -4. 9 E-324 Fifteen 8 significant digits Currency -922, 337, 203, 685, 477. 5808 4 places to 8 to 922, 37, 203, 685, 477. 5807 right of decimal Seven 4 significant digits

Data types Numeric Range Precision Data Type Integer -32, 768 to 32, 767 Whole numbers Long -2, 147, 483, 648 to Whole 2, 147, 483, 647 numbers Date January 1, 100 to Not December 31, 9999 applicable Boolean True or False Not applicable Numb er of Bytes 2 4 8 2

Data types Numeric Data Type String (variable length) String (fixed length) Variant Range Precision N/A N/A adjusted Number of Bytes 10 bytes+length of string Length of string 8

Integer Variables Store integers between -32, 768 and 32, 767 n Require no decimal point n If the number is outside of the range Use the Long data type n

Long Integer Variables Used to store integers between 2, 147, 483, 648 and 2, 147, 483, 647 n Must be used whenever an integer number exceeds the range for the Integer type n

Single Precision Variables Represents numbers which have both a whole and a fractional part n Used to store values ranging in value from -3. 402823 E 38 to -1. 401298 E-45 for negative values and from 1. 401298 E-45 to 3. 402823 E 38 for positive values n Can store numbers with greater precision than integers n

Double-Precision Variables n n Store large floating point numbers, but require twice as many bytes of storage compared to type Single Stored as floating-point numbers ranging in value from - 1. 79769313486232 E 308 to 4. 94065645841247 E-324 for negative values and from 4. 94065645841247 E-324 to 1. 79769313486232 E 308 for positive values

Single vs. Double n Use Single unless the calculation requires greater precision n Not only does Double take more memory to store, but it also requires more time to run than type Single

Boolean Variables n Can be used whenever a variable may have one of only two possible values - True or False, Off or On, etc. n Frequently used in statements which require a test of whether something is true or false.

String Variables n Can hold any character, word, or phrase that the keyboard can produce. n In VB there are two kinds of string variables: ¨ Variable-length: Stings in which the number of characters in the string is not specified in advance. ¨ Fixed-length: Strings in which the number of characters in the string is specified in advance

Declaring Variables n n Declare ALL variables with the DIM statement General form: ¨ n Dim Variable 1 as type 1, variable 2 as type 2, etc. For example, Dim str. My. Name as String, sng. My. Value as Single ¨ Dim cur. Taxes as Currency, cur. Price as Currency ¨ Dim cur. Amount. Due as Currency ¨ n n n Two or more variables can be declared with same Dim statement but you must include the variable type If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time Use variables rather than objects in processing since all textboxes are strings

Structures n A structure contains a collection of variables (properties) to represent an entity. For example: ¨ Struct Date {int Day, char Month, int year} This example is from language C

Functions A set of instructions that are executed as one whole. n In the language of VBA a function that does not return a values is called Subroutine. A function that returns a value is called Function. n

Objects n n Apart from properties, like in structures, also contain methods represented by functions. An object represents a physical entity. Class is the description of an object in programming language. Example: An object of class Car has the following properties: Wheel, engine, hulk, seats. It also has the following methods: it can drive, it can be parked, it can undergo reparation.

Object-Oriented Event-driven Programming (OOED) OOED uses objects, or self contained modules that combine data and program code that pass strictly defined messages to one another. OOED is easier to work with, because it is more intuitive than traditional programming methods. Visual Basic is an OOED language Users can combine the objects with relative ease to create new systems or extend existing ones. Properties of objects are attributes associated with an object Methods of objects are those activities that the object can carry out Objects respond to events – mouse click, key press

OOED Programming Process A six step process for writing an OOED computer program: 1. Define problem. 2. Create interface 3. Develop logic for action objects 4. Write and test code for action objects 5. Test overall project 6. Document project in writing No matter how well a program is written, the objective is not achieved if the program solves the wrong problem.

Step One: Define Problem n n Before you can create a computer application to solve a problem, you must first clearly define it Must identify the data to be input to the program and the results to be output from it. Sketching an interface is a good way to understand the problem and to communicate your understanding to other people Denote input and output objects as well as action objects--those for which code (instructions) are needed

Sketch of Vintage Video Interface

Step Two: Create Interface n n n Once you have defined problem and sketched interface, you are ready to create interface Doing this with VB is quite easy--select objects and place them on VB form following sketch For Vintage Video, only need three objects: ¨ buttons for action ¨ textboxes for input and output ¨ labels for descriptors

Vintage Video Interface

Step Three: Develop Logic for Action Objects n Need to think about what each action object should do in response to an event n This is the logic for each object n Use Input/Processing/Output (IPO) Tables and Pseudocode to develop the logic n IPO Tables show the inputs, outputs, and the processing to convert inputs into outputs

IPO Table for Calculate Button Input Video price Processing Taxes = 0. 7 x price Amount due = price + taxes Output Taxes Amount due

Using Pseudocode n n An important part of the developing the logic for action objects is generating corresponding pseudocode. Pseudocode involves actually writing a program in English rather than in a computer language. When the actual computer program is written, the pseudocode is translated into computer language. A pseudocode program is useful for two reasons: ¨ The programmer may use it to structure the algorithm's logic in writing. ¨ It provides a relatively direct link between the algorithm and the computer program

Pseudocode for Calculate Button Begin procedure Input Video Price Taxes = 0. 07 x Video Price Amount Due = Video Price + Taxes Output Taxes and Amount Due End procedure

Step Four: Write and Test Code of Action Objects n n Once you learn the vocabulary and syntax of a language, you should be able to convert the logic embodied in the pseudocode into a computer language. In our case, we use VB You need to test each code for each action object as they are created Once the object code is written, the programmer must test and correct it. This stage is referred to as debugging, since it involves removing "bugs". Use test data for which you know the correct answer to test the object code

VB Code for Calculate Button Private Sub cmd. Calc_Click() ‘ This object calculates the Taxes and Amount Due ‘ given the Video Price Dim Price as Currency, Taxes as Currency Dim Amount. Due as Currency Price = val(txt. Video. Price) Taxes = 0. 07*Price Amount. Due = Price + Taxes txt. Taxes = str(Taxes) txt. Amount. Due = str(Amount. Due) End sub

Step Five: Test Overall Project n Even with extensive testing, some bugs can often be found in most commercial software. n With computer software, each program instruction must be absolutely correct. Otherwise, the whole program might fail. n BE SURE to test your program in the actual environment and on the actual data on which it will be used

It this course: n n We are going to use variables a lot in VBA. Variables will be used a lot with the Subroutines and Functions We shall use the objects associated with the elements of an Excel workbook, and a Word document. We shall not create any custom objects. In order to do this, we should be qualified programmers.

Programming constructs Linear construct n Branching construct n Looping (cyclic) construct n

Processing blocks Begin/End Stand alone statement YES NO Decision Block Cycle block

Linear construct

Branching construct YES NO

Looping construct