NOTES: Variables & Constants (module 10)

Similar documents
VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Programming Language 2 (PL2)

Full file at

NOTES: Procedures (module 15)

Introduction to Data Entry and Data Types

BASIC ELEMENTS OF A COMPUTER PROGRAM

Variables and Constants

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

printf( Please enter another number: ); scanf( %d, &num2);

Visual C# Instructor s Manual Table of Contents

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

VISUAL BASIC 6.0 OVERVIEW

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Chapter 2 Basic Elements of C++

Microsoft Visual Basic 2015: Reloaded

The C++ Language. Arizona State University 1

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Computational Expression

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

Objectives. In this chapter, you will:

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Notes on Chapter 1 Variables and String

Computer Science 110. NOTES: module 8

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Variables and Literals

Language Fundamentals

1.1 Introduction to C Language. Department of CSE

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

C++ Programming: From Problem Analysis to Program Design, Third Edition

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Introduction to Programming in Turing. Input, Output, and Variables

Lecture 2 Tao Wang 1

Visual C# Program: Resistor Sizing Calculator

Microsoft Visual Basic 2005: Reloaded

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

Program Planning, Data Comparisons, Strings

variables programming statements

Chapter 2 Working with Data Types and Operators

Introduction to the C++ Programming Language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CS242 COMPUTER PROGRAMMING

Chapter 2.5 Writing maintainable programs

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

REVIEW. The C++ Programming Language. CS 151 Review #2

IT 374 C# and Applications/ IT695 C# Data Structures

Variables and Constants

CHAPTER 7 OBJECTS AND CLASSES

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Approximately a Final Exam CPSC 206

Programming Logic and Design Seventh Edition Chapter 2 Elements of High-Quality Programs

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CST112 Variables Page 1

Lab # 02. Basic Elements of C++ _ Part1

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Perl Basics. Structure, Style, and Documentation

Introduction to Java Unit 1. Using BlueJ to Write Programs

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Ex: If you use a program to record sales, you will want to remember data:

Visual C# Program: Temperature Conversion Program

Basic Computation. Chapter 2

Chapter-8 DATA TYPES. Introduction. Variable:

Microsoft Word Training. IT ESSENTIALS Managing Large Documents Using Word 2013 (IS165) October 2015

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Basics of Java Programming

The Java Language Rules And Tools 3

Java Notes. 10th ICSE. Saravanan Ganesh

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Data Types and Variables in C language

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Programmers should write code that is self-documenting and split into small sections.

(Refer Slide Time: 00:23)

Programming Lecture 3

Software and Programming 1

Variables, expressions and statements

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

CHAPTER 7 OBJECTS AND CLASSES

Chapter 2 THE STRUCTURE OF C LANGUAGE

Variable A variable is a value that can change during the execution of a program.

First Visual Basic Lab Paycheck-V1.0

Chapter 2: Using Data

Fundamentals of Programming CS-110. Lecture 2

VARIABLES AND CONSTANTS

Exercise: Inventing Language

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Start Visual Basic. Session 1. The User Interface Form (I/II) The Visual Basic Programming Environment. The Tool Box (I/II)

Decision Structures. Start. Do I have a test in morning? Study for test. Watch TV tonight. Stop

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

13 FORMATTING WORKSHEETS

Microsoft Office 2011 for Mac: Introductory Q&As Excel Chapter 3

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

Initial Coding Guidelines

Transcription:

