BACS 287 Programming Fundamentals 1. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Variables State Scope Lifetime.

Slides:



Advertisements
Similar presentations
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
1.
VBA Modules, Functions, Variables, and Constants
Slide 1 Variables, Constants and Data Types. Slide 2 Variables v Three components define a variable: –Name (memory location) –Type –Information (value)
IS437: Fall 2004 Instructor: Dr. Boris Jukic Data Types, Constants, Variables, Scope, Conversion.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
Chapter 2: Introduction to C++.
JavaScript, Third Edition
Basic Elements of C++ Chapter 2.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
110-D1 Variables, Constants and Calculations(1) Chapter 3: we are familiar with VB IDE (building a form…) to make our applications more powerful, we need.
Variables, Constants, Methods, and Calculations Chapter 3 - Review.
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
1 VBA – podstawowe reguły języka Opracowanie Janusz Górczyński wg Microsoft Help.
Variable, Expressions, Statements and Operators By: Engr. Faisal ur Rehman CE-105 Fall 2007.
Input & Output: Console
CHAPTER THREE Representing Data: Constants and Variables.
National Diploma Unit 4 Introduction to Software Development Data types, variables and constants.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
Access VBA Programming for Beginners - Class 2 - by Patrick Lasu
3 - Variables Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Looping and Counting Lecture 3 Hartmut Kaiser
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
CHAPTER # 2 Part 2 PROGRAMS AND DATA 1 st semster King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Variable, Constants and Calculations Dr Mohammad Nabil Almunawar.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
# 1# 1 What is a variable that you create? What is a constant that you create? What is an intrinsic (built-in) constant? What variables are built in?
Programming with Microsoft Visual Basic th Edition
Variables in VB.NET. Variables  A storage location in memory (RAM)  Holds data/information while the program is running  These storage locations can.
CPS120: Introduction to Computer Science Variables and Constants.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CHAPTER THREE Representing Data: Constants and Variables.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Bill Tucker Austin Community College COSC 1315
Chapter # 2 Part 2 Programs And data
A variable is a name for a value stored in memory.
Chapter Topics The Basics of a C++ Program Data Types
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Visual Basic 6 (VB6) Data Types, And Operators
Basic Elements of C++.
Chapter 3: Using Variables and Constants
2. Understanding VB Variables
Lecture Set 4 Data Types and Variables
Basic Elements of C++ Chapter 2.
IDENTIFIERS CSC 111.
CIS16 Application Development Programming with Visual Basic
C++ Data Types Data Type
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Fundamentals of visual basic
Chapter # 2 Part 2 Programs And data
Chapter 2: Introduction to C++.
Chap 2. Identifiers, Keywords, and Types
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Presentation transcript:

BACS 287 Programming Fundamentals 1

BACS 287 Programming Fundamentals This lecture introduces the following topics: – Variables State Scope Lifetime – Constants – User-Defined Data Structures

BACS 287 Visual Basic Programming Programs are explicit instructions to the computer telling it how to solve a problem. Programs use the structured logic that you create with pseudocode or flowcharts. Programs differ from pseudocode in that you must write your program according to the rules of the language (syntax). Thus, you must convert your pseudocode to VB statements. You can see the full VB reference documentation at:

BACS 287 Visual Basic Programming The general hierarchical structure of a VB program is as follows: – Solution – Project – Forms & Modules – Procedures (functions & subroutines) – Structures (constructs) – Statements – Variables/Constants/Functions/... Highest Lowest

BACS 287 Variables Variables are named memory locations that hold temporary data values during the execution of a program. There are 4 key characteristics of variables: – Name – what it is called – Type – the kind of data it is designed to hold – Size – how much memory does it take to store it – Value – the current value of the variable When you define a variable you determine its name, type, and size. You can determine its value either when you define it or later in the program.

Memory and Variables

CPU/Memory Interaction

BACS 287 Variable Definition Name: Assigns a name to memory location – Begins with a letter or an _ (underscore) – No periods, dashes, spaces, or special characters allowed in name (underscore ‘_’ is ok) – If it begins with underscore, it must have at least one alphabetic character or number – <= 1,023 characters in length – Unique within the variable scope – Cannot be a “reserve word” (like ‘print’, ‘true’,…) The variable can be defined explicitly by the programmer or implicitly by Visual Basic. You should always use the explicit method.

BACS 287 Variable Name Prefixes There are several naming schemes for variables in Visual Basic. A popular one uses a 3 or 4-letter prefix before a “camel case” descriptive name. It’s called “Hungarian notation” The main prefixes are: bol – Booleanlng – Long byt - Byte int – Integersng – Single dec - Decimal sho – Shortdbl – Double dat – Date str – Stringobj – Object uint – unsigned integer This is the “Hungarian notation”

BACS 287 Variable Definition Variables can be define explicitly by using the DIM statement. The DIM statement allows you to define the variable’s name, type, size, and value. For example: Dim intClassSize as Integer Dim sngGPA as Single = 3.21

