Visual Basic: An Object Oriented Approach 5: Structured Programming.

Slides:



Advertisements
Similar presentations
Chapter 4 - Control Statements
Advertisements

CSM18 Visual Basic Section 2 Department of Computing UniS 1 CSM18 Further Constructs in VB A statement is the fundamental syntactical element of a program.
Control Structures Ranga Rodrigo. Control Structures in Brief C++ or JavaEiffel if-elseif-elseif-else-end caseinspect for, while, do-whilefrom-until-loop-end.
Intermediate Code Generation
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
 Control structures  Algorithm & flowchart  If statements  While statements.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
Iteration (Looping Constructs in VB) Iteration: Groups of statements which are repeatedly executed until a certain test is satisfied Carrying out Iteration.
Basic Elements of Programming A VB program is built from statements, statements from expressions, expressions from operators and operands, and operands.
The Programming Discipline Professor Stephen K. Kwan 2010 Things you need to know (learn) for developing large computer programs.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Chapter 1 Program Design
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Fundamentals of Python: From First Programs Through Data Structures
A Level Computing#BristolMet Session Objectives U2#S6 MUST identify different data types used in programming aka variable types SHOULD describe each data.
1 Chapter 9 Writing, Testing, and Debugging Access Applications.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Chapter 4: The Selection Process in Visual Basic.
Lecture Set 5 Control Structures Part A - Decisions Structures.
1 Relational Expressions Relational expressions: –Expressions that compare operands –Sometimes called conditions –Evaluated to yield a result –Typically.
VB Core II Conditional statements Exception handling Loops Arrays Debugging.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
Controlling Execution Programming Right from the Start with Visual Basic.NET 1/e 8.
VBScript Language. What is VBScript Based on the Visual Basic family of languages Supports object oriented features Interpreted Loosely Typed Implicitly.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 8 Debugging, Creating Executable Files, and Distributing a Windows Application.
Conditional Expression One of the most useful tools for processing information in an event procedure is a conditional expression. A conditional expression.
1 Flow Control Ifs, loops. 2 Data Type At the lowest level, all data in a computer is written in 1’s and 0’s (binary) How the data gets interpreted, what.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
31/01/ Selection If selection construct.
Higher Computing Software Development -So Far- 5/10/10.
Controlling Program Flow with Looping Structures
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Controlling Program Flow with Decision Structures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
AVCE ICT – Unit 7 - Programming Session 12 - Debugging.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
UNIT 5 Lesson 15 Looping.
VBA - Excel VBA is Visual Basic for Applications
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Visual Basic 6 (VB6) Data Types, And Operators
Control Structures: Part 2
Chapter 5 Decisions. Chapter 5 Decisions ssential uestion: How are Boolean expressions or operators used in everyday life?
CHAPTER FIVE Decision Structures.
Chapter (3) - Looping Questions.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Debugging and Handling Exceptions
Presentation transcript:

Visual Basic: An Object Oriented Approach 5: Structured Programming

Structures within Software Structure is apparent at a number of levels A project can involve a number of modules, each occupying a separate file Each module will contain a number of procedures (Subs and Functions) and variable declarations Within a Sub or Function, certain standard code constructs are used to define whether actions happen or not, or how often they are executed Data variables in a module can be grouped in several ways to form data structures The last two categories are central to the idea of ‘Structured Programming’

Structured Programming Born out of chaotic nature of software designs before late 1960s Idea is to limit the power of the programmer to direct a program with no restrictions Code statements are organised in a small number of standard forms Structure of data should mirror real-life information structure wherever possible

Program Control Constructs Three main structuring principles Code statements should be grouped into functional units Subs, Functions Possible to select whether one or more statements will execute or not, based on a simple logical criterion If..Then, If..Then..Else, Select Case Possible to repeat a statement or group of statements either a given number of times or until a specific condition is true For..Next, Do..Loop

Conditions Central to the principles of programming The flow of execution depends on prevailing conditions within a program A condition is an expression that evaluates to True or False. Can be… A single Boolean variable A combination of Boolean variables The result of a comparison for equality or relative size A combination of such comparisons

Conditions X=0‘ True if X is zero, False otherwise Y=X‘ as above X < Y‘ True is X is not equal to Y or ‘ bigger than it X = 0 And Y >2‘ True is both are true X = 0 Or Y > 2‘ True is either is true

Conditions to control flow… Using a condition, can direct the flow of a program… If Time > “12:00” Then MsgBox “Good afternoon” End If

Can use If..Then flexibly… If Time < “12:00” Then MsgBox “Good morning” ElseIf Time > “12:00” And Time < “18:00” Then MsgBox “Good afternoon” Else MsgBox “Good evening” End If

Iteration Iteration is repetition of code Can execute one or more statements A given number of times Until a condition becomes True While a condition remains True This allows the same code to be reused For a number of similar variables For the same variable(s) containing a succession of values e.gPrint a number of pages e.g.Get input from a user until a valid entry e.g. Calculate a succession of loan payments

Iteration For index = 1 To 12‘ Print a table of squares Print index, index * index Next Do‘ Repeat until user enters name Name = InputBox(“Enter your name”) Loop Until Name <> “”

Structured Data Individual variables are awkward in many circumstances Usually need to work with sets of data Classes of students Lists of library books Normally, information is complex and has structure Items are related by.. Similarity (e.g. class of students) Hierarchy (e.g. a book has several chapters) Grouping (e.g. a person has a name, address, phone number, national insurance number, several credit cards, etc..) We use data structures to group information together