Computer Science 110 NAME: NOTES: Variables & Constants (module 10) Introduction to Variables A variable is like a container. Like any other container, its purpose is to temporarily hold or store something. In programming, variables are containers that temporarily hold data. Variable containers hold values in the computer's memory. They act as a placeholder in memory to store a value. The value that is stored in the variable container can change as the program runs. Your code can use one or many variables. Variables can contain words, numbers, dates, properties or object references. Variables are given short, easy-to-remember names that usually describe the piece of data that will be stored. Variables can hold: User information/data entered at run time The result of a calculation performed by the program A piece of data you wish to display on your form The applications that we have created and worked with until now are much more limited than a typical Visual Basic application because they do not allow the user to input any data. Think of the HelloWorld application that we created in the last modue. This application would be much more useful if the user could enter their own English text and then translate that text into French or Spanish at the click of a button! Declaring and Naming Variables We use text boxes and option buttons to get user input. Variables and constants are then used in the code to hold the values that are given to us through these objects. The variable becomes our way of "tracking" data. As we have seen in the last lesson, a variable is a named memory location that stores a value. A good programmer always uses variables. By using variables, the programmer allows values to be represented by meaningful names that make the program code easier to read and follow. Before you can use a variable in your Visual Basic program, you should declare the variable. This is the programmer's way of stating his/her intention to use the variable in the program. Declaring a variable tells Visual Basic about the variable. It tells Visual Basic: What the variable's name is What type of value the variable will contain How much computer memory must be set aside to hold the value that will be placed in the variable In Visual Basic, you may use: Explicit declarations Implicit declarations Explicit declarations One of the ways to create a variable is to declare it explicitly. Normally, you declare a variable explicitly before you use the variable. To make an explicit declaration, use a Dim statement and the variable name. The correct syntax for an explicit declaration is shown on the computer screen to the right. By explicitly declaring a variable, you "reserve room" for the variable in the computer's memory. The declaration statement tells Visual Basic what type of data it can expect to see and how much memory must be set aside to hold the data. You will learn more about Visual Basic data types in upcoming lessons. The following examples show variable declaration statements that apply the correct syntax: Dim inttestscore As Integer Dim strfirstname As String Dim blnbuttonclicked As Boolean

When a numeric variable is declared in Visual Basic, it is automatically given the value of zero (0) by default. Once you have declared a variable, you can assign information to it in your program code. To assign a value to a variable means to initialize the variable. To assign data to the variable, you use the equal sign (=) sign. The equal sign is called the assignment operator. Explicit declarations One of the ways to create a variable is to declare it explicitly. Normally, you declare a variable explicitly before you use the variable. To make an explicit declaration, use a Dim statement and the variable name. The correct syntax for an explicit declaration is shown on the computer screen to the right. By explicitly declaring a variable, you "reserve room" for the variable in the computer's memory. The declaration statement tells Visual Basic what type of data it can expect to see and how much memory must be set aside to hold the data. You will learn more about Visual Basic data types in upcoming lessons. The following examples show variable declaration statements that apply the correct syntax: Dim inttestscore As Integer Dim strfirstname As String Dim blnbuttonclicked As Boolean When a numeric variable is declared in Visual Basic, it is automatically given the value of zero (0) by default. Once you have declared a variable, you can assign information to it in your program code. To assign a value to a variable means to initialize the variable. To assign data to the variable, you use the equal sign (=) sign. The equal sign is called the assignment operator. In this course, we will declare all variables using explicit declarations. Naming Variables As a programmer, you must choose names, or identifiers, for your program variables. Variable names: Should be clearly understandable to the reader Should be descriptive of the contents of the variable Should include a three-letter prefix that describes the type of data the variable will hold Regardless of the type of variable, the following rules apply when choosing the variable identifier: Variable names must begin with a letter. Variable names can contain letters, numbers and the underscore (_) character. Variable names can be as long as 255 characters or as short as only one character. Variable names can not be Visual Basic keywords. Keywords are words that have a predefined meaning to the Visual Basic compiler. For example, Double is a Visual Basic keyword. Variable names can not contain spaces, periods and other special characters such as \, *,?, etc. Visual Basic identifiers are not case-sensitive. For example, Count and count represent the same memory location. Visual Basic will always try to maintain consistency, however. It will automatically change the case of an identifier so that it matches the case when it was first used. Therefore, if the variable Count is originally declared with an uppercase C, Visual Basic will automatically change the C to uppercase if the programmer enters it with a lowercase c, as in count. The following are examples of legal variable identifiers: intstrikeouts strthisisacrazyvariablenamebutitislegal dblaveragescore dbltotalsalary dbltaxrate_2003 intsum intx Note: It is good programming style to precede the identifier with a three-letter prefix indicating the data type. The following table shows the data types and their prefixes:

Data Type Prefix Single Double Integer Long Currency String sgl dbl int lng cur str Boolean Variable declaration statements reserve space in the computer's memory for a value. Variable Assignment A variable that is declared with a Dimstatement, as in Dim dblaverage As Double is given the value zero (0) by default until it is assigned another value. A variable is initialized, or assigned, a value through an assignment statement. For example: dblaverage = 90.5 Variable assignment statements must be written with the identifier, or variable name, on the left side of the equal sign and the value on the right side of the equal sign, as shown in the above example. In the assignment statement: dblaverage = 90.5 the variable called dblaverage is assigned the value 90.5. What this really means is that the value 90.5 is stored in the memory location referred to by the name dblaverage. In other words, a place in the computer's memory was set aside to hold a value with the data type Double. That place in memory that is set aside is referenced by the identifier, dblaverage. The value 90.5 is temporarily placed in that location in memory. An expression may also be used on the right side of the equal sign to assign a value to the variable. For example, in the statement: intsum = 2 + 2-1 The expression on the right, 2 + 2-1, is evaluated to the value of 3 and then the value 3 is assigned to the variable named intsum. Another example of an assignment statement is: dblrate = intsum * 0.15 In this statement, the expression on the right also contains a variable called intsum. A variable can be used wherever a value can be used. When working with variables, it is important to remember two things: 1. A variable can store only one value at any given time. Example #1: Dim dblsum As Double dblsum = 53.1 dblsum = 74.6 The value stored in dblsum is 74.6 because 74.6 is the last value assigned to dblsum and dblsum can only hold one value. 2. The expression on the right of an assignment statement is evaluated first and then its value is given to the variable on the left. Example #2: Dim dblsum As Double dblsum = 2 dblsum = dblsum + 3 bln

In the first assignment statement, dblsum is given the value 2. In the second assignment statement, the expression dblsum + 3 is evaluated as 2 + 3, which is 5. The value 5 is then assigned to dblsum, overwriting what was previously stored there (2) in the statement preceding it. Practicing With Variables Follow the instructions below to create a Money Wise! application that will use variables to calculate the total price of an item after the sales tax has been added. 1. Start the Visual Basic IDE. 2. Create a new project. 3. Add objects to the form as shown to the right. Refer to this image when placing and sizing the form and its objects. 4. Use the table to name and set the properties for the objects. Object Name Property Caption Property Form1 frmmoneywise Money Wise! Label1 lblquestion What is my cost when the sales tax is added to an item that is priced at 10 dollars? Label2 lblanswer empty Command1 cmdcalculate Calculate Cost Command2 cmddone Done Once you have named your properties, you should then: 5. Save the project. Choose File Save Project As. In the Save in box, navigate to your Practice folder. In the File name box, type frmmoneywise. Click OK. The Save Project As dialogue box appears. Practice will be showing in the Save in box. In the File name box, type Money Wise. Click OK. 6. Now we will write the program code. Double-click the Calculate object to open the Code window. To create a cmdcalculate_click event procedure, type the following using good programming style: Dim dblitemprice As Double 'declares variable Dim dbltotalprice As Double 'declares variable dblitemprice = 10 dbltotalprice = dblitemprice * 0.15 + dblitemprice lblanswer.caption = dbltotalprice 'Displays the price of the item after tax The code for your event procedure should look exactly like the following:

7. Finally, we will write the code for the cmddone_click event procedure. Type the code for the event as follows using proper indenting style: Unload Me 8. Resave your project. 9. Run the application. Click the Calculate Cost button to test the application. The price 11.50 should be displayed. 10. Click the Done button to end the program. Using Constants A constant is a named memory location that stores a value that cannot be changed at run time. Its initial assignment is never changed. To use a named constant, it must first be declared in a Conststatement, as shown: The following is an example of a statement that declares a constant: Const dblpi As Double = 3.14 This statement declares a constant named dblpi that is of the Double data type and holds a value of 3.14. In the next exercise, we will modify our Money Wise application and use a constant. 1. Open your Money Wise project. 2. Double click the Calculate Cost button to open the Code window. 3. Change the cmdcalculate_click procedure to match the code, as shown: Notice that two changes were made to the event procedure: A constant was declared in the first statement as follows: Const dbltax As Double = 0.15 The name of the constant (dbltax)replaced 0.15 in the statement dbltotalprice = dblitemprice * 0.15 + dblitemprice So that the modified statement now reads as follows: dbltotalprice = dblitemprice * dbltax + dblitemprice 4. Resave your project.