BACS 287 Variable State The state of the variable is determined by: – Type – Length – Current value The state of the variable can change during the execution of the program.

BACS 287 Variable Definition Type: Determines what kind of data can be stored in the variable. These are common VB data types. – Byte - whole numbers ( ) (1 byte) – Short - whole numbers (-32,768 – 32,767) (2 bytes) – Integer - whole numbers ( 4 bytes) (-2,147,483,648 to 2,147,483,647) – Long – big whole numbers (8 bytes) (apx. -9 septillion to +9 septillion) – Single – floating point numbers (4 bytes) (apx. 1.4 X to 3.4 X ) – Double – big floating point numbers (8 bytes) – Decimal - high precision decimal numbers (16 bytes) – String - text information (1 byte per character) (up to apx. 2 billion chars) – Boolean - logical values (True or False) (2 bytes) – Date - date and time information (8 bytes) – Object - any data type (4 bytes) (pointer to object) – User-Defined Type – defined by programmer (built from base types)

BACS 287 Variable Definition It is best to use the smallest data type that can hold the anticipated data. It is best to use one of the integer data types unless you need decimal values. It is best to explicitly define a variable’s data type. Otherwise it will be the object type by default. You should only use the object type when necessary.

BACS 287 Variable Definition Size: The amount of memory used by the variable. This is fixed by the data type selected (or the data value entered). For example: Dim intValue as integer  uses 4 bytes Dim strName as string = “My Name”  uses 7 bytes Dim datDate as date = #01/05/2002#  uses 8 bytes Dim objForm as object = frmMyForm  uses 4 bytes

BACS 287 Variable Definition Value: The value assigned to the memory location named by the variable. You can assign values to variables at the time they are defined or with an assignment statement later in the program. Dim strName as String = “Jay Lightfoot” -OR- Dim strName as String strName = “Jay Lightfoot” This example assign literal values (i.e., literals) to the variable.

BACS 287 Variable Definition You can also assign other variables and constants to variables. strName = strProfessor intClassSize = MAX_CLASS These examples assume strProfessor and MAX_CLASS were previously defined and assigned a value.

BACS 287 Variable Definition Examples Dim bytAge as byte = 30 Dim sngTorque as single = Dim dblMass as double = E+12 Dim lngNationalDebt as long = Dim strAddress as string = “123 W. 10th St.” Dim datValue as date = #09/14/2003# Dim blnResident as boolean = true

BACS 287 Special Object Values Value of “Nothing” Object variables are initially created with a value of “Nothing” (unless you specify another value). “Nothing” means no value and is converted to 0 for number data types and the empty string for strings. Null Value Object variables may be assigned a value of “null”. Null means that the data is unknown or missing. It is different from 0 or blank. It is also different from “nothing”.

BACS 287 Variable Scope The scope of the variable is the range of program instructions over which the variable is known, and thus capable of being manipulated. A variable is visible within its scope and invisible outside of it. In Visual Basic, the scope of a variable is determined by where it is defined.

BACS 287 Variable Scope Variables can be declared (defined) at different levels in Visual Basic. The place they are declared determines the variable scope. The common levels are: – Public-Level (Global level)Highest – Friend-level – Form / Module-Level – Procedure-level – Block-level Lowest Each level has different scoping characteristics.

BACS 287 Variable Scope – Block Level A “block” is a sub-part of a statement. This statement has 2. If A = true then dim B as byte Sum = Sum + 1 Block Cnt = Cnt + 1 Else MsgBox(“Error”, “Input Error”) Block EndIf

Variable Scope Form1 Form2 Procedure1Procedure2 Procedure 1 Procedure2 PROJECT Public-Level Module-Level Form-Level Block-Level Friend-Level

BACS 287 Variable Scope Block-Level - Only visible inside the code block where it is defined. Dim or Static - Used to define block-level variables Procedure-Level - Only visible inside the procedure where it is defined. Blocks within the procedure can see it also. Dim or Static - Used to define procedure-level variables Form-Level - Visible to all procedures within the form. Invisible outside the form. Dim - Used to define form-level variables.

BACS 287 Variable Scope Module-Level - Visible inside the module and invisible outside the module. Private - Used to define module-level variables. Only in modules. Private intCount as Integer Friend-Level - Visible inside the project and invisible outside the project. Friend - Used to define module-level variables. Only in modules. Friend sngCount as single Public-Level (Global) - Visible to the entire project and in other projects while application is running. Public - Used to define Public-Level variables. Only in modules. Public strName as String

Variable Scope Project Form1Form2 Procedure A Procedure B Procedure C Procedure D Public X as Integer Dim Y as IntegerDim Z as Integer Dim L as Integer Dim M as Integer Dim N as Integer Dim O as Integer