Arrays Simplest form of data structure A number of variables of the same type, related in some way A list of names A Table of profit figures All elements share the same name Each element has an index indicating its position in the array

Arrays Students John Smith Jane Green Mary Brown Mike Stone Ashok Din Profits Quarters 1-Dimensional Array 2-Dimensional Array Element Index Dim Students(1 To 6) Dim Profits(1998 To 2000, 1 To 4)

Programming with Arrays Strong affinity between arrays and For..Next loops… For Student_No = 1 To 6 Print Students(Student_No) Next For Year = 1998 To 2000‘ Note – a nested For loop For Quarter = 1 To 4 TotalProfit = TotalProfit + Profits(Year, Quarter) Next

User Defined Types Arrays group a number of similar items together (e.g. a List of…). Items share a name. Sometimes it is necessary to group related items of different type together (e.g. someone’s Name, Address, Date of Birth, Phone_No etc.) A User Defined Type allows a number of different variables with distinct names to be grouped into Records

A User Defined Type A template for compound variables Each individual member has its own name and type Some similarities to Classes Must define a UDT before declaring variables of the type Access individual members using a dot (.) notation Defines a package of data Type Student Name As String DOB As Date Address As String Level As Integer End Type ‘ A single Student… Dim S As Student ‘ An array of them… Dim Class(1 To 20) As Student ‘ A useful index variable… Dim StudentCount As Integer Type Student Name As String DOB As Date Address As String Level As Integer End Type ‘ A single Student… Dim S As Student ‘ An array of them… Dim Class(1 To 20) As Student ‘ A useful index variable… Dim StudentCount As Integer

Programming UDTs Sub CreateStudentRecord() ‘ Assign values to student record fields… S.Name = InputBox(“Enter student’s name”) S.Address = InputBox(“Enter student’s address”) S.DOB = InputBox(“Enter student’s date of birth”) S.Level = InputBox(“Enter year enrolled for (1..3)”) ‘ Now increment the index to be used with the Class array… StudentCount = StudentCount + 1 ‘ and copy the student record (note – a single assigment)… Class(StudentCount) = S End Sub Sub CreateStudentRecord() ‘ Assign values to student record fields… S.Name = InputBox(“Enter student’s name”) S.Address = InputBox(“Enter student’s address”) S.DOB = InputBox(“Enter student’s date of birth”) S.Level = InputBox(“Enter year enrolled for (1..3)”) ‘ Now increment the index to be used with the Class array… StudentCount = StudentCount + 1 ‘ and copy the student record (note – a single assigment)… Class(StudentCount) = S End Sub

Error Handling Three types of error to deal with Syntax errors – violation of language rules Visual Basic will detect and highlight these Logic errors – the code does not do what you intend it to Only solution is experience – learn how to design and implement algorithms, take care. Run-time errors – things that are normally not anticipated e.g. ask the user to enter a number, but get a letter e.g. try to access a disk that is not in the drive e.g. try to do impossible operation ( x/0) Need to deal with Run-Time errors in programs

Coping with run-time errors Three options… Code around them Always check user inputs for type and sense, check for drive availability etc. Can lead to excess code and programs that are difficult to follow Ignore them Turn off error checking Dangerous – may look as if a result has been reached but likely to be wrong Build error trapping code Break code into ‘Normal’ flow code and ‘Error Handling’ Define how to react if an error occurs

Coding around an error Sub Calculate_Age() Dim DOB As String DOB = InputBox("Enter your date of birth.") If IsDate(DOB) Then MsgBox "You are " & (Date – Cdate(DOB))/365 & " years old." Else MsgBox "Invalid date." End If End Sub Sub Calculate_Age() Dim DOB As String DOB = InputBox("Enter your date of birth.") If IsDate(DOB) Then MsgBox "You are " & (Date – Cdate(DOB))/365 & " years old." Else MsgBox "Invalid date." End If End Sub Call to IsDate( ) function prevents a possible error

Ignoring an error Sub Calculate_Age() Dim DOB As Date On Error Resume Next DOB = InputBox("Enter your date of birth.") MsgBox "You are " & (Date - DOB) / 365 & " years old." End Sub Sub Calculate_Age() Dim DOB As Date On Error Resume Next DOB = InputBox("Enter your date of birth.") MsgBox "You are " & (Date - DOB) / 365 & " years old." End Sub On Error Resume Next causes VB to ignore run-time errors – can lead to mistaken belief that a wrong answer is correct

Adding an Error Handler Sub Calculate_Age() Dim DOB As Date On Error GoTo err_Calculate_Age DOB = InputBox("Enter your date of birth.") MsgBox "You are " & (Date - DOB) / 365 & " years old." err_Calculate_Age: If Err Then If Err = 13 Then ' Type mismatch - we expected this. MsgBox "An invalid date has been entered." Resume Else MsgBox Error.Description ‘ Some errors can never be anticipated. End If End Sub Sub Calculate_Age() Dim DOB As Date On Error GoTo err_Calculate_Age DOB = InputBox("Enter your date of birth.") MsgBox "You are " & (Date - DOB) / 365 & " years old." err_Calculate_Age: If Err Then If Err = 13 Then ' Type mismatch - we expected this. MsgBox "An invalid date has been entered." Resume Else MsgBox Error.Description ‘ Some errors can never be anticipated. End If End Sub Error handling starts here Where to go in the event of an error