5. Run your application. Did You Know? Good programming style dictates that constants be declared before variable declarations, at the beginning of a procedure. Visual Basic Built-In Data Types Visual Basic 6.0 supports many built-in data types. It is important to choose the correct data type to represent each variable. Remember, a variable acts like a placeholder in the computer's memory. The type of data that a variable will hold determines the amount of memory that will be set aside for the variable. If a variable is declared as an Integer, two bytes of memory must be reserved for it. If a variable is declared as Long, four bytes of memory are reserved for it. A Long data type, therefore, takes up more memory than an Integer data type. To make the best use of your computer's resources and to allow your applications to run efficiently, it is important to choose the most appropriate data type for each variable. It is a waste of resources to declare a variable as a Double, for example, if the value it will contain will always be small enough to be accommodated by an Integer type and will never contain decimals. Visual Basic has five built-in data types. Integer and Long These data types represent both positive and negative integers (whole numbers.) The difference between Integer and Long is in the range of values that can be represented. Integer value ranges are lower Long should be reserved for values higher than 32 767 or lower than -32 768 If a value with a decimal portion is assigned to an Integer or Long data type, the value is rounded to a whole number, so precision is lost Single and Double These data types are used to represent positive and negative real numbers, often referred to as floating point numbers, meaning that they contain numbers after the decimal point. As with Integer and Long, the difference between Single and Double is in the range of numbers they each can represent: Single can represent numbers up to 3.4e 38 Double can represent numbers up to 1.8e 308 Currency This data type represents real numbers that are money values. Currency data types can hold numbers up to four decimal places to the right of the decimal because some currencies around the world need this much accuracy String The String data type represents a set of characters. String guidelines: A string can include the letters of the alphabet, digits and any other character such as %, $ and spaces When you assign a value to a String data type, the value must be enclosed in quotation marks (" ") as shown in these examples: Dim strmyname As String strmyname = "Ashley" Dim strmessage As String strmessage = "Sorry, try again." Boolean The Boolean data type is special in that it can only be set to one of two values either True or False. The Boolean data type is useful for representing on/off and yes/no values For example, blnopen would be set to true if open and false if closed Reminder In the lesson titled Declaring and Naming Variables, refer to the section called Naming Variables for a table of three-letter prefixes used to represent the Visual Basic built-in data types.

Identify the Correct Variable Declarations Throughout this lesson, you have learned the importance of good programming style. Writing a clear and concise variable declaration is key to being a good programmer. In the two examples shown below, our programmer wrote variable declarations to represent a student: First name Middle name Last name Age GPA (Grade Point Average) Look at both of the examples carefully, and then click on the one that is written correctly and includes good programming style. Check with your teacher to see if you chose correctly. More on Variable Declarations Up until now, we have used the Dim statement to declare one variable per statement. A single Dim statement can also be used to declare multiple variables. For example, the following statement declares several variables of different types with one Dim statement: Dim strcomputersciencestudent As String, intstudentid As Integer, dblavgmark As Double A comma (,) must be used to separate each declaration. Visual Basic initializes (assigns) variables to a default value when the variables are declared: Numeric variables such as Integer, Long, Single, Double and Currency are initialized to zero (0) by default. String variables are initialized to an empty string, or (""), by default. Boolean variables are initialized to False, which is equivalent to zero (0), by default. Test Your Understanding Choose variable names for the following and then write one Dim statement to declare all three variables: Name Age GPA (Grade Point Average) Once you have completed your variable names, check with the teacher. Obtaining a Value From the User An application is more useful when the user is able to input values at run time. These values are then used in the program code as the program executes. For example, in our Money Wise application, the application would be more useful to us if the user could enter the price of an item. The program could then calculate the total price including tax. One way to obtain user input in Visual Basic is to use a text box. A text box object is created, as you learned in the lesson Practicing With Text Boxes, by using the TextBox control in the Toolbox. Text box objects do not have a Caption property. For this reason, a label is usually placed near the text box to describe how it will be used. In the following exercise, we will add a text box to the Money Wise application and then add the code for a change event: 1. Open the Money Wise application and display the MoneyWise form, if it is not already displayed. 2. Change the lblquestion Caption property to display Enter the price of the item:. 3. Add a text box object beside the label and modify the interface so that it is similar to the screen capture that is shown below. 4. Set the Name property of the text box to txtprice. 5. Delete the current text box Text property value so that the Values column is blank for that property.