BACS 287 Variable Lifetime The lifetime (or extent) of the variable is the interval of time in which the memory storage area is bound to the variable. Variables defined locally exist only while the procedure or block in which they are declared is executing. Variables defined as Form-level exist as long as the form is loaded in memory. Variables defined as module-level or public exist as long as the application is executing.

BACS 287 Variable Lifetime Block-Level – Only exists as long as the lexical block where it is defined is executing. Normally the ‘End’ terminator of the block indicates the end of the variable lifetime. Procedure-Level - Only exists as long as the procedure where it is defined is executing. Static variables are an exception to this. They exist as long as the program is executing. Their scope is the same. Form-Level – Only exist as long as the form is loaded in memory.

BACS 287 Variable Lifetime Module-Level – Exist as long as the program is executing. Friend-Level - Exist as long as the program is executing. Public-Level (Global) - Exist as long as the program is executing.

BACS 287 Variable Conversion The data type of a variable can be changed while the program is running. This is often done to modify a string to a number so you can do calculations or to take a number and convert it to a string with special formatting characters (like $ and commas). Visual Basic has two main ways to do this: – Build-in conversion functions – only work in VB – Conversion methods – work in any.NET language

BACS 287 Variable Conversion Functions CDec(expression) – convert to decimal CByte(expression) – convert to byte CChar(expression) – convert to character CDbl(expression) – convert to double CSng(expression) – convert to single CInt(expression) – convert to integer CStr(expression) – convert to string CDate(expression) – convert to date/time Example: strResult = Cstr(123) strResult = Cstr(2 + 6)

BACS 287 Variable Conversion Methods Convert.ToDecimal(value) – convert to decimal Convert.ToByte(value) – convert to byte Convert.ToChar(value) – convert to character Convert.ToDouble(value) – convert to double Convert.ToSingle(value) – convert to single Convert.ToInt32(value) – convert to 4 byte integer Convert.ToInt16(value) – convert to 2 byte integer Convert.ToString(value) – convert to string Convert.ToDateTime(value) – convert to date/time Example: strResult = Convert.ToString(123)

BACS 287 Variable Conversion – TryParse A special method called TryParse exists to perform conversions with formatting. This method also returns a value of True or False; thus, it can be used as the condition of an IF-Then statement. Example: blnResult = Decimal.TryParse(textbox.text, sales) Options also exist to add formatting characters to the resulting output.

BACS 287 Constants A constant is similar to a variable except that its value cannot be changed once it is set. This is useful for situations where you have a value that may change over time (but is static while the program runs). It also helps document the program and improves readability.

BACS 287 Constant Definition There are 2 types of constants: – User defined constants (symbolic) Public Const PI as Double = Private Const mdatDUE_DATE as Date = #6/16/99# – System defined constants (intrinsic) If vbYes then Print “yes”... If “red” then color = Color.Red...

BACS 287 Constants Constants can be defined at all the scope levels that variables can be. Constants share the same lifetime rules as variables. Good programming practices dictate that all constants be declared at the module level (or above).

BACS 287 Constants Constants often follow these naming conventions: – First character – scope indicator (m for module) – Next 3 characters – date type indicator (int,dec,…) – Rest of name capitalized Public Const mintMIN_AGE as integer = 18 Const decINTEREST as decimal = The second example is a local constant as would be defined in a procedure.

BACS 287 User-Define Data Structures User-Defined data structures allow you to combine several different types of data into a single structure. They are useful when you need a single variable that records several related pieces of information. Use the STRUCTURE statement to declare them. The definition must be made in a module (i.e., not local scope).

BACS 287 User-Define Data Structures Public Structure StudentInfo Public SSN as String Public Name as String Public EnrollDate as Date Public CurrentStatus as Byte Public GPA as single End Structure... Dim stuLocal as StudentInfo... If stuLocal.Name = “John Smith” then...

BACS 287 User-Define Data Structure Public Structure ProjectPack Public frmInput as form Public frmCalc as form Private dbProject as database End Structure... Dim Project1 as ProjectPack... Project1.frmCalc = frmMyForm

BACS 287 User-Define Data Structures You can nest user-defined data types so that one type can be made up of other user-defined data types. You can also include other complex structures (arrays, objects,...). Structures support most of the features of classes (including methods). Thus, structures can contain procedures that act upon local data.

User-Define Data Structures Public Structure Employee ' Public members, accessible throughout declaration region. Public FirstName As String Public MiddleName As String Public LastName As String ' Friend members, accessible anywhere within the same assembly. Friend EmployeeNumber As Integer Friend BusinessPhone As Long ' Private members, accessible only within the structure itself. Private HomePhone As Long Private Salary As Double Private Bonus As Double ' Procedure member, which can access structure's private members. Friend Sub CalculateBonus(ByVal Rate As Single) Bonus = Salary * CDbl(Rate) End Sub End Structure

Review State – Name, type, value, size Scope – Block, procedure, form/module, public Lifetime – Block, procedure, form/module, public Conversions Constants User-defined data structures BACS 287