6. Now we will change the program code. Double-click the text box to display the Code window. From the Object list, select General 7. The cursor is now in the General section. Type Option Explicit, if it is not already there, and then press Enter. 8. Modify the cmdcalculate_click event procedure. 9. From the Object list, select txtprice. A txtprice_change ( ) event is added to the code. 10. Add the following lines of code to the txtprice_changeevent procedure: 'Clears price when the user clears text box to type a new price lblanswer.caption = "" 11. Resave the project and run the application.

Did You Know? To prevent errors, program code should include the Option Explicit statement in the General section of the Code window so that variables must be declared before they are used. The Option Explicit statement tells Visual Basic to check for an undeclared variable at run time. Option Buttons and Frames In the last lesson, we looked at the use of text boxes as a common way to obtain user input. Option buttons, sometimes called radio buttons, are another way to obtain input from the user. In this lesson, we will learn about option buttons. Option buttons are grouped together. They are designed to provide the user with a set of input choices. Only one option button in the group can be selected at a time. An option button object is created using the OptionButton control in the Toolbox. Properties are then set for this object just as we have done for other objects that we created. Option buttons are usually coded with a click event. The click event procedure is executed when the user clicks on an option button. A frame is a container object. The frame container is used to group option buttons. An example of a frame containing option buttons is shown above. In this example, the option buttons for choosing a grade were placed in a frame with the caption Grade. Frames are created using the Frame control in the Toolbox. A frame must be created first and then the option buttons are added to it. When adding option buttons to a frame, they are drawn with the OptionButton control and then dragged to the desired position within the frame. When option buttons are drawn in the frame in this way, both the frame and the option buttons will move together when the frame is dragged to a new location on the form. Hello World! Redesign In this next exercise, we are going to redesign the Hello, World! application. 1. Open the Visual Basic development environment. 2. Create a new project. 3. Design a new form that looks like the following:

4. Set the properties for the objects as shown in the chart: Object Name Caption Font Alignment Form1 frmhellointernational Hello From Around the World! Label1 lblmessage empty Bold, 18pt Center Frame1 fralanguage Select a language Command1 cmddone Done 10pt Option1 optenglish English 10pt Option2 optspanish Spanish 10pt Option3 optfrench French 10pt 5. Save the project in your Practice folder as follows: 1. Save the form as frmhellointernational 2. Save the project as Hello International 6. Now we will add the click event procedures for the three option buttons. 7. Double-click the English option button to display the Code window. 8. Add the following code statement to the optenglish_click procedure: lblmessage.caption = "Hello, world!" 9. Double-click the Spanish button and add the following code statement to the optspanish_click procedure: lblmessage.caption = "Hola mundo!" 10. Double-click the French button and add the following code statement to the optfrench_click procedure: lblmessage.caption = "Bonjour monde!" 11. To make English the default language when the application starts, code must be added to the Form_Load event procedure. Open the Code window. Choose Form from the object drop-down list as shown: Make sure the Load event is selected from the Event drop-down list on the right, as shown in the image above. 12. Add the following code statements to the Form_Load event procedure. optenglish.value = True lblmessage.caption = "Hello, world!" 13. Finally, double-click the Done button and we will add a cmddone_click event procedure with the following code: Unload Me 14. Your Code window, with the complete code, should look like:

15. Resave your project. 16. Run the application. Click each option button to see the program in operation. Click the Done button to end the program. 17. Close Visual Basic. Option Explicit The syntax rules of most major programming languages force the programmer to declare a variable before it can be used. In Visual Basic, declaring variables with the Dim statement is optional. However, it is strongly recommended that you declare all variables before using them. Using the Option Explicit statement forces you to declare all variables. To use Option Explicit, follow these steps: 1. From the Code window, click on the object box drop-down arrow and select General, as shown above. 2. A clear area in the Code window will appear. Type the following into this area and press Enter. Option Explicit Once Option Explicit has been added to your program, you must declare all variables before using them or Visual Basic will report an error at run-time with the message "Variable not defined." One advantage of using Option Explicit is that if you mistype a variable name, Visual Basic will detect it immediately. This can be very useful as this type of error is usually hard to find.