SlideShare a Scribd company logo
Microsoft Visual Basic Programs To Accompany
Programming Logic And Design 3rd Edition Jo Ann
Smith download
https://ebookbell.com/product/microsoft-visual-basic-programs-to-
accompany-programming-logic-and-design-3rd-edition-jo-ann-
smith-2516288
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Microsoft Visual Basic 2005 Express Edition Build A Program Now
Patrice Pelland
https://ebookbell.com/product/microsoft-visual-basic-2005-express-
edition-build-a-program-now-patrice-pelland-928390
Microsoft Visual Basic 2008 Express Edition Build A Program Now Papcdr
Pelland
https://ebookbell.com/product/microsoft-visual-basic-2008-express-
edition-build-a-program-now-papcdr-pelland-55141900
Microsoft Visual Basic 2010 For Windows Web And Office Applications
Complete Sam 2010 Compatible Products 1st Edition Shelly
https://ebookbell.com/product/microsoft-visual-basic-2010-for-windows-
web-and-office-applications-complete-sam-2010-compatible-products-1st-
edition-shelly-55132322
Microsoft Visual Basic 2010 Developers Handbook 1st Edition Klaus
Lffelmann
https://ebookbell.com/product/microsoft-visual-basic-2010-developers-
handbook-1st-edition-klaus-lffelmann-55132362
Microsoft Visual Basic 2010 For Windows Applications Introductory
Available Titles Skills Assessment Manager Sam Office 2010 1st Edition
Shelly
https://ebookbell.com/product/microsoft-visual-basic-2010-for-windows-
applications-introductory-available-titles-skills-assessment-manager-
sam-office-2010-1st-edition-shelly-55132370
Microsoft Visual Basic 2008 Express Programming For The Absolute
Beginner 1st Edition Ford
https://ebookbell.com/product/microsoft-visual-basic-2008-express-
programming-for-the-absolute-beginner-1st-edition-ford-55132374
Microsoft Visual Basic Net Programming For The Absolute Beginner First
Edition Harbour
https://ebookbell.com/product/microsoft-visual-basic-net-programming-
for-the-absolute-beginner-first-edition-harbour-55139964
Microsoft Visual Basic 2012 Reloaded 5th Edition Zak Diane
https://ebookbell.com/product/microsoft-visual-
basic-2012-reloaded-5th-edition-zak-diane-55141894
Microsoft Visual Basic 2010 Step By Step Michael Halvorson
https://ebookbell.com/product/microsoft-visual-basic-2010-step-by-
step-michael-halvorson-2310058
Microsoft Visual Basic Programs To Accompany Programming Logic And Design 3rd Edition Jo Ann Smith
Microsoft Visual Basic Programs To Accompany Programming Logic And Design 3rd Edition Jo Ann Smith
MI CROSO F T ® VISUAL
BASIC® PROGRAMS
TO ACCOMPANY
PROGRAMMING LOGIC
AND DESIGN
BY JO ANN SMITH
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
S I X T H E D I T I O N
© 2011 Course Technology, Cengage Learning
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored, or used in any form or by
any means graphic, electronic, or mechanical, including but not limited to
photocopying, recording, scanning, digitizing, taping, Web distribution,
information networks, or information storage and retrieval systems, except
as permitted under Section 107 or 108 of the 1976 United States Copyright
Act, without the prior written permission of the publisher.
Library of Congress Control Number: 2010928662
ISBN-13: 978-0-538-74625-0
ISBN-10: 0-538-74625-4
Course Technology
20 Channel Center Street
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions
with office locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by
Nelson Education, Ltd.
For your lifelong learning solutions, visit course.cengage.com
Visit our corporate Web site at cengage.com.
Some of the product names and company names used in this book have
been used for identification purposes only and may be trademarks or regis-
tered trademarks of their respective manufacturers and sellers.
Any fictional data related to persons or companies or URLs used through-
out this book is intended for instructional purposes only. At the time this
book was printed, any such data was fictional and not belonging to any real
persons or companies.
Course Technology, a part of Cengage Learning, reserves the right to revise this
publication and make changes from time to time in its content without notice.
The programs in this book are for instructional purposes only.
They have been tested with care, but are not guaranteed for any particular
intent beyond educational purposes. The author and the publisher do not
offer any warranties or representations, nor do they accept any liabilities
with respect to the programs.
Microsoft® Visual Basic® Programs to
Accompany Programming Logic and Design,
Sixth Edition
Jo Ann Smith
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Senior Product Manager: Alyssa Pratt
Development Editor: Mary Pat Shaffer
Content Project Manager: Jennifer Feltri
Art Director: Marissa Falco
Proofreader: Suzanne Ciccone
Indexer: Sharon Hilgenberg
Compositor: Integra
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions
Further permissions questions can be e-mailed to
permissionrequest@cengage.com
Printed in the United States of America
1 2 3 4 5 6 7 14 13 12 11 10
Brief Contents
Preface . . . . . . . . . . . . . . . . . xi
CHAPTER 1 An Introduction to Visual Basic and
the Visual Basic Programming Environment
Programming Environment . .
. . 1
1
CHAPTER 2 Variables, Constants, Operators,
and Writing Programs Using Sequential
Statements . . . . . . . . . . . . . . . . 11
CHAPTER 3 Writing Structured Visual Basic Programs. . . 31
CHAPTER 4 Writing Programs that Make Decisions . . . . 46
CHAPTER 5 Writing Programs Using Loops . . . . . . . 74
CHAPTER 6 Using Arrays in Visual Basic Programs . . . . 96
CHAPTER 7 File Handling and Applications . . . . . . 112
CHAPTER 8 Advanced Array Techniques . . . . . . . . 127
CHAPTER 9 Advanced Modularization Techniques . . . . 144
CHAPTER 10 Creating a Graphical User Interface
(GUI) Using the Visual Studio Integrated
Development Environment (IDE) . . . . . . 169
Index . . . . . . . . . . . . . . . . . 193
iii
Contents
Preface . . . . . . . . . . . . . . . . . xi
CHAPTER 1 An Introduction to Visual Basic and
the Visual Basic Programming Environment
Programming Environment . .
. . 1
1
The Visual Basic Programming Language . . . . . . . . . . 2
Three Types of Visual Basic Programs . . . . . . . . . . . . 2
An Introduction to Object-Oriented Terminology . . . . . . . . 3
The Structure of a Visual Basic Program . . . . . . . . . . . 5
The Visual Basic Development Cycle. . . . . . . . . . . . . 6
Writing Visual Basic Source Code . . . . . . . . . . . . . 7
Compiling a Visual Basic Program . . . . . . . . . . . . . 7
Executing a Visual Basic Program . . . . . . . . . . . . . 9
Exercise 1-1: Understanding How to Compile
and Execute Visual Basic Programs . . . . . . . . . . .10
Lab 1.1: Compiling and Executing a Visual
Basic Program . . . . . . . . . . . . . . . . . . . . .10
CHAPTER 2 Variables, Constants, Operators,
and Writing Programs Using Sequential
Statements . . . . . . . . . . . . . . . . 11
Variables . . . . . . . . . . . . . . . . . . . . . . . . .12
Variable Names . . . . . . . . . . . . . . . . . . . . .12
Visual Basic Data Types . . . . . . . . . . . . . . . . . .13
Exercise 2-1: Using Visual Basic Variables,
Data Types, and Keywords . . . . . . . . . . . . . . .14
Declaring and Initializing Variables. . . . . . . . . . . . . .14
Exercise 2-2: Declaring and Initializing Visual
Basic Variables. . . . . . . . . . . . . . . . . . . . .15
Lab 2.1: Declaring and Initializing Visual Basic Variables. . .16
Constants . . . . . . . . . . . . . . . . . . . . . . . . .17
Unnamed Constants . . . . . . . . . . . . . . . . . . .17
Named Constants . . . . . . . . . . . . . . . . . . . .17
iv
Exercise 2-3: Declaring and Initializing Visual
Basic Constants . . . . . . . . . . . . . . . . . . . .18
Lab 2.2: Declaring and Initializing Visual
Basic Constants . . . . . . . . . . . . . . . . . . . .18
Arithmetic and Assignment Operators . . . . . . . . . . . .19
Arithmetic Operators . . . . . . . . . . . . . . . . . . .19
Assignment Operators and the Assignment Statement . . . .20
Precedence and Associativity . . . . . . . . . . . . . . .21
Exercise 2-4: Understanding Operator Precedence
and Associativity . . . . . . . . . . . . . . . . . . . .22
Lab 2.3: Arithmetic and Assignment Operators . . . . . . .23
Sequential Statements, Comments, and Interactive Input
Statements . . . . . . . . . . . . . . . . . . . . . . .24
Exercise 2-5: Understanding Sequential Statements . . . . .28
Lab 2.4: Using Sequential Statements in a Visual
Basic Program . . . . . . . . . . . . . . . . . . . . .29
CHAPTER 3 Writing Structured Visual Basic Programs. . . 31
Using Flowcharts and Pseudocode to Write a Visual
Basic Program . . . . . . . . . . . . . . . . . . . . . .32
Lab 3.1: Using Flowcharts and Pseudocode
to Write a Visual Basic Program . . . . . . . . . . . . .36
Writing a Modular Program in Visual Basic . . . . . . . . . .38
Lab 3.2: Writing a Modular Program in Visual Basic . . . . .45
CHAPTER 4 Writing Programs that Make Decisions . . . . 46
Boolean Operators . . . . . . . . . . . . . . . . . . . . .47
Comparison Operators . . . . . . . . . . . . . . . . . .47
Logical Operators . . . . . . . . . . . . . . . . . . . .48
Comparison and Logical Operator Precedence
and Associativity . . . . . . . . . . . . . . . . . . . .49
Comparing Strings . . . . . . . . . . . . . . . . . . . . .52
Decision Statements . . . . . . . . . . . . . . . . . . . .53
The If Statement . . . . . . . . . . . . . . . . . . . .54
Exercise 4-1: Understanding If Statements . . . . . . . .55
Lab 4.1: Using If Statements . . . . . . . . . . . . . .56
The If Then Else Statement. . . . . . . . . . . . . .57
Exercise 4-2: Understanding If Then Else Statements . .58
Lab 4.2: Using If Then Else Statements . . . . . . . .60
Nested If Statements . . . . . . . . . . . . . . . . . .60
Exercise 4-3: Understanding Nested If Statements . . . .62
Lab 4.3: Using Nested If Statements . . . . . . . . . . .63
v
C O N T E N T S
The Select Case Statement . . . . . . . . . . . . . .64
Exercise 4-4: Using a Select Case Statement. . . . . . . . . . . 67
Lab 4.4: Using a Select Case Statement . . . . . . . .67
Using Decision Statements to Make Multiple
Comparisons . . . . . . . . . . . . . . . . . . . . . .68
Using AND Logic . . . . . . . . . . . . . . . . . . . . .69
Using OR Logic . . . . . . . . . . . . . . . . . . . . .69
Exercise 4-5: Making Multiple Comparisons
in Decision Statements . . . . . . . . . . . . . . . . .70
Lab 4.5: Making Multiple Comparisons
in Decision Statements . . . . . . . . . . . . . . . . .72
CHAPTER 5 Writing Programs Using Loops . . . . . . . 74
Writing a Do While Loop in Visual Basic . . . . . . . . . .75
Exercise 5-1: Using a Do While Loop . . . . . . . . . .76
Using a Counter to Control a Loop . . . . . . . . . . . . .77
Exercise 5-2: Using a Counter-Controlled Do While Loop . .78
Lab 5.1: Using a Counter-Controlled Do While Loop . . . .78
Using a Sentinel Value to Control a Loop . . . . . . . . . . .79
Exercise 5-3: Using a Sentinel Value to Control
a Do While Loop . . . . . . . . . . . . . . . . . . .81
Lab 5.2: Using a Sentinel Value to Control
a Do While Loop . . . . . . . . . . . . . . . . . . .81
Writing a For Loop in Visual Basic . . . . . . . . . . . . .82
Exercise 5-4: Using a For Loop . . . . . . . . . . . . . .84
Lab 5.3: Using a For Loop . . . . . . . . . . . . . . . .84
Writing a Do Until Loop in Visual Basic . . . . . . . . . .85
Exercise 5-5: Using a Do Until Loop . . . . . . . . . .86
Lab 5.4: Using a Do Until Loop. . . . . . . . . . . . .86
Nesting Loops. . . . . . . . . . . . . . . . . . . . . . .87
Exercise 5-6: Nesting Loops . . . . . . . . . . . . . . .88
Lab 5.5: Nesting Loops . . . . . . . . . . . . . . . . .88
Accumulating Totals in a Loop . . . . . . . . . . . . . . .89
Exercise 5-7: Accumulating Totals in a Loop . . . . . . . .91
Lab 5.6: Accumulating Totals in a Loop . . . . . . . . . .92
Using a Loop to Validate Input . . . . . . . . . . . . . . .93
Exercise 5-8: Validating User Input . . . . . . . . . . . .94
Lab 5.7: Validating User Input . . . . . . . . . . . . . . .95
CHAPTER 6 Using Arrays in Visual Basic Programs . . . . 96
Array Basics . . . . . . . . . . . . . . . . . . . . . . .97
Declaring Arrays . . . . . . . . . . . . . . . . . . . . .97
Initializing Arrays . . . . . . . . . . . . . . . . . . . .98
vi
C O N T E N T S
Accessing Array Elements . . . . . . . . . . . . . . . .99
Staying Within the Bounds of an Array . . . . . . . . . . .99
Using Constants with Arrays . . . . . . . . . . . . . . 100
Exercise 6-1: Array Basics . . . . . . . . . . . . . . . 101
Lab 6.1: Using Arrays . . . . . . . . . . . . . . . . . 102
Searching an Array for an Exact Match . . . . . . . . . . 102
Exercise 6-2: Searching an Array for an Exact Match . . . 105
Lab 6.2: Searching an Array for an Exact Match . . . . . 106
Parallel Arrays. . . . . . . . . . . . . . . . . . . . . . 107
Exercise 6-3: Parallel Arrays . . . . . . . . . . . . . . 110
Lab 6.3: Parallel Arrays . . . . . . . . . . . . . . . . 111
CHAPTER 7 File Handling and Applications . . . . . . 112
File Handling . . . . . . . . . . . . . . . . . . . . . . 113
Opening a File for Reading . . . . . . . . . . . . . . . 113
Reading Data from an Input File . . . . . . . . . . . . . 114
Reading Data Using a Loop and EOF . . . . . . . . . . . 114
Opening a File for Writing . . . . . . . . . . . . . . . . 115
Writing Data to an Output File . . . . . . . . . . . . . . 115
Exercise 7-1: Opening Files and Performing File Input . . . 117
Lab 7.1: Using an Input File . . . . . . . . . . . . . . . 118
Understanding Sequential Files and Control Break Logic . . . 119
Exercise 7-2: Accumulating Totals in Single-Level
Control Break Programs . . . . . . . . . . . . . . . 124
Lab 7.2: Accumulating Totals in Single-Level
Control Break Programs . . . . . . . . . . . . . . . 125
CHAPTER 8 Advanced Array Techniques . . . . . . . . 127
Sorting Data . . . . . . . . . . . . . . . . . . . . . . 128
Swapping Data Values . . . . . . . . . . . . . . . . . . 129
Exercise 8-1: Swapping Values . . . . . . . . . . . . . 129
Lab 8.1: Swapping Values . . . . . . . . . . . . . . . 130
Using a Bubble Sort . . . . . . . . . . . . . . . . . . . 130
The Main() Procedure . . . . . . . . . . . . . . . . 134
The fillArray() Procedure . . . . . . . . . . . . . 135
The sortArray() Procedure . . . . . . . . . . . . . 136
The displayArray() Procedure . . . . . . . . . . . 137
Exercise 8-2: Using a Bubble Sort . . . . . . . . . . . . 137
Lab 8.2: Using a Bubble Sort . . . . . . . . . . . . . . 138
Using Multidimensional Arrays . . . . . . . . . . . . . . 139
Exercise 8-3: Using Multidimensional Arrays . . . . . . . 142
Lab 8.3: Using Multidimensional Arrays . . . . . . . . . 142
vii
C O N T E N T S
CHAPTER 9 Advanced Modularization Techniques . . . . 144
Writing Procedures with No Parameters . . . . . . . . . . 145
Exercise 9-1: Writing Procedures with No Parameters . . . 147
Lab 9.1: Writing Procedures with No Parameters . . . . . 148
Writing Procedures that Require a Single Parameter . . . . 148
Exercise 9-2: Writing Procedures that Require
a Single Parameter . . . . . . . . . . . . . . . . . . 151
Lab 9.2: Writing Procedures that Require a Single
Parameter . . . . . . . . . . . . . . . . . . . . . . 152
Writing Procedures that Require Multiple Parameters . . . . 152
Exercise 9-3: Writing Procedures that Require
Multiple Parameters . . . . . . . . . . . . . . . . . 154
Lab 9.3: Writing Procedures that Require
Multiple Parameters . . . . . . . . . . . . . . . . . 155
Writing Functions that Return a Value . . . . . . . . . . . 156
Exercise 9-4: Writing Functions that Return a Value . . . . 158
Lab 9.4: Writing Functions that Return a Value . . . . . . 159
Passing an Array and an Array Element to a Procedure
or Function . . . . . . . . . . . . . . . . . . . . . . 160
Exercise 9-5: Passing Arrays to Procedures
and Functions . . . . . . . . . . . . . . . . . . . . 163
Lab 9.5: Passing Arrays to Procedures and Functions . . . 164
Using Visual Basic’s Built-In Functions . . . . . . . . . . . 165
Exercise 9-6: Using Visual Basic’s Built-In Functions . . . . 167
Lab 9.6: Using Visual Basic’s Built-In Functions . . . . . . 167
CHAPTER 10 Creating a Graphical User Interface (GUI)
Using the Visual Studio Integrated
Development Environment (IDE) . . . . . . 169
Graphical User Interface Programs . . . . . . . . . . . . 170
The Visual Studio Integrated Development Environment . . . 170
Components of a Visual Basic Solution. . . . . . . . . . . 172
The Solution Folder . . . . . . . . . . . . . . . . . . 172
The Designer Window . . . . . . . . . . . . . . . . . 173
The Code Window . . . . . . . . . . . . . . . . . . . 174
Design-Time and Run-Time Operating Modes . . . . . . . . 175
Creating a Visual Basic IDE Program. . . . . . . . . . . . 176
Designing the Form for the Doubler Program . . . . . . . 177
Writing the Code for the Doubler Program . . . . . . . . 180
Exercise 10-1: Elements of a GUI in Microsoft
Visual Studio. . . . . . . . . . . . . . . . . . . . . 181
viii
C O N T E N T S
Lab 10.1: Creating a Visual Basic GUI Program
in Microsoft Visual Studio . . . . . . . . . . . . . . . 182
A Programmer-Defined Class . . . . . . . . . . . . . . . 182
Creating a Programmer-Defined Class . . . . . . . . . . 183
Adding Properties to a Class . . . . . . . . . . . . . . 185
Adding Methods to a Class . . . . . . . . . . . . . . . 186
Exercise 10-2: Creating a Class in Visual Basic . . . . . . 189
Lab 10.2: Creating a Class in Visual Basic . . . . . . . . 190
Index . . . . . . . . . . . . . . . . . 193
ix
C O N T E N T S
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Preface
Microsoft® Visual Basic® Programs to Accompany Programming Logic
and Design, Sixth Edition (also known as, VB PAL) is designed to
provide students with an opportunity to write Visual Basic programs
as part of an Introductory Programming Logic course. It is written to
be a companion text to the student’s primary text, Programming Logic
and Design, Sixth Edition, by Joyce Farrell. This textbook assumes
no programming language experience and provides the beginning
programmer with a guide to writing structured programs and simple
object-oriented programs using introductory elements of the popular
Visual Basic programming language. It is not intended to be a text-
book for a course in Visual Basic programming. The writing is non-
technical and emphasizes good programming practices. The examples
do not assume mathematical background beyond high school math.
Additionally, the examples illustrate one or two major points; they
do not contain so many features that students become lost following
irrelevant and extraneous details.
The examples in VB PAL, Sixth Edition are often examples presented
in the primary textbook, Programming Logic and Design, Sixth
Edition. The following table shows the correlation between topics in
the two books.
VB PAL, Sixth Edition
Programming Logic and
Design, Sixth Edition
Chapter 1: An Introduction to
Visual Basic and the Visual Basic
Programming Environment
Chapter 1: An Overview of
Computers and Logic
Chapter 2: Variables, Constants,
Operators, and Writing Programs
Using Sequential Statements
Chapter 2: Working with Data,
Creating Modules, and Designing
High-Quality Programs
Chapter 3: Understanding Structure
Chapter 3: Writing Structured Visual
Basic Programs
Chapter 2: Working with Data,
Creating Modules, and Designing
High-Quality Programs
Chapter 3: Understanding Structure
(continues)
xi
VB PAL, Sixth Edition
Programming Logic and
Design, Sixth Edition
Chapter 4: Writing Programs that
Make Decisions
Chapter 4: Making Decisions
Chapter 5: Writing Programs Using
Loops
Chapter 5: Looping
Chapter 6: Using Arrays in Visual
Basic Programs
Chapter 6: Arrays
Chapter 7: File Handling and
Applications
Chapter 7: File Handling and
Applications
Chapter 8: Advanced Array
Techniques
Chapter 8: Advanced Array
Concepts, Indexed Files, and Linked
Lists
Chapter 9: Advanced Modularization
Techniques
Chapter 9: Advanced Modularization
Techniques
Chapter 10: Creating a Graphical
User Interface (GUI) Using the Visual
Studio Integrated Development
Environment (IDE)
Chapter 10: Object-Oriented
Programming
Chapter 11: More Object-Oriented
Programming Concepts
Chapter 12: Event Driven GUI
Programming, Multithreading, and
Animation
Organization and Coverage
Microsoft®Visual Basic®Programs to Accompany Programming
Logic and Design, Sixth Edition provides students with a review of
the programming concepts they are introduced to in their primary
textbook. It also shows them how to use Visual Basic to transform
their program logic and design into working programs. The structure
of a Visual Basic program, how to compile and run a Visual Basic
console program, and introductory object-oriented concepts are
introduced in Chapter 1. Chapter 2 discusses Visual Basic’s data
types, variables, constants, arithmetic and assignment operators, and
using sequential statements to write a complete Visual Basic program.
In Chapter 3, students learn how to transform pseudocode and
flowcharts into Visual Basic programs. Chapters 4 and 5 introduce
students to writing Visual Basic programs that make decisions and
programs that use looping constructs. Students learn to use Visual
Basic to develop more sophisticated programs that include using
arrays, control breaks, and file input and output in Chapters 6 and 7.
In Chapter 8, students learn about sorting data items in an array and
(continued)
xii
P R E F A C E
using multidimensional arrays. Passing parameters to procedures is
introduced in Chapter 9. Lastly, in Chapter 10, students learn about
the Visual Studio Integrated Development Environment (IDE), and
gain some experience in creating a Graphical User Interface (GUI)
and writing event-driven programs. Students also learn to write
programs that include programmer-defined classes.
This book combines text explanation of concepts and syntax along
with pseudocode and actual Visual Basic code examples to provide
students with the knowledge they need to implement their logic and
program designs using the Visual Basic programming language. This
book is written in a modular format and provides paper-and-pencil
exercises as well as lab exercises after each major topic is introduced.
The exercises provide students with experience in reading and
writing Visual Basic code as well as modifying and debugging
existing code. In the labs, students are asked to complete partially
pre-written Visual Basic programs. Using partially pre-written
programs allows students to focus on individual concepts rather
than an entire program. The labs also allow students to see their
programs execute.
VB PAL, Sixth Edition is unique because:
It is written and designed to correspond to the topics in the
•
primary textbook, Programming Language and Design, Sixth
Edition.
The examples are everyday examples; no special knowledge of
•
mathematics, accounting, or other disciplines is assumed.
It introduces students to introductory elements of the Visual Basic
•
programming language rather than overwhelming beginning
programmers with more detail than they are prepared to use or
understand.
Text explanations are interspersed with pseudocode from the
•
primary book, thus reinforcing the importance of programming
logic.
Complex programs are built through the use of complete
•
examples. Students see how an application is built from start to
finish instead of studying only segments of programs.
Features of the Text
Every chapter in this book includes the following features. These
features are both conducive to learning in the classroom and enable
students to learn the material at their own pace.
xiii
P R E FA C E
Objectives: Each chapter begins with a list of objectives so the
•
student knows the topics that will be presented in the chapter.
In addition to providing a quick reference to topics covered, this
feature provides a useful study aid.
Figures and illustrations: This book has plenty of visuals, which
•
provide the reader with a more complete learning experience,
rather than one that involves simply studying text.
Notes: These notes provide additional information—for example, a
•
common error to watch out for.
Exercises: Each section of each chapter includes meaningful
• paper-
and-pencil exercises that allow students to practice the skills and
concepts they are learning in the section.
Labs: Each section of each chapter includes meaningful lab work
•
that allows students to write and execute programs that implement
their logic and program design.
Acknowledgments
I would like to thank all of the people who helped to make this book
possible, especially Mary Pat Shaffer, Developmental Editor, whose
expertise and attention to detail have made this a better textbook.
She also provided encouragement, patience, humor, and flexibility
when I needed it. Thanks also to Alyssa Pratt, Senior Product
Manager, and Amy Jollymore, Acquisitions Editor, for their help
and encouragement. I am grateful to Jennifer Feltri, Content Project
Manager, and Vidya Muralidharan, of Integra Software Services,
for overseeing the production of the printed book. It is a pleasure
to work with so many fine people who are dedicated to producing
quality instructional materials.
I am dedicating this book to my son, Tim and his son, my grandson,
William. Both add great dimension and joy to my life.
Jo Ann Smith
xiv
P R E F A C E
Read This Before
You Begin
To the User
Data Files
To complete most of the lab exercises, you will need data files that
have been created for this book. Your instructor will provide the
data files. You also can obtain the files electronically from the Course
Technology Web site by connecting to www.course.com, and then
searching for this book title.
You can use a computer in your school lab or your own computer to
complete the lab exercises in this book.
Solutions
Solutions to the Exercises and Labs are provided to instructors on the
Course Technology Web site at www.course.com. The solutions are
password protected.
Using Your Own Computer
To use your own computer to complete the material in this textbook,
you will need the following:
Computer with a 1.6 GHz or faster processor
•
Operating system:
•
Windows XP (x86) with Service Pack 3 - all editions except
•
Starter Edition
Windows Vista (x86 & x64) with Service Pack 2 - all editions
•
except Starter Edition
Windows 7 (x86 and x64)
•
xv
Windows Server 2003 (x86 & x64) with Service Pack 2 - Users
•
will need to install MSXML6 if not already present
Windows Server 2003 R2 (x86 and x64)
•
Windows Server 2008 (x86 and x64) with Service Pack 2
•
Windows Server 2008 R2 (x64)
•
Architectures: 32-Bit (x86) and 64-Bit (x64) (WOW)
•
RAM:
•
1024 MB
•
1.5 GB if running in a Virtual Machine
•
3 GB of available hard-disk space
•
5400 RPM hard drive
•
DirectX 9-capable video card that runs at 1024 x 768 or higher
•
display resolution
DVD-ROM Drive
•
This book was written using Microsoft Windows Vista and Quality
Assurance tested using Microsoft Windows Vista and Windows 7.
Updating Your PATH Environment Variable
Setting the PATH environment variable allows you to use the Visual
Basic compiler (vbc) and execute your programs without having to
specify the full path for the command.
To set the PATH permanently in Windows 7:
1. Click the Start button in the lower left corner of your
Desktop.
2. Select Control Panel, click System and Security, and then
click System.
3. Select the Advanced system settings link. Click Yes, if
necessary.
4. In the System Properties dialog box, select the Advanced tab, if
necessary, and then click the Environment Variables button.
5. Select PATH or Path in the User variables or System
variables section, click Edit, and then edit the PATH variable
by adding the following to the end of the current PATH:
;C:WindowsMicrosoft.NETFrameworkv4.0.30128
xvi
EAD THIS BEFORE YOU BEGIN
R E A D T H I S B E F O R E
Note that it is important to include the semicolon (;) at the
beginning of the path, preceding C:. You may have to replace
the “v4.0.30128” with the version number you have installed.
You also may have to substitute the drive letter of the
partition you are working on if it is not C:. A typical PATH
might look like this:
C:Windows;C:WindowsSystem32;
C:WindowsMicrosoft.NETFrameworkv4.0.30128
6. When you are finished editing the PATH variable, click OK.
7. Click OK on the Environment Variables dialog box.
8. Click OK on the System Properties dialog box.
9. Close the System window.
To set the PATH permanently in Windows Vista:
1. Click the Start button in the lower left corner of your Desktop.
2. Select Control Panel and then select Classic View, if
necessary.
3. Double-click System.
4. Select the Advanced system settings link. Click Continue,
if necessary.
5. In the System Properties dialog box, select the Advanced tab, if
necessary, and then click the Environment Variables button.
6. Select PATH or Path in the User variables or System
variables section, click Edit, and then edit the PATH variable
by adding the following to the end of the current PATH:
;C:WindowsMicrosoft.NETFrameworkv4.0.30128
Note that it is important to include the semicolon (;) at the
beginning of the path, preceding C:. You may have to replace
the “v4.0.30128” with the version number you have installed.
You also may have to substitute the drive letter of the
partition you are working on if it is not C:. A typical PATH
might look like this:
C:Windows;C:WindowsSystem32;
C:WindowsMicrosoft.NETFrameworkv4.0.30128
7. When you are finished editing the PATH variable, click OK.
8. Click OK on the Environment Variables dialog box.
9. Click OK on the System Properties dialog box.
10. Close the System window.
xvii
READ THIS BEFORE YOU BEGIN
R E A D T H I S B E F O R E
To set the PATH permanently in Windows XP:
1. Click the Start button in the lower left corner of your Desktop.
2. Select Control Panel and then double-click System.
3. In the System Properties dialog box, select the Advanced tab,
and then click the Environment Variables button.
4. Select PATH or Path in the User variables or System
variables section, click Edit, and then edit the PATH variable
by adding the following to the end of the current PATH:
;C:WindowsMicrosoft.NETFrameworkv4.0.30128
Note that it is important to include the semicolon (;) at the
beginning of the path, preceding C:. You may have to replace
the “v4.0.30128” with the version number you have installed.
You also may have to substitute the drive letter of the
partition you are working on if it is not C:. A typical PATH
might look like this:
C:Windows;C:WindowsSystem32;
C:WindowsMicrosoft.NETFrameworkv4.0.30128
5. When you are finished editing the PATH variable, click OK.
6. Click OK on the Environment Variables dialog box.
7. Click OK on the System Properties dialog box.
8. Close the System window.
Capitalization does not matter when you are setting the PATH variable.
The PATH is a series of folders separated by semicolons (;). Windows
searches for programs in the PATH folders in order, from left to right.
To find out the current value of your PATH, at the prompt in a
Command Prompt window, type: path.
To the Instructor
To complete some of the Exercises and Labs in this book, your students
must use the data files provided with this book. These files are available
on the Course Technology Web site at www.course.com. Follow the
instructions in the Help file to copy the data files to your server or
standalone computer. You can view the Help file using a text editor such
as WordPad or Notepad. Once the files are copied, you may instruct
your students to copy the files to their own computers or workstations.
Course Technology Data Files
You are granted a license to copy the data files to any computer or
computer network used by individuals who have purchased this book.
xviii
EAD THIS BEFORE YOU BEGIN
R E A D T H I S B E F O R E
After studying this chapter, you will be able to:
Discuss the Visual Basic programming language and

its history
Recognize the three types of Visual Basic programs

Explain introductory concepts and terminology used

in object-oriented programming
Recognize the structure of a Visual Basic program

Complete the Visual Basic development cycle, which

includes creating a source code file, compiling the source
code, and executing a Visual Basic program
C H A P T E R 1
An Introduction
to Visual Basic and
the Visual Basic
Programming
Programming
Environment
Environment
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
You should do the exercises and labs in this chapter only after you
have finished Chapter 1 of your book, Programming Logic and
Design, Sixth Edition, by Joyce Farrell. This chapter introduces the
Visual Basic (VB) programming language and its history. It explains
some introductory object-oriented concepts, and describes the pro-
cess of compiling and executing a Visual Basic program. You begin
writing Visual Basic programs in Chapter 2 of this book.
The Visual Basic Programming
Language
Visual Basic is a programming language that you can use to cre-
ate interactive Web pages and to write Web-based applications that
run on Web servers. Web servers are the computers that “serve up”
content when you request to view Web pages. An online bookstore
and an online course registration system are examples of Web-based
applications. Visual Basic is also used to develop Windows-based
stand-alone enterprise applications (programs that help manage
data and run a business).
What makes Visual Basic especially useful is that it is an object-
oriented programming language. The term object-oriented encom-
passes a number of concepts explained later in this chapter and
throughout this book. For now, all you need to know is that an object-
oriented programming language is modular in nature, allowing the
programmer to build a program from reusable parts of programs
called classes, objects, and methods.
When Visual Basic was introduced by Microsoft in 1991, it was
described as the perfect programming language because it allowed
programmers to easily create applications that include a graphical
user interface (GUI). A GUI allows users to interact with programs
by using a mouse to point, drag, or click.
Three Types of Visual Basic Programs
Visual Basic programs can be written as Web applications, Windows
applications, or console applications. A Web application is a pro-
gram that runs on the World Wide Web and is available to end users
on any platform (e.g., Windows, Mac, Linux). A Windows applica-
tion is a program, such as Microsoft Word or Excel, that runs on
a Windows system. A console application is a program, without
a GUI, that executes in a console window and produces text-based
output. In Chapters 1 through 9 of this book, you write console appli-
cations. Visual Basic programmers often use the Microsoft Visual
2
C H A P T E R 1 An Introduction to Visual Basic
Studio Integrated Development Environment (IDE) when they write
programs. In Chapter 10, you learn to use the IDE to create Visual
Basic Windows applications that include a simple GUI.
Writing console applications is a good way to learn a language
because when you are working on one, you don’t have to be con-
cerned with a GUI. Console applications allow you to focus on the
syntax of the language and the language constructs, such as how and
when you use selection and looping statements. (You’ll learn about
selection and looping statements later in this book.)
An Introduction to Object-Oriented
Terminology
You must understand a few object-oriented concepts to be success-
ful at reading and working with Visual Basic programs in this book.
Note, however, that you will not learn enough to make you a Visual
Basic programmer. You will have to take additional Visual Basic
courses to become a Visual Basic programmer. This book teaches you
only the basics.
To fully understand the term object-oriented, you need to know a
little about procedural programming. Procedural programming is
a style of programming that is older than object-oriented program-
ming. Procedural programs consist of statements that the computer
runs or executes. Many of the statements make calls (a request to
run or execute) to groups of other statements that are known as pro-
cedures, modules, methods, or functions. These programs are known
as “procedural” because they perform a sequence of procedures.
Procedural programming focuses on writing code that takes some
data (for example, quarterly sales figures), performs a specific task
using the data (for example, adding up the sales figures), and then
produces output (for example, a sales report). When people who use
procedural programs (the users) decide that they want their programs
to do something slightly different, a programmer must revise the pro-
gram code, taking great care not to introduce errors into the logic of
the program.
Today, we need computer programs that are flexible and easy to
revise. Object-oriented programming languages, including Visual
Basic, were introduced to meet this need. In object-oriented pro-
gramming, the programmer can focus on the data that he or she
wants to manipulate, rather than the individual lines of code required
to manipulate that data (although those individual lines still must
eventually be written). An object-oriented program is made up of a
collection of interacting objects.
3
An Introduction to Object-Oriented Terminology
An object represents something in the real world, such as a
car, an employee, or an item in an inventory. An object includes
(or encapsulates) both the data related to the object and the tasks
you can perform on that data. The term behavior is sometimes used
to refer to the tasks you can perform on an object’s data. For example,
the data for an inventory object might include a list of inventory
items, the number of each item in stock, the number of days each
item has been in stock, and so on. The behaviors of the inventory
object might include calculations that add up the total number of
items in stock and calculations that determine the average amount of
time each item remains in inventory.
In object-oriented programming, the data items within an object are
known collectively as the object’s attributes or properties. You can
think of an attribute or property as one of the characteristics of an
object, such as its shape, its color, or its name. The tasks the object
performs on that data are known as the object’s methods. (You can
also think of a method as an object’s behavior.) Because methods are
built into objects, when you create a Visual Basic program, you don’t
always have to write multiple lines of code telling the program exactly
how to manipulate the object’s data. Instead, you can write a shorter
line of code, known as a call, that passes a message to the method
indicating that you need it to do something.
For example, you can display dialog boxes, scroll bars, and buttons for
a user of your program to type in or click on simply by sending a mes-
sage to an existing object. At other times, you will be responsible for
creating your own classes and writing the code for the methods that
are part of that class. Whether you use existing, prewritten classes
or create your own classes, one of your main jobs as a Visual Basic
programmer is to communicate with the various objects in a program
(and the methods of those objects) by passing messages. Individual
objects in a program can also pass messages to other objects.
When Visual Basic programmers begin to write an object-oriented
program, they first create a class. A class can be thought of as a
template or pattern for a group of similar objects. In a class, the
programmer specifies the data (attributes/properties) and behaviors
(methods) for all objects that belong to that class. An object is some-
times referred to as an instance of a class, and the process of creating
an object is referred to as instantiation.
To understand the terms class, instance, and instantiation, it’s helpful
to think of them in terms of a real-world example—baking a choco-
late cake. The recipe is similar to a class, and an actual cake is an
object. If you wanted to, you could create many chocolate cakes that
are all based on the same recipe. For example, your mother’s birthday
4
C H A P T E R 1 An Introduction to Visual Basic
cake, your sister’s anniversary cake, and the cake for your neighbor-
hood bake sale all might be based on a single recipe that contains
the same data (ingredients) and methods (instructions). In object-
oriented programming, you can create as many objects as you need
in your program from the same class.
The Structure of a Visual Basic
Program
When a programmer learns a new programming language, the first
program he or she traditionally writes is a Hello World program—a
program that displays the message “Hello World” on the screen.
Creating this simple program illustrates that the language is capable
of instructing the computer to communicate with the outside world.
The Visual Basic version of the Hello World program is shown in
Figure 1-1.
Module HelloWorld
Sub Main()
System.Console.WriteLine("Hello World.")
End Sub
End Module
Figure 1-1 Hello World program
At this point, you’re not expected to understand all the code in
Figure 1-1. Just notice that the code begins with the word Module.
Module is a special word, known as a keyword, which is reserved by
Visual Basic to have a special meaning. A Module is one of the pos-
sible packages into which you can place code that you want to com-
pile and execute. The Module keyword tells the Visual Basic compiler
that you are beginning the creation of a Module and that what follows
is part of that Module. The name of the Module is up to you; however,
to make your program easier to maintain and revise later, take care to
choose a meaningful name. Because this program is written to display
the words “Hello World.” on the user’s screen, it makes sense to name
the Module HelloWorld. The keywords End Module on the last line of
Figure 1-1 mark the end of the Module.
On the second line in Figure 1-1, you see Sub Main(). This marks the
beginning of the procedure named Main().
This is a special procedure in a Visual Basic program; the Main() pro-
cedure is the first procedure that executes when any program runs.
5
The Structure of a Visual Basic Program
The programs in the first eight chapters of this book will include only
the Main() procedure. In later chapters you will be able to include
additional procedures.
The first part of any procedure is its header. In Figure 1-1, the header
for the Main() procedure begins with the Sub keyword and is fol-
lowed by the procedure name, which is Main(). The End Sub on the
second-to-last line of Figure 1-1 marks the end of the Main() pro-
cedure. All the code within the procedure header and the End Sub
executes when the Main() procedure executes. In Figure 1-1, there is
only this one line of code that executes:
System.Console.WriteLine("Hello World.")
This is the line that causes the words “Hello World.” to appear on
the user’s screen. This line consists of two parts. The first part,
System.Console.WriteLine(), prints (that is, displays on the
screen) whatever is included within its parentheses and positions
the cursor so any subsequent output appears on the next line. In
this example, the parentheses contain the message “Hello World.”
so that is what will appear on the screen. (The quotation marks
will not appear on the screen, but they are necessary to make the
program work.)
In the statement System.Console.WriteLine("Hello World."),
System is a namespace, Console is an object, and WriteLine()
is a method. A namespace is a collection of classes. The System
namespace includes many of the commonly used classes. Visual Basic
programs frequently use the namespace-dot-object-dot-method
syntax or the class-dot-object-dot-method syntax.
Next, you learn about the Visual Basic development cycle so
that later in this chapter, you can compile the Hello World
program and execute it. The Hello World program is saved in a
file named HelloWorld.vb and is included in the student files for
this chapter.
The Visual Basic Development Cycle
When you finish designing a program and writing the Visual Basic
code that implements your design, you must compile and execute
your program. This three-step process of writing code, compiling
code, and executing code is called the Visual Basic development
cycle. It is illustrated in Figure 1-2. Don’t be concerned if you don’t
understand all the terms in Figure 1-2. These terms are explained in
the following sections.
You can tell
Main() is a
procedure
because of
the parenthe-
ses; all Visual Basic
procedure names are
followed by parentheses.
6
C H A P T E R 1 An Introduction to Visual Basic
Step 1
Write Visual Basic
source code
Source code file
(MyProgram.vb)
Step 2
Compile source code
(vbc MyProgram.vb)
Step 3
Execute the program
Common Intermediate
Language
(CIL)
Output
Figure 1-2 The Visual Basic development cycle
Writing Visual Basic Source Code
As you learned in the previous section, you write a Visual Basic pro-
gram by creating a Module and including a procedure named Main()
in the Module. But what do you use to write the program, and where
do you save it?
To write a Visual Basic program, you can use any text editor, but the
steps in this book assume you are using Windows Notepad. To start
Notepad, click the Start button, point to Programs or All Programs,
click Accessories, and then click Notepad. Once Notepad starts,
you simply type in your Visual Basic source code. Source code is the
name used for the statements that make up a Visual Basic program.
For example, the code shown in Figure 1-1 is source code.
When you save the file that contains the source code, it is important
to add the extension .vb to the filename. For the Hello World pro-
gram, the Module is named HelloWorld; therefore, it is convenient to
name the source code file HelloWorld.vb. Of course, it is also impor-
tant to remember the location of the folder in which you choose to
save your source code file.
Compiling a Visual Basic Program
The Visual Basic compiler is named vbc, and it is responsible
for taking your source code and transforming it into Common
Intermediate Language (CIL). CIL is intermediate, machine-
independent code. Intermediate means that the code is between
7
The Visual Basic Development Cycle
source code and machine code. Machine code consists of the 1s
and 0s that a computer needs to execute a program. Next, the Visual
Basic compiler reads the CIL code and produces an executable file.
This file has the same name as the source code file, but it has an .exe
extension rather than a .vb extension.
The following steps show how to compile a source code file. These
steps assume you have already created and saved the HelloWorld.vb
source code file.
1. Set your PATH environment variable. Refer to “Read This
Before You Begin” at the front of this book or ask your
instructor for instructions on how to set the PATH environ-
ment variable.
2. Open a Command Prompt window. To do this in
Windows XP, click the Start button, point to All Programs,
point to Accessories, and then click Command Prompt.
In Vista or Windows 7, click the Start button, point to All
Programs, click Accessories, and then click Command
Prompt. The cursor blinks to the right of the current file path.
3. To compile your source code file, you first have to change to
the file path containing your source code file. To do this, type
cd driveletter:path where driveletter is the drive contain-
ing your file, and path is the path to the folder containing
your file. For example, to open a file stored in a folder named
“Testing,” which is in turn stored in a folder named “My
Program,” which is stored on the C: drive, you would type
cd c:My ProgramTesting. After you type the command,
press Enter. The cursor now blinks next to the file path for
the folder containing your source code file.
4. Type the following command, which uses the Visual Basic
compiler vbc to compile the program:
vbc HelloWorld.vb
If there are no syntax errors in your source code, a file named
HelloWorld.exe is created, and you will not see anything
special happen. If there are syntax errors, you will see error
messages on the screen. In that case, you need to go back to
Notepad to fix the errors, save the source code file again, and
recompile until no syntax errors remain. Syntax errors are
messages from the compiler that tell you what your errors are
and where they are located in your source code file.
5. After the program is compiled, you can use the dir com-
mand to display a directory listing to see the file named
HelloWorld.exe. To execute the dir command, you type dir
If you are
working in
a school
computer
lab, the PATH
environment variable
might already have
been set for you.
The PATH
environment
variable tells
your operating
system which
directories on your sys-
tem contain commands.
8
C H A P T E R 1 An Introduction to Visual Basic
at the command prompt. For example, if your source code file
is located at C:My ProgramTesting, the command prompt
and dir command should look like this: C:My Program
Testing> dir. The HelloWorld.exe file should be in the same
directory as the source code file, HelloWorld.vb.
Step 3 in the development cycle is executing the Visual Basic pro-
gram. You’ll learn about that next.
Executing a Visual Basic Program
As you know, a computer can understand only machine code (1s and
0s). The machine code for your Visual Basic program is stored in a file
with an .exe extension.
To execute the Hello World program, do the following:
1. Open a Command Prompt window. To do this in Windows
XP, click the Start button, point to All Programs, point to
Accessories, and then click Command Prompt. In Vista or
Windows 7, click the Start button, point to All Programs,
click Accessories, and then click Command Prompt.
Change to the file path containing your executable file, if
necessary, and then enter the following command:
HelloWorld
2. When the program executes, the words “Hello World.” appear
in a Command Prompt window.
Figure 1-3 illustrates the steps involved in compiling HelloWorld.vb
using the vbc compiler, executing the dir command to verify that the file
HelloWorld.exe was created, and executing the Hello World program.
Figure 1-3 Compiling and executing the Hello World program
At this point in
your program-
ming career,
don’t expect
to understand
the contents of an .exe
file if you open one using
a text editor, such as
Notepad.
You must be
in the same
directory that
contains your
.exe file
when you execute the
program.
9
The Visual Basic Development Cycle
Exercise 1-1: Understanding How to Compile
and Execute Visual Basic Programs
In this exercise, you use what you have learned about compiling and
executing Visual Basic programs to answer Questions 1–2.
You have written a Visual Basic program and have stored your source
code in a file named MyVBProgram.vb.
1. What command would you use to compile the source code?
2. What command would you use to execute the program?
LAB 1.1 Compiling and Executing
a Visual Basic Program
In this lab, you compile and execute a prewritten Visual
Basic program, and then answer Questions 1–6.
1. Open the source code file named GoodMorning.vb using
Notepad or the text editor of your choice.
2. Save this source code file in a directory of your choice, and
then change to that directory.
3. Compile the source code file. There should be no syntax errors.
Record the command you used to compile the source code file.
4. Execute the program. Record the command you used to exe-
cute the program, and also record the output of this program.
5. Modify the program so that it displays “Good Job!,” and
then change the Module name to GoodJob. Save the file as
GoodJob.vb. Compile and execute the program.
6. Modify the Good Job program so that it prints two lines of
output. Add a second output statement that displays “Have
a great day.” Change the Module name to GoodJob2 and then
save the modified file as GoodJob2.vb. Compile and execute
the program.
10
C H A P T E R 1 An Introduction to Visual Basic
After studying this chapter, you will be able to:
Name variables and use appropriate data types

Declare and initialize variables

Understand and use unnamed and named constants

Use arithmetic operators in expressions

Use assignment operators in assignment statements

Write Visual Basic comments

Write programs using sequential statements and interactive

input statements
C H A P T E R 2
Variables, Constants,
Operators, and
Writing Programs
Using Sequential
Statements
In this chapter, you learn about writing programs that use variables,
constants, and arithmetic operators. You also learn about programs
that receive interactive input from a user of your programs. We begin
by reviewing variables and constants and learning how to use them in
a Visual Basic program. You should do the exercises and labs in this
chapter only after you have finished Chapters 2 and 3 of your book,
Programming Logic and Design, Sixth Edition, by Joyce Farrell.
Variables
As you know, a variable is a named location in the computer’s
memory whose contents can vary (thus the term variable). You use
variables in a program when you need to store values. The values
stored in variables often change as a program executes.
In Visual Basic, it is a good programming practice to declare variables
before you use them in a program. Declaring a variable is a two-part
process: first, you give the variable a name, and then you specify its
data type. You’ll learn about data types shortly. But first, we’ll focus
on the rules for naming variables in Visual Basic.
Variable Names
Variable names in Visual Basic can consist of letters, numerical digits,
and the underscore character, but they cannot begin with a digit. You
should avoid variable names that begin with an underscore because
they are not compliant with the Common Language Specification
(CLS). You will learn more about the CLS in additional courses you
take in Visual Basic.
You cannot use a Visual Basic keyword for a variable name. As you
learned in Chapter 1 of this book, a keyword is a word with a special
meaning in Visual Basic. The following are all examples of legal vari-
able names in Visual Basic: my_var, num6, intValue, and firstName.
Table 2-1 lists some examples of invalid variable names, and explains
why each is invalid.
Name of Variable Explanation
3wrong Invalid because it begins with a digit
don’t Invalid because it contains a single quotation mark
public Invalid because it is a Visual Basic keyword
Table 2-1 Some examples of invalid variable names
When naming variables, keep in mind that Visual Basic is not case
sensitive—in other words, Visual Basic does not know the difference
A variable is
sometimes
referred to as
an identifier.
12
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
between uppercase and lowercase characters. That means value,
Value, and VaLuE are the same variable name in Visual Basic.
In Visual Basic, variable names can be 1,023 characters in length.
A good rule is to give variables meaningful names that are long
enough to describe how the variable is used, but not so long that
you make your program hard to read or cause yourself unnec-
essary typing. For example, a variable named firstName will
clearly be used to store someone’s first name. The variable name
freshmanStudentFirstName is descriptive but inconveniently long;
the variable name fn is too short and not meaningful.
One of the naming conventions used by Visual Basic programmers is
called camel case. This means:
Variable names are made up of multiple words, with no spaces
•
between them.
The first character in the variable name is lowercase.
•
The first character of each word after the first word is a capitalized
•
character.
Examples of Visual Basic variable names in camel case include
firstName, myAge, and salePrice. You do not include spaces between
the words in a variable name.
Visual Basic Data Types
In addition to specifying a name for a variable, you also need to spec-
ify a particular data type for that variable. A variable’s data type dic-
tates the amount of memory that is allocated for the variable, the type
of data that you can store in the variable, and the types of operations
that can be performed on the variable. There are many different kinds
of data types, but in this book we will focus on the most basic kind
of data types, known as primitive data types. There are 12 primitive
data types in Visual Basic: Boolean, Byte, Char, Date, Double, Decimal,
Integer, Long, Object, Short, Single, and String. Some of these data
types (Short, Integer, Long, Double, and Single) are used for vari-
ables that store numeric values, and are referred to as numeric data
types. The others have specialized purposes. For example, the Boolean
data type is used to store a value of either True or False.
You will not use all of Visual Basic’s primitive data types in the pro-
grams you write in this book. Instead, you will focus on two of the
numeric data types (Integer and Double) and one type that holds
text (String). The Integer data type is used for values that are whole
numbers. For example, you could use a variable with the data type
Integer to store someone’s age (for example, 25) or the number of
Although
Visual Basic is
not case sen-
sitive, your
programs will
be easier for you and
other programmers to
read if you use uppercase
and lowercase characters
consistently.
13
Visual Basic Data Types
students in a class (for example, 35). A variable of the Integer data
type occupies 32 bits (4 bytes) of space in memory.
You use the data type Double to store a floating point value (that is, a
fractional value), such as the price of an item (2.95) or a measurement
(2.5 feet). A variable of the Double data type occupies 64 bits (8 bytes)
of space in memory. You will learn about using other data types as
you continue to learn more about Visual Basic in subsequent courses.
The Integer and Double data types will be adequate for all the
numeric variables you will use in this book. But what about when
you need to store a group of characters (such as a person’s name) in a
variable? In programming, we refer to a group of one or more charac-
ters as a string. An example of a string is the last name “Wallace” or
a product type such as a “desk.” In Visual Basic, the String primitive
data type is used for storing strings.
Exercise 2-1: Using Visual Basic Variables,
Data Types, and Keywords
In this exercise, you use what you have learned about naming
variables, data types, and keywords to answer Questions 1–2.
1. Is each of the following a legal Visual Basic variable name?
(Answer “yes” or “no.”)
myAge this_is_a_var NUMBER
yourAge number $number
Single 1number intNum
May25 number Two Number
2. What data type (Integer, Double, or String) is most appro-
priate for storing each of the following values?
A person’s height (in inches)
The amount of interest on a loan, such as 10%
The price of a pair of boots
The name of your pet
The number of CDs you own
Declaring and Initializing Variables
Now that you understand the rules for naming a variable, and you
understand the concept of a data type, you are ready to learn how to
declare a variable. In Visual Basic, it is a good programming practice
to declare all variables before you use them in a program. When you
declare a variable, you tell the compiler that you are going to use the
In Program-
ming Logic
and Design,
Sixth Edition,
the data type
num is used to refer to all
numeric data types. That
book does not make a
distinction between
Integer and Double
because the pseudocode
used in the book is not
specific to any one pro-
gramming language.
However, in Visual Basic
this distinction is always
maintained.
14
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
variable. In the process of declaring a variable, you must specify the
variable’s name and its data type. Declaring a variable tells the com-
piler that it needs to reserve a memory location for the variable. A line
of code that declares a variable is known as a variable declaration.
The Visual Basic syntax for a variable declaration is as follows:
Dim variableName As dataType
For example, the declaration statement Dim counter As Integer
declares a variable named counter of the Integer data type. The
compiler reserves the amount of memory space allotted to an
Integer variable (32 bits, or 4 bytes) for the variable named counter.
The compiler then assigns the new variable a specific memory
address. In Figure 2-1, the memory address for the variable named
counter is 1000, although you wouldn’t typically know the memory
address of the variables included in your Visual Basic programs.
Figure 2-1 Declaration of variable and memory allocation
counter (variable name) another variable
value of counter value of the next variable
first
byte
second
byte
third
byte
fourth
byte
1000 (The memory address is assigned by
the compiler; you cannot assign the memory
address yourself.)
1004 (This is the next available memory address
after counter because 4 bytes [1000, 1001,
1002, and 1003] have been reserved for the
variable named counter.)
Dim counter As Integer
You can also initialize a Visual Basic variable when you declare it.
When you initialize a Visual Basic variable, you give it an initial
value. For example, you can assign an initial value of 8 to the counter
variable when you declare it, as shown in the following code:
Dim counter As Integer = 8
You can also declare and initialize variables of data type Double and
String as shown in the following code:
Dim salary As Double
Dim cost As Double = 12.95
Dim firstName As String
Dim homeAddress As String = "123 Main Street"
Exercise 2-2: Declaring and Initializing Visual
Basic Variables
In this exercise, you use what you have learned about declaring and
initializing variables to answer Questions 1–2.
Numeric
variables are
automatically
initialized to
zero (0),
unless you specify a
different value.
15
Declaring and Initializing Variables
1. Write a Visual Basic variable declaration for each of the
following. Use Integer, Double, or String and choose
meaningful variable names.
Declare a variable to store a product number (1–1000).
Declare a variable to store the number of pets in your family.
Declare a variable to store the price of a pair of boots.
Declare a variable to store the name of your favorite book.
2. Declare and initialize variables to represent the following
values. Use Integer, Double, or String, and choose meaningful
variable names.
One side of a rectangle that is 5.1 inches in length
The number of days in November
The name of your dog, “Duchess”
The number of credit hours you are taking this term
LAB 2.1 Declaring and Initializing
Visual Basic Variables
In this lab, you declare and initialize variables in a Visual
Basic program provided with the data files for this book.
The program, which is saved in a file named NewAge.vb, calculates
your age in the year 2040.
1. Open the source code file named NewAge.vb using Notepad
or the text editor of your choice.
2. Declare an integer variable named newAge.
3. Declare and initialize an integer variable named currentAge.
Initialize this variable with your current age.
4. Declare and initialize an integer variable named currentYear.
Initialize this variable with the value of the current year. Use
four digits for the year.
5. Save this source code file in a directory of your choice, and
then make that directory your working directory.
16
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
6. Compile the source code file NewAge.vb.
7. Execute the program. Record the output of this program.
Constants
As you know, a constant is a value that never changes. In Visual
Basic, you can use both unnamed constants as well as named con-
stants in a program. You’ll learn about named constants shortly. But
first, we’ll focus on unnamed constants.
Unnamed Constants
Computers are able to deal with two basic types of data: text and
numeric. When you use a specific numeric value, such as 35, in a
program, you write it using the numbers, without quotation marks.
A specific numeric value is called a numeric constant because
it does not change; a 35 always has the value 35. When you use a
specific text value, or string of characters, such as “William,” you
enclose the string constant in double quotation marks. Both of the
preceding examples, 35 and “William,” are examples of unnamed
constants because they do not have specified names as variables do.
Named Constants
In addition to variables, Visual Basic allows you to create named
constants. A named constant is similar to a variable, except it can
be assigned a value only once. You use a named constant when you
want to assign a name to a value that will never be changed when a
program executes.
To declare a named constant in Visual Basic, you use the keyword
Const followed by the name of the constant, followed by the keyword
As and the data type. Named constants must be initialized when
they are declared, and their contents may not be changed during
the execution of the program. For example, the following statement
declares an Integer constant named MAX_STUDENTS and initializes
MAX_STUDENTS with the value 35.
Const MAX_STUDENTS As Integer = 35
By convention,
in Visual Basic
the names of
constants are
written in all
uppercase letters. This
makes it easier for you to
spot named constants in
a long block of code.
17
Constants
Exercise 2-3: Declaring and Initializing Visual
Basic Constants
In this exercise, you use what you have learned about declaring and
initializing constants to answer the following question.
1. Declare and initialize constants to represent the following val-
ues. Use Integer, Double, or String and choose meaningful
names.
The price of a car wash is $14.95.
The number of days in November is 30.
The name of your dog is “Duchess”.
The maximum number of credit hours you may take in a term
is 18.
LAB 2.2 Declaring and Initializing
Visual Basic Constants
In this lab, you declare and initialize constants in a Visual
Basic program provided with the data files for this book.
The program, which is saved in a file named NewAge2.vb, calculates
your age in the year 2040.
1. Open the source code file named NewAge2.vb using Notepad
or the text editor of your choice.
2. Declare a constant named YEAR and initialize YEAR with the
value 2040.
3. Edit the following statement so that it uses the constant
named YEAR:
newAge = currentAge + (2040 − currentYear)
4. Edit the following statement, so that it uses the constant
named YEAR:
System.Console.WriteLine ("I’ll be" & newAge & "in 2040.")
5. Save this source code file as NewAge2.vb in a directory of your
choice, and then make that directory your working directory.
6. Compile the source code file NewAge2.vb.
7. Execute the program. Record the output of this program.
18
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
Arithmetic and Assignment Operators
After you declare a variable, you can use it in various tasks. For
example, you can use variables in simple arithmetic calculations, such
as adding, subtracting, and multiplying. You can also perform other
kinds of operations with variables, such as comparing one variable to
another to determine which is greater.
In order to write Visual Basic code that manipulates variables in
this way, you need to be familiar with operators. An operator is a
symbol that tells the computer to perform a mathematical or logical
operation. Visual Basic has a large assortment of operators. We begin
the discussion with a group of operators known as the arithmetic
operators.
Arithmetic Operators
Arithmetic operators are the symbols used to perform arithmetic
calculations. You are probably already very familiar with the arithme-
tic operators for addition (+) and subtraction (−). Table 2-2 lists and
explains Visual Basic’s arithmetic operators.
Operator Name
and Symbol Example Comment
Addition + num1 + num2
Subtraction − num1 − num2
Multiplication * num1 * num2
Integer Division  152 Integer division; result is 7; fraction is truncated
Division / 15/2
15.0 / 2.0
15.0 / 2
Floating-point division; result is 7.5
Floating-point division; result is 7.5
Floating-point division; result is 7.5
Modulus MOD hours MOD 24 Performs division and finds the remainder; result is 1
if the value of hours is 25
Negation − −(num1 − num2) If value of (num1 − num2) is 10, then
−(num1 − num2) is −10
Exponentiation ^ 2 ^ 3 Raises 2 to the third power; result is 8
Table 2-2 Visual Basic arithmetic operators
You can combine arithmetic operators and variables to create
expressions. The computer evaluates each expression, and the result
is a value. To give you an idea of how this works, assume that the
value of num1 is 3 and num2 is 20, and that both are data type Integer.
19
Arithmetic and Assignment Operators
With this information in mind, study the examples of expressions and
their values in Table 2-3.
Expression Value Explanation
num1 + num2 23 3+20=23
num1 − num 2 −17 3−20=−17
num2 MOD num1 2 20 / 3=6 remainder 2
num1 * num2 60 3 * 20=60
num2 / num1 6.66666 20 / 3=6.66666 (floating point division)
num2  num1 6 20 / 3=6 (remainder is truncated)
−num1 −3 Value of num1 is 3, therefore −num1 is −3
num2 ^ num1 8000 20 raised to the third power is 8000
Table 2-3 Expressions and values
Assignment Operators and the Assignment
Statement
Another type of operator is an assignment operator. You use an
assignment operator to assign a value to a variable. A statement that
assigns a value to a variable is known as an assignment statement.
In Visual Basic, there are several types of assignment operators. The
one you will use most often is the = assignment operator, which sim-
ply assigns a value to a variable. Table 2-4 lists and explains some of
Visual Basic’s assignment operators.
Operator Name
and Symbol Example Comment
Assignment = count = 5 Places the value on the right side into the
memory location named on the left side
Initialization = Dim count
As Integer = 5
Places the value on the right side into the
memory location named on the left side
when the variable is declared
Assignment += num += 20 Equivalent to num = num + 20
Assignment −= num −= 20 Equivalent to num = num − 20
Assignment *= num *= 20 Equivalent to num = num * 20
Assignment /= num /= 20 Equivalent to num = num / 20
Assignment = num = 20 Equivalent to num = num  20
Assignment ^= num ^= 20 Equivalent to num = num ^ 20
Table 2-4 Visual Basic assignment operators
20
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
When an assignment statement executes, the computer evaluates
the expression on the right side of the assignment operator and then
assigns the result to the memory location associated with the variable
named on the left side of the assignment operator. An example of an
assignment statement is shown in the following code:
answer = num1 * num2
This assignment statement causes the computer to evaluate the
expression num1 * num2. After evaluating the expression, the com-
puter stores the result in the memory location associated with
answer. If the value stored in the variable named num1 is 3, and the
value stored in the variable named num2 is 20, then the value 60 is
assigned to the variable named answer.
Here is another example:
answer += num1
This statement is equivalent to the following statement:
answer = answer + num1
If the value of answer is currently 10 and the value of num1 is 3,
then the expression on the right side of the assignment statement
answer + num1 evaluates to 13, and the computer assigns the value
13 to answer.
Precedence and Associativity
Once you start to write code that includes operators, you need to be
aware of the order in which a series of operations is performed. In
other words, you need to be aware of the precedence of operations
in your code. Each operator is assigned a certain level of precedence.
For example, multiplication has a higher level of precedence than
addition. So in the expression 3 * 7 + 2, the 3 * 7 would be multi-
plied first; after the multiplication is completed, the 2 is added.
But what happens when two operators have the same precedence?
The rules of associativity determine the order in which operations
are evaluated in an expression containing two or more operators with
the same precedence. For example, in the expression 3 + 7 − 2, the
addition and subtraction operators have the same precedence. As
shown in Table 2-5, the addition and subtraction operators have left-
to-right associativity, which causes the expression to be evaluated
from left to right (3 + 7 added first; then 2 is subtracted). Table 2-5
shows the precedence and associativity of the operators discussed in
this chapter.
21
Arithmetic and Assignment Operators
Operator Name Operator Symbol Order of Precedence Associativity
Parentheses () First Left to right
Exponentiation ^ Second Left to right
Negation − Third Right to left
Multiplication and
division
* / Fourth Left to right
Integer division  Fifth Left to right
Modulus MOD Sixth Left to right
Addition and
subtraction
+ − Seventh Left to right
Assignment = += −= Eighth Right to left
*= /= =
^=
Table 2-5 Order of precedence and associativity
As you can see in Table 2-5, the parentheses operator ( ) has the
highest precedence. You use this operator to change the order in
which operations are performed. Note the following example:
average = test1 + test2 / 2
The task of this statement is to find the average of two test scores.
The way this statement is currently written, the compiler will
divide the value in the test2 variable by 2, and then add it to the
value in the test1 variable. So, for example, if the value of test1 is
90 and the value of test2 is 88, then the value assigned to average
will be 134, which is obviously not the correct average of these two
test scores. By using the parentheses operator in this example, you
can force the addition to occur before the division. The correct
statement looks like this:
average = (test1 + test2) / 2
In this example, the value of test1, 90, is added to the value of test2,
88, and then the sum is divided by 2. The value assigned to average,
89, is the correct result.
Exercise 2-4: Understanding Operator
Precedence and Associativity
In this exercise, you use what you have learned about operator pre-
cedence and associativity. Study the following code and then answer
Questions 1–2.
22
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
' This program demonstrates the precedence and
' associativity of operators.
Module Operators
Sub Main()
Dim value1 As Integer = 8
Dim value2 As Integer = 2
Dim value3 As Integer = 11
Dim answer1 As Integer
Dim answer2 As Integer
Dim answer3 As Integer
Dim answer4 As Integer
Dim answer5 As Integer
Dim answer6 As Integer
answer1 = value1 * value2 + value3
System.Console.WriteLine("Answer 1: " & answer1)
answer2 = value1 * (value2 + value3)
System.Console.WriteLine("Answer 2: " & answer2)
answer3 = value1 + value2 − value3
System.Console.WriteLine("Answer 3: " & answer3)
answer4 = value1 + (value2 − value3)
System.Console.WriteLine("Answer 4: " & answer4)
answer5 = value1 + value2 * value3
System.Console.WriteLine("Answer 5: " & answer5)
answer6 = value3 / value2
System.Console.WriteLine("Answer 6: " & answer6)
End Sub
End Module
1. What is the value of answer1, answer2, answer3, answer4,
answer5, and answer6?
2. Explain how precedence and associativity affect the result.
LAB 2.3 Arithmetic and Assignment
Operators
In this lab, you complete a Visual Basic program that
is provided along with the data files for this book. The
23
Arithmetic and Assignment Operators
program, which was written for an appliance company, prints the
name of an appliance, its retail price, its wholesale price, the profit
made on the appliance, a sale price, and the profit made when the sale
price is used.
1. Open the file named Appliance.vb using Notepad or the text
editor of your choice.
2. The file includes variable declarations and output statements.
Read them carefully before you proceed to the next step.
3. Design the logic and write the Visual Basic code that will use
assignment statements to first calculate the profit, then cal-
culate the sale price, and finally calculate the profit when the
sale price is used. Profit is defined as the retail price minus the
wholesale price. The sale price is 20% deducted from the retail
price. The sale profit is defined as the sale price minus the
wholesale price. Perform the appropriate calculations as part
of your assignment statements.
4. Save the source code file in a directory of your choice, and
then make that directory your working directory.
5. Compile the program.
6. Execute the program. Your output should be as follows:
Item Name: Dishwasher
•
Retail Price: $425
•
Wholesale Price: $275
•
Profit: $150
•
Sale Price: $340
•
Sale Profit: $65
•
Next, you see how to put together all you have learned in this chapter
to write a Visual Basic program that uses sequential statements, com-
ments, and interactive input statements.
Sequential Statements, Comments,
and Interactive Input Statements
The term sequential statements (or sequence), refers to a series
of statements that must be performed in sequential order, one after
another. You use a sequence in programs when you want to perform
actions one after the other. A sequence can contain any number of
24
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
actions, but those actions must be in the proper order, and no action
in the sequence can be skipped. Note that a sequence can contain
comments that are not considered part of the sequence itself.
Comments serve as documentation, explaining the code to the
programmer and any other people who might read it. In Chapter 2
of Programming Logic and Design, Sixth Edition, you learned about
program comments, which are statements that do not execute. You
use comments in Visual Basic programs to explain your logic to
people who read your source code. The Visual Basic compiler ignores
comments.
In Visual Basic, you type an apostrophe character (’) at the begin-
ning of the text that you want the compiler to ignore. You may place
comments anywhere in a Visual Basic program. In the Visual Basic
program below, the first five lines of the program are comments that
explain some basic information about the program. Comments are
included throughout to describe various parts of the program.
A sequence often includes interactive input statements, which are
statements that ask, or prompt, the user to input data. The Visual
Basic program in the following example uses sequential statements
and interactive input statements to convert a Fahrenheit temperature
to its Celsius equivalent:
' This Visual Basic program converts a Fahrenheit
' temperature to Celsius.
' Input: Interactive
' Output: Fahrenheit temperature followed by
' Celsius temperature
Option Explicit On
Option Strict On
Module Temperature
Sub Main()
Dim fahrenheitString As String
Dim fahrenheit As Double
Dim celsius As Double
' Get interactive user input
fahrenheitString = InputBox$( _
"Enter Fahrenheit temperature: ")
' Convert String to Double
fahrenheit = Convert.ToDouble(fahrenheitString)
' Calculate celsius
celsius = (fahrenheit − 32.0) * (5.0/9.0)
' Output
System.Console.WriteLine("Fahrenheit temperature:" & _
fahrenheit)
System.Console.WriteLine("Celsius temperature:" & _
celsius)
End Sub
End Module
You are
responsible
for including
well-written,
meaningful
comments in all of the
programs that you write.
In fact, some people think
that commenting your
source code is as impor-
tant as the source code
itself.
25
Sequential Statements, Comments, and Interactive Input Statements
This program is made up of sequential statements that execute one
after the other. As noted above, it also includes comments explaining
the code. The comment lines begin with '.
The statement, Option Explicit On, turns on the Visual Basic
option that requires you to declare all variables in your program.
The default in Visual Basic is that this option is on. The statement,
Option Strict On, turns on the Visual Basic option that requires
you to declare variables with a specific type and can therefore accept
only values of that data type. The Strict option must be turned on
to enforce strong typing. The Strict option is turned off by default.
It is highly recommended that you turn on this option; you should
get in the habit of including this statement in all your Visual Basic
programs.
After the variable fahrenheitString is declared as a String, and
fahrenheit and celsius are declared (using the Double data type),
the following assignment statement executes:
fahrenheitString = InputBox$( _
"Enter Fahrenheit temperature:")
The InputBox$() function (on the right side of the assignment state-
ment) is used when you want the program’s user to interactively
input data needed by your program. When you use the InputBox$()
function, you specify within the parentheses the words you want to
appear in the dialog box on the user’s screen. In this example, the
phrase “Enter Fahrenheit temperature:” will appear in the dialog box
on the user’s screen. The same dialog box also displays a text box
where the user can type his or her input, as shown in Figure 2-2.
Figure 2-2 An input dialog box
In this program, you want the user to input a Fahrenheit temperature
value so that the program can convert it to Celsius. You would think,
then, that this would be a simple matter of taking the value entered by the
user, assigning it to a variable, and then performing the necessary conver-
sion calculation. However, Visual Basic considers any input entered into
an input dialog box to be a string. In this case, the Fahrenheit value input
by the user is assigned to the String variable named fahrenheitString.
The problem is that we can’t perform calculations on strings; we can only
Notice that
the under-
score charac-
ter (_) is used
in the output
statement to continue a
single statement from
one line to the next.
26
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
perform calculations on numeric variables. So, before the program can
proceed with the calculation required to convert a Fahrenheit value to a
Celsius value, we need to transfer the value entered by the user to a vari-
able with a numeric data type.
That task is performed by the following assignment statement, which
is the second statement to execute:
fahrenheit = Convert.ToDouble(fahrenheitString)
The ToDouble() method is used on the right side of this assignment
statement. This method belongs to the Convert class and is used
to convert the Fahrenheit value, which the compiler automatically
considered a String, to the Double data type. Once the String is
converted to Double, it is assigned to the variable fahrenheit (which,
at the beginning of the program, was declared as a Double).
The third statement to execute is another assignment statement, as
follows:
celsius = (fahrenheit − 32.0) * (5.0 / 9.0)
The formula that converts Fahrenheit temperatures to Celsius is
used on the right side of this assignment statement. Notice the use of
parentheses in the expression to control precedence. The expression
is evaluated, and the resulting value is assigned to the variable named
celsius.
Notice that the division uses the / operator. This is an example of
floating-point division, which results in a value that includes a fraction.
If the  operator were used, integer division would be performed,
and the fractional portion would be truncated. This would result in
a value of 0.
The next two statements to execute in sequence are both output
statements, as follows:
System.Console.WriteLine("Fahrenheit temperature:" & _
fahrenheit)
System.Console.WriteLine("Celsius temperature:" & _
celsius)
The statement System.Console.WriteLine() is used to output what-
ever is within the parentheses. The first output statement displays
the words “Fahrenheit temperature:” followed by the value stored in
the variable fahrenheit. The second output statement displays the
words “Celsius temperature:” followed by the value stored in the vari-
able celsius. To use the WriteLine() method correctly, you include
only one argument within the parentheses. Arguments are discussed
briefly in Chapter 3 and in more detail in Chapter 9. The concatena-
tion operator is used in both output statements to combine two items
into one (a string constant, which is one or more characters within
27
Sequential Statements, Comments, and Interactive Input Statements
double quotes, and a Double). The & symbol, when used in this con-
text, is the concatenation operator. It is used to combine two values
next to each other to create a single string.
This program is saved in a file named Temperature.vb and is
included in the student files for this chapter. You can see the output
produced by the Temperature program in Figure 2-3.
Figure 2-3 Output produced by the Temperature.vb program
Now that you have seen a complete Visual Basic program that uses
sequential statements and interactive input statements, it is time for
you to begin writing your own programs.
Exercise 2-5: Understanding Sequential
Statements
In this exercise, you use what you have learned about sequential state-
ments. Read the following scenario and then answer Questions 1–4.
Suppose you have written a Visual Basic program that calculates the
amount of paint you need to cover the walls in your family room.
Two walls are 10 feet high and 18.5 feet wide. The other two walls are
10 feet high and 20.5 feet wide. The salesperson at the home improve-
ment store told you to buy 1 gallon of paint for every 150 square feet
of wall you need to paint. Suppose you wrote the following code, but
your program is not compiling. This program is saved in a file named
Paint.vb and is included in the student files for this chapter. Take a
few minutes to study this code and then answer Questions 1–4.
' This program calculates the number of gallons
' of paint needed.
Option Explicit On
Option Strict On
Module Paint
Sub Main()
Dim height1 As Double = 10
Dim height2 As Double = 10
Dim width1 As Integer = 18.5
Dim width2 As Double = 20.5
Dim squareFeet As Double
Dim numGallons As Integer
In Program-
ming Logic
and Design,
Sixth Edition,
the comma
(,) is used as the concat-
enation operator.
You will learn
how to control
the number of
places after
the decimal
point when you output
floating-point values in
Chapter 9 of this book.
28
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
numGallons = squareFeet / 150
squareFeet = (width1 * height1 + width2 * height2) * 2
System.Console.WriteLine("Number of Gallons:" & _
numGallons)
End Sub
End Module
1. The first error is in this line of code.
Dim width1 As Integer = 18.5
What do you have to do to fix this problem?
2. The second error has to do with these three lines of code.
Dim squareFeet As Double
Dim numGallons As Integer
numGallons = squareFeet / 150
What must you do to fix this problem?
3. Even if you fix the problems identified in Question 1 and
Question 2, you still have a problem with this program. It has
to do with the order in which your statements are written.
Identify the problem, and then determine what you need to
do to fix the problem. On the following lines, describe how to
fix the problem.
4. You have two variables declared in this program to represent
the height of your walls, height1 and height2. Do you need
both of these variables? If not, how would you change the
program? Be sure to identify all of the changes you would
make.
LAB 2.4 Using Sequential Statements
in a Visual Basic Program
In this lab, you complete a Visual Basic program provided
with the data files for this book. The program calculates
the amount of tax withheld from an employee’s weekly salary, the tax
deduction to which the employee is entitled for each dependent, and
29
Sequential Statements, Comments, and Interactive Input Statements
the employee’s take-home pay. The program output includes state tax
withheld, federal tax withheld, dependent tax deductions, salary, and
take-home pay.
1. Open the source code file named Payroll.vb using Notepad
or the text editor of your choice.
2. Variables have been declared and initialized for you as
needed, and the output statements have been written. Read
the code carefully before you proceed to the next step.
3. Write the Visual Basic code needed to perform the following:
Calculate state withholding tax at 3.0%, and calculate
•
federal withholding tax at 30.0%.
Calculate dependent deductions at 5.0% of the employee’s
•
salary for each dependent.
Calculate total withholding.
•
Calculate take-home pay as salary minus total withholding
•
plus deductions.
4. Save this source code file in a directory of your choice, and
then make that directory your working directory.
5. Compile the program.
6. Execute the program. You should get the following output:
State Tax: $28.5
•
Federal Tax: $285
•
Dependents: $142.5
•
Salary: $950
•
Take-Home Pay: $779
•
7. In this program, the variables named salary and
numDependents are initialized with the values 950.0 and 3. To
make this program more flexible, modify it to accept interac-
tive input for salary and numDependents. Name the modified
version Payroll2.vb.
30
C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
C H A P T E R 3
Writing Structured
Visual Basic
Programs
After studying this chapter, you will be able to:
Use structured flowcharts and pseudocode to write

structured Visual Basic programs
Write simple modular programs in Visual Basic

Other documents randomly have
different content
GLAMORGANSHIRE.
Glamorgan.—Rev. Robert Knight, Captain Boteler, Dr Carne;
Messrs A. Murray, E. David, William Llewellyn, and R.
Franklen.
GLOUCESTERSHIRE, EAST.
Cirencester and Gloucestershire.—Messrs P. Matthews, Edmund
Ruck, David Bowly.
HAMPSHIRE, NORTH.
Alton District.—Messrs H. Holding, Edward Knight, H. J.
Mulcock, W. Garnett, J. Eggan.
Basingstoke.—Mr George Harriott.
HAMPSHIRE, SOUTH.
Botley and South Hants.—Messrs Edward Twynam, Josh.
Blundell, Caleb Gater, W. C. Spooner.
HEREFORDSHIRE.
Herefordshire.—Mr Henry Higgins.
Ledbury District.—Rev. Edward Higgins, Messrs Reynolds
Petton, Thomas France.
Ross District.—Mr H. Chillingworth.
HUNTINGDONSHIRE.
Huntingdonshire.—Rev. James Linton, Messrs John Mann,
Hammond, Ibbot Mason, Robert T. Moseley, Geo. Brighty,
Peter Purvis, John Warsop.
KENT, EAST.
East Kent.—Sir B. W. Bridges, Bart., Messrs D. H. Carttar,
Edward Hughes, John Abbot, Edward C. Hughes, Rev. Bradley
Dyne, Musgrave Hilton, Charles Neame.
KENT, WEST.
Cranbrook.—Rev. W. M. S. Marriott, Messrs J. E. King, R. Tooth,
Geo. Hinds, J. E. Wilson.
Gravesend.—W. M. Smith, Esq., late high sheriff, Messrs W. F.
Dobson, T. Collyer, Pinching, W. E. Russell, R. C. Arnold, J.
Armstrong, W. Brown, W. Hubble, T. Mace.
Rochester.—Messrs W. Mauclark, W. Miles, C. Lake.
Maidstone.—Messrs T. Abbott, F. B. Eloy, G. Powell.
Edenbridge.—Messrs W. Searle, sen., J. Holmden, Geo. Arnold.
Sevenoaks.—Messrs J. Selby, G. Turner, E. Crook.
Bromley.—Messrs Hammond, Moysar, and Edgerton.
Dartford.—Messrs W. Allen, J. Solomon, and Slaughter.
Tonbridge.—Rev. G. Woodgate, and others.
Wrotham.—Messrs Leary, Thomas Spencer, and Charlton.
LANCASHIRE, SOUTH.
Liverpool.—Messrs Richard C. Naylor, II., Clever Chapman,
Charles Turner, Lawrence Peel, Thomas Bold.
LEICESTERSHIRE, NORTH.
Leicestershire.—Messrs Perkins, G. Kilby.
Waltham.—Messrs John Clark, F. Vincent.
LEICESTERSHIRE SOUTH.
Market Harborough.—Messrs Edward Fisher, jun., Josh. Perkins.
Hinckley.—Messrs Matthew Oldacres, John Champion, Charles
D. Breton, Thomas Swinnerton, John Brown, Richard Warner,
John P. Cooke, James H. Ward.
LINCOLNSHIRE, NORTH.
Lincoln and Lindsey.—Colonel Sibthorp, M.P., R. A. Christopher,
Esq., M.P., Mr T. Greetham, Mr J. G. Stevenson.
Grimsby.—Mr F. Iles.
Caistor.—Mr Wm. Torr.
Alford.—Mr W. Loft.
LINCOLNSHIRE, SOUTH.
Long Sutton and Holbeach.—Messrs Wm. Skelton, Spencer
Skelton, George Prest.
Sleaford.—Messrs Tinley and Nickolls.
LINCOLNSHIRE, EAST.
East Lincolnshire.—Messrs Fricker, Joseph Rinder, jun.
NORFOLK, EAST.
North Walsham.—John Warnes, Esq.
NORTHAMPTONSHIRE.
Northamptonshire.—Messrs Gray, Rogers, and J. Scriven.
NORTHUMBERLAND.
Northumberland.—Sir Matthew White Ridley, Bart., Messrs
Robert David, John Ayersby, John Robson, Walter Johnson,
Thomas Smith, H. Wilkin.
NOTTINGHAMSHIRE.
North Nottinghamshire.—Messrs John Holmes, John Walker, T.
Hopkinson.
South Nottinghamshire.—Messrs George Storer, W. Chouler,
Richard Milward, W. Champion, J. Parkinson, jun., H. Gilbert.
OXFORDSHIRE.
Banbury.—Messrs S. Lovell, J. Gardner, J. Selby.
RUTLANDSHIRE.
Rutland Branch.—Messrs Thomas Spencer, Christopher Smith,
Samuel Cheetham.
Uppingham Branch.—Messrs Owsley, Edward Wortley.
SHROPSHIRE, NORTH.
Shropshire.—Four delegates.
Oswestry District.—S. Bickerton, Esq.
SHROPSHIRE, SOUTH.
Bridgnorth.—E. W. Powell, Esq., John Stephens, Esq.
SOMERSETSHIRE, WEST.
Somerset.—Messrs Cridland and Bult, John Wood, H. G.
Andrews, R. Hooke, J. Hooke.
Langport and Bridgewater District.—Mr John King, (vice
chairman) and Mr T.B. Morle.
STAFFORDSHIRE, NORTH.
Stafford.—Major Chetwynd, Messrs T. Hartshorne, W. T.
Lockyer, C. Keeling, J. Nickisson, J. Aston.
STAFFORDSHIRE, SOUTH.
Eccleshall Branch.—Rev. V. G. Yonge, Rev. Charles Mainwaring.
SUFFOLK.
East Suffolk.—Rev. Mr Alston, Messrs John Mosely, N.
Barthropp, P. Dykes, W. Bloss.
Ipswich Branch.—C. Lillingston, Esq. Deputy Lieutenant, Messrs
T. Haward, W. F. Schrieber, J. Garnall, Venn, W. Back, W.
Rodwell, J.D. Everett, Morgan, R. C. Perry, Mark Wade, Rev. F.
K. Steward.
Hartismere Branch.—Dr Chevalier, Messrs Samuel Peck and
Deck.
Stradbroke District.—W. L. B. Frener, Esq., Rev. A. Cooper.
West Suffolk.—Messrs King, Vrall, Simpson, Woodward,
George Gayford.
Cosford Hundred.—Messrs C. Kersey, P. Postans.
Bungay Branch.—Two delegates.
SURREY, EAST.
Kingston.—Messrs G. Nightingale and Daniels.
Croydon Branch.—Messrs Cressingham, (chairman,) Rowland,
Raincock, Robinson, Walker, and Gutteridge.
Reigate Branch.—Messrs Peter, Caffyn, Jesse Pym.
Tandridge Hundred Branch.—Messrs Isaac Stavely, Edward
Kelsey.
SURREY, WEST.
West Surrey United Association.—Col. Holme Summer, Rowland
Goldhawk, Esq.
Epsom District.—Messrs Francis Garner and King.
Dorking District.—Messrs Weller and Dewdney.
SUSSEX, EAST.
Sussex.—Messrs W. Rigden, A. Denman, S. H. Bigg, Edward
Wyatt.
East Grinsted.—Messrs George Head, Wm. Turner, John Rose,
John Mills, John Payne.
WARWICKSHIRE, NORTH.
Rugby and Dunchurch Branch.—Messrs H. Townsend, John
Perkins.
Sutton Coldfield.—The Hon. E. S. Jervis, W. M. Jervis, Esq.,
Rev. W. K. B. Bedford, Messrs R. Fowler, R. Fowler, jun.,
Bodington, Sadler, Osborne, Buggins.
Coleshill.—Messrs Cook, Gilbert, H. Thornley, John York, and
Dr Davies.
WARWICKSHIRE, SOUTH.
Warwickshire.—Messrs Edward Greaves, C. M. Caldecott, Luke
Pearman, J. H. Walker, W. W. Bromfield, R. Hemming, S.
Umbers, B. Sedgeley, John Moore, H. Brown.
WILTSHIRE, NORTH.
Messrs G. Brown, W. Ferris, J. A. Williams, R. Strange, J. Wilkes,
E. L. Rumbold, L. Waldron.
WILTSHIRE, SOUTH.
Salisbury Branch.—Messrs Stephen Mills, F. King, George Burtt,
Leonard Maton, B. Pinnegar,—Lush.
WORCESTERSHIRE, WEST.
Worcestershire Branch.—The Hon. and Rev. W. C. Talbot, F.
Woodward, Esq., Richard Gardner.
YORKSHIRE, NORTH RIDING.
Knaresborough.—Mr T. Collins, jun., of Scotton.
Easingwold.—Mr Charles Harland.
YORKSHIRE, EAST RIDING.
East Riding.—Mr John Almack.
Malton.—E. Cayley, Esq.
Holderness.—Messrs Josh. Stickney and G. C. Francis.
Pocklington.— — Cross.
YORKSHIRE, WEST RIDING.
Boroughbridge Branch.—Wm. Josh. Coltman, Esq.
SCOTLAND.
Scottish Protective Association.—Sir J. Drummond, Bart.,
Professor Aytoun, Professor Low, Dr Gardner, Messrs Geo.
Makgill, Jno. Dickson, Jno. Dudgeon, J. Murdoch, J. Shand,
Blackwood, Garland, Hugh Watson, Cheyne, Steuart of
Auchlunkart.
East Lothian.—Sir Jno. Hall, Bart. of Dunglass, Messrs R. Scot
Skirving and Aitchison, of Alderston.
Aberdeenshire.—Dr Garden.
IRELAND.
County Down.—The Marquis of Downshire.
The noble Chairman rose and said—Gentlemen, it will not be
necessary for me upon the present occasion to trespass but a few
moments upon your attention, because I am happy to say that there
are gentlemen much more able to discuss the question upon which
we are met here to-day than the individual who now stands before
you—more able, I say; but there is no man in the United Kingdom
who is more deeply impressed than I am with the conviction that, if
this country is to continue to be great and free, moderate import
duties must be imposed (loud cheers.) Though some persons have
called free trade a "great experiment," and wish us to wait and see
what the result of that "experiment" is to be, I tell them fairly now,
that that experiment has been tried—that it has failed—and that
common sense always said it would fail (great cheering.) But during
the trial of this "great experiment," have they calculated the amount
of hazard which they are incurring? Are they aware of the mass of
landowners and tenant-farmers of England who must be cast away if
this experiment is not immediately put an end to? (loud cheers.) We
are met here to-day to receive deputations from different parts of
the country, and it has been thought advisable to convene this
meeting, because doubts have been expressed in Parliament,
whether distress was universal or not. We are met to-day to hear
from the tenant-farmers from various parts of the country the
prospects of their localities (hear, hear.) Gentlemen, I fear those
prospects are bad indeed. But still I will say before you that which I
stated in Parliament—that I have the greatest confidence in the
good feeling of the people of England (cheers.) I believe that the
tenant-farmers will follow the advice which I have ventured to give
them, and persevere (hear, hear.) They know the justice of their
cause. Let you, all of you, when you return home, tell your
neighbours to persevere; and depend upon it, justice will, sooner or
later, be done to you (loud cheers.) I will not now detain you longer
than to say I hope that the expressions which may be made use of
here to-day will be to show that, ill used as we are, we are still loyal
to our Sovereign, and firmly attached to the constitution of our
country (tremendous cheering.)
Mr T. W. BOOKER, Ex-High-Sheriff of Glamorganshire, of Velindra
House, near Cardiff, was then called upon by the noble chairman,
and amidst great applause stepped forward to propose the first
resolution—"That the difficulty and intolerable distress pervading the
agricultural and other great interests of the country, and the state of
deprivation and suffering to which large masses of the industrial
population are reduced, are, in the opinion of this meeting, fraught
with consequences the most disastrous to the public welfare, and if
not speedily remedied must prove fatal to the maintenance of public
credit, will endanger the public peace, and may even place in peril
the safety of the state."—Mr Booker spoke as follows: My lord duke,
my lords, and gentlemen,—It is, I do most unfeignedly assure you,
with the deepest diffidence, if not with the deepest reluctance, that I
stand before you thus early in the proceedings of this most eventful
day; for, gentlemen, I came here under the sincere hope that I
might be allowed to listen to others instead of myself occupying your
time. But there are times, and this is an occasion, when I feel that it
would ill become any man to shrink from the discharge of a public
duty which those with whom he has an identity of feeling and a
community of interest will and wish should devolve upon him.
Humble, therefore, though my name may be, yet I will, without
further apology, proceed at once to the objects which have called us
together. (Cheers.) At this time of day, and on this occasion, I need
not, I think, enter upon any lengthened argument, nor need I
adduce any elaborate statements of statistical facts, to prove that
the condition of Great Britain and Ireland and her dependencies is,
to say the least, most unsatisfactory. (Hear, hear.) Your own
experience will tell you that. Therefore to save your time, and with a
knowledge of those who will have to follow me, I will assume three
propositions. First of all, I will assume that the agricultural interest is
immeasurably the most important interest of the state. (Hear.)
Secondly, I will assume that that interest is in a state of alarming
and greatly increasing depression. (Hear, hear.) And, thirdly, I will
assume that that depression is occasioned and aggravated by the
adoption and continuance in that altered policy of the country which
now prevails. (Cheers.) I presume that my two first propositions will
be conceded to me everywhere; and as to the third, here at least I
presume we are unanimous, that the difficulties, the dangers, the
distresses, and the disasters that now accompany us are attributable
to that vile, suicidal policy falsely called free trade. (Cheers.) Having
gone thus far, and having arrived at this point, it will not be of much
advantage to you that I should dwell long upon the nature and
extent of the distress which now accompanies you, and now
environs you. That I will leave to others of those intelligent practical
men who, in such multitudinous numbers, have left their homes and
have come here to tell, in this central heart of England, their feelings
upon the distresses and dangers that have overtaken them. But I
will just glance at what is the prevailing symptom of the distress of
the present day. And, strange as it may appear, the prevailing
symptom is cheapness—cheapness of all the necessaries and
conveniences of life—cheapness of the bountiful gifts of Providence,
the productions of the earth—cheapness of the works of man, the
produce of his skill and labour. And how is it that this cheapness,
which augurs plenty and abundance, should not be accompanied
with its usual, nay, its invariable concomitants—ease, enjoyment,
safety, and repose? (Cheers.) There must be something
fundamentally wrong in a state which produces such startling
results. It was the opinion of one whose opinion, and whose
memory too, ought to be an object of veneration with every Free-
trader, as unquestionably they are of respect, from the sterling,
amiable, pains-taking qualities of the man—I allude to the late Mr
Huskisson—it was his opinion, and he delivered it in his place in the
House of Commons so long ago as the year 1815—it was his opinion
that nothing could be more delusive than the proposition that
cheapness in the price of provisions is always a benefit. On the
contrary, cheapness, without a demand for labour, is a symptom of
distress. (Cheers.) The French, he adds, in his day, had cheapness
without capital, and that was a proof in them of progressive decay.
But this all-pervading state of cheapness is so ably glanced at and
set forth in a document which I hold in my hand, and which has
been transmitted to me since my arrival in town, that I cannot
forbear quoting some passages from it. It is the Address of the
Metropolitan Trades' Delegates to their fellow-countrymen, on the
interests and the present position of the labouring classes of the
empire; and if there can be words of solemn warning and import,
they are contained in this most extraordinary document. It
commences:—
"Fellow-Countrymen,—There is not recorded an era in the history of
our country, nor, indeed, in the history of all nations, when the great
subject of the natural and social rights of those who live by means of
their labour was required to be so thoughtfully considered, so clearly
explained, and so zealously and faithfully supported, as the present
era."
It afterwards goes on to treat the question of cheapness thus:—
"We have it announced to us that it is under the operation of
unregulated, stimulated, and universal competition, we are
henceforth to live.
"Cheapness is proclaimed to be the one great and desirable
attainment. But the cheapness that is attained under this system is
not the result of fair and distributory abundance—being mainly
acquired by diminishing the enjoyments, or the consumption, of
those by whose labour productions are derived, and by that
economy of labour by which, in so many instances, the labourer is
cast off altogether from employment, because a cheaper, that is, a
less consuming instrument than his body, is invented and applied.
The labour of the working man thus becomes a superfluous
commodity in the market, so that he must either be an outcast
altogether from society, or else find some way of doing more work
for less of materials of consumption; and even then, if he should
succeed in this course of realising cheapness, he becomes
instrumental in bringing many others of his fellow-labourers down to
the same degraded level to which he is reduced. (Loud cheers.)
"Bad and appalling, however, as is the existing condition of so many
whose only means of supporting themselves and their families is the
exercise of their daily labour, yet we maintain that the prospect
before us is still more dark and gloomy. We declare to you our
conviction that a far greater degree of suffering and of destitution
impends over the labouring class and their families, both of this and
of all other nations, unless the falseness of the free or competitive
system be thoroughly penetrated, clearly exposed, and a course of
general commerce, very different from that emanating from the free
system, be entered upon." (Great cheers.) In this manner do these
practical men, who are practically groaning under the evils of this
altered system, dispose of the question of cheapness. The men
whose signatures are appended to that document, have done me
the honour also of communicating with me since I have been in
town, and of stating to me what their intentions and objects are.
They write me on the 4th of May inst. that "The delegates have a
desire to collect all the statistics in their power showing the decline
in the employment of the people, and also showing the gradual
falling-off of wages since the introduction of free-trade measures to
their respective trades; and also the condition of those trades which
have not been directly interfered with by foreign imports, but which
the delegates have reason to believe are indirectly affected by the
displaced hands, from other industrial branches, continually forcing
themselves into the above-mentioned trades—this is the reason they
have appealed to all who are friends to native industry for
assistance." But, gentlemen, it is said that free trade has not yet had
fair play. Most fortunately I am indebted to the kindness and
courtesy of a member of parliament, a personal friend of my own,
the invaluable member for Falmouth, Mr Gwyn, for the returns of
trade and navigation up to the close of last month, which only
appeared and were placed in my hands last night. I have gone
through these documents with all the business habits that I am
capable of; and I come to this conclusion and result, the truth of
which I defy any Free-trader to controvert. (Cheers.) The flourishing
state of the cotton trade is boasted of. Why, these documents prove
to you that the export of cotton goods has increased 10 per cent,
but the consumption of cotton altogether has decreased 20 per cent.
(Loud cheers.) And what does this show? That there is a decrease in
the consumption of cotton of 30 per cent. What! free trade not had
fair play! Why, our colonies have had free trade for the last twenty
years. For the last ten years they have had the blessing of free and
unrestricted trade, and let me appeal to any colonist, what is the
universal language which defies even contradiction—We are ruined!
(loud cheers.) Our own British possessions get their supplies cheaper
from the United States than they can from Great Britain or our North
American colonies. They expend the property of their own colonies,
and of ours too, which they get there, in fostering the trade of our
rivals to the destruction and exclusion of their own. Free trade not
had fair play! Why, what have been its effects in Ireland? (hear,
hear.) In the year 1844 or 1845, there were of acres cultivated in
wheat in Ireland, 1,059,620; but in 1847, the blessed year that
followed the consummation of free trade, the number was reduced
to 743,871, and in 1848 it was still further reduced to 565,746, thus
showing a decrease in three years of the palmy days of free trade of
no less than 500,000 acres of wheat, equal to the production of
2,100,000 quarters, and in value, at what ought to be the price of
wheat, upwards of six millions sterling. (Shouts of "hear, hear.") This
shows with a vengeance that capital is flowing from the banks of the
Shannon to the shores of the Vistula (hear, hear.) Free trade not had
fair play! What will you, farmers, your wives and daughters, say to
this? In the year 1833, the export of salt butter from Ireland was
25,000 tons, in value L.3,000,000 sterling, and it would take 260,000
cows to produce that quantity of butter. Now, let the Free-traders tell
us what has been the export of salt butter from Ireland during the
last year (hear, hear.) Ireland has broken up her old pastures, and
has sown wheat upon them; and yet with all that forced and ruinous
cultivation, the foreigner beats her out-and-out. But it is only a
waste of time to go through the extent and the nature of the
distress which afflicts you. I will no longer dilate upon it. I will leave
its effects upon England to those admirable men whose public spirit
and whose private wrongs have brought them here. And I will at
once ask, what is to be the remedy? You will answer me with one
acclaim, There can be but one, and that is a return to the policy of
protection to native industry (cheers.) And how is this remedy to be
attained? Why, by a cordial union of all classes whose labour has
been invaded, and the produce of whose skill, enterprise, and
industry has been excluded by that vile policy which has supplanted
us in our own markets. I presume, and I say it with all respect and
deep humility, that you can have no remaining hope from the
present parliament (cheers), nor from the present advisers of the
Crown (tremendous cheering.) But we have a constitutional
sovereign, who well knows that her own peace and happiness
depend upon the welfare and prosperity of her people. She well
knows that upon that peace and prosperity, not only her own
happiness, but the security of her throne (cheers,) and the stability
of the monarchy that she administers, all alike depend (cheers.) Let
us carry to the foot of the throne the wishes of her faithful people.
Let us tell her of the distress and difficulties that are overtaking the
industrious cultivators of the soil of the empire which she benignly
governs. (Loud cries of "hear.") Let us tell her of the dangers and
disasters that environ the hard-working, industrious occupiers of the
territorial domains of the ancient nobility and gentry of her land
(hear, hear.) Let us tell her, as the noble duke said, that, although
oppressed, we are still faithful—still uncompromising—still
unswerving—still unseduceable—still loyal and true to her; and I will
stake my life on it, that she will be compassionate and true to us
(hear, hear.) The humble individual who now addresses you is no
proud aristocrat—he is no lordly possessor of wide-spread territorial
domains; but he has obtained his fortune by the active pursuits of
commercial industry (hear, hear.) He affords daily employment to
hundreds, and thousands are dependent for their daily bread on his
care and success (hear, hear.) I hope, therefore, that I speak with a
due sense of the responsibility of my words and actions; and I desire
—and, with God's blessing, I shall use every energy and talent that
my Maker has endowed me with (loud cheers)—I desire, and with
God's help, I shall endeavour to transmit to my children's children
unimpaired those laws and liberties, those customs and institutions,
which have afforded me protection during my own career of
successful toil (cheers.) You will take one word of counsel from me.
You, the owners and industrious occupiers of the soil, will, I hope,
from this vast assembly hurl back with proud defiance that gross
threat, that, if success should attend your exertions for a restoration
of protection, the foundations of property would be shaken to their
centre (hear, hear.) Such is the language used by Free-traders in
fustian, in words as well as in merchandise (hear, hear.) Ay, forsooth,
by the apostle of peace, who would have the manly quarrels of
nations, as well as of individuals, settled by palaver and humbug,
instead of musketry and gunpowder (great cheering.) Hurl back, I
say, that defiance, and let your answer reach the ears of all who
dare to obstruct the exercise of free discussion, and the results of
free discussion in this hitherto free and prosperous land (hear.) But,
in the struggle that must of necessity ensue before we can obtain
the gracious accession of our beloved Sovereign to the prayers of
her people, it may and will happen that our friends who, amidst
treachery and desertion unparalleled (hear, hear,) had stood firm and
faithful to their principles and professions, may be inconvenienced,
and that their seats in the legislature may be jeopardised by the
miscellaneous onslaught of our ministerial and jacobinical opponents
(hear, hear.) But this must not, this shall not, be; for these men must
be protected at the hustings (hear, hear.) When I look at this vast,
this magnificent assemblage—when I consider whom and what it
represents—I cannot for a moment doubt that there are, in the
ranks of the protectionists of England, Ireland, Wales, and Scotland,
a thousand men who will put down their hundred pounds a-piece to
form a fund against all aggressors (hear, hear.) For myself, I shall at
once avow that I will be one, either of a thousand to put down my
hundred pounds (hear, hear,) or, if need be, I will be one of a
hundred to put down my thousand pounds (loud cheers,) for this
national, this necessary object. And then having done our duty, and
having among our hereditary legislators a Richmond (cheers,) a
Stanhope (hear,) a Stanley (cheers,) an Eglinton, a Talbot, a
Downshire, a Malmesbury, a Beaufort, and a host of others, who will
forgive me if I now fail to name them; and a Disraeli (great cheering
followed the mention of Mr Disraeli's name,) a Granby (hear, hear,) a
Manners (hear, hear,) a Beresford, a Stuart, a Newdegate, and many
more such whom we will send to aid them in the House of
Commons, let us commit our cause, the cause of peace and plenty,
the cause of truth and justice (cheers,) the sacred cause of
protection to native industry and capital (hear, hear)—let us
commend that cause to our Sovereign, to our country, and to our
God (loud cheers.) My lords and gentlemen, I must apologise for the
undue length at which I have addressed you. I thank you most
cordially for the kindness and the enthusiasm with which you have
listened to me, and I now beg to propose the resolution with which I
have the honour to be intrusted.
The honourable gentleman sat down amidst the most deafening
cheers.
Mr W. CHOULER, South Muskham, Newark, Notts, in rising to second
the resolution, said he should not waste their time by offering any
apologies for his unfitness to address them upon that occasion. He
had come forward to state facts, and he should at once proceed to
discharge that duty to the best of his ability. He should first of all
advert to the state of the labourers in his own immediate
neighbourhood. He could state that the wages of those labourers
had of late been reduced nominally from 12s. to 10s., and in some
parts of the county to 9s. a-week; while the real reduction was much
greater, because, in consequence of the depressed condition of their
employers, they had been deprived of that piece-work by which they
had formerly earned a further sum of 1s. or 2s. a-week. Since he
had come to London he had received a statement of the condition of
the labourers in a part of Leicestershire which adjoined South
Nottinghamshire, and from that statement he found that during the
winter there had been many unemployed labourers in that district;
and that latterly, even at the approach of the spring-time, eight of
those labourers had been going about begging. They had not asked,
however, for alms, but for employment, by which they could have
obtained an honest livelihood for themselves and their families.
(Hear, hear.) Now, he appealed to every one whom he was
addressing, whether a cultivator of the soil could be placed in a
more heartrending situation than when he found himself unable to
afford employment to an honest and industrious, but necessitous
labourer? But, feeling dissatisfied with things at home, he had taken
some trouble to ascertain how the labourers are situated in other
districts with which he had no immediate connexion. As a matter of
course, he had thought that the place in which he might expect to
find perfection was the estate of Sir Robert Peel. (Loud cries of
"hear, hear," jeers, and laughter.) He had read the document issued
some time since by Sir Robert Peel to his tenantry, and through his
tenantry to the country at large; and from the wording of that
document he had been led to suppose that in the parish of
Kingsbury, the property of Sir Robert Peel, the labourers were fully
employed, well housed, and well fed. But he would tell them what
he had seen there only a few days ago. The parish of Kingsbury was
an extensive one, and the farms there were large, for that part of
the country, as they varied from 300 to 400 acres. But instead of the
labourers in Kingsbury being lodged in comfortable cottages, he
found scarcely any labourers' cottages upon the estate. There were
no small holdings, no cottage allotments in the parish; and he had
been told that the labourers employed in it resided at a distance of
two or three miles from the place. The fact was, that for some years
a system had been carried on in that parish for reducing the number
of its agricultural labourers, (hear, hear,) and removing the poor off
the property. He confessed he only wondered that the "Times
Commissioner" had not been down there (hear, and laughter,) to tell
the tenantry how much of the physical force of the labourer was lost
by living so far from his work. But he had found worse than that. He
had found that English labourers were being gradually displaced by
low-priced Irish labourers. He had found that the tenants of Sir
Robert Peel had been employing during the winter, is well as during
the summer, six or eight Irish labourers each, to whom they paid
little or no money wages. (Cries of "shame.") Now he should not
have thought much about that if he had found that the Irish
labourers were prospering, as they are British subjects; but he had
seen them in a very wretched condition, to which the English
labourers also were being rapidly reduced. The Irish there have no
house to live in, no bed to lie on, or fire to go to, but lay on straw in
an outhouse; therefore this system has this tendency,—to depress
the English labourer to the Irish or Continental level, without
elevating the other. He would pass, however, from the parish of
Kingsbury to a district represented by another lion of the day. (A
laugh.) They would recollect that Mr C. Villiers, the member for
Wolverhampton, had stated at the commencement of the session
that there had been L.91,000,000 a-year saved to the country by the
fall in prices which had followed the adoption of the free-trade
policy. Now it had occurred to him that the constituents of Mr Villiers
must have obtained a pretty good share of that sum. But he had
found that in Wolverhampton the poor-rates had been gradually
increasing during the last eight or ten years. It appeared that, during
the twelve months ending in March 1842, the poor-rates in the union
of Wolverhampton had not amounted to half the sum which they
had reached during the twelve months ending in March 1850. It
further appeared that in the year ending March 25, 1849, they had
amounted to only L.10,007, while in the year ending March 25,
1850, they had amounted to L.11,625. He had mentioned these
facts for the purpose of showing that the people of Wolverhampton
had derived no advantage from the supposed saving of L.91,000,000
a-year effected by the adoption of a free-trade policy. But he said,
without fear of contradiction, that no such saving had been made.
He admitted that that sum had been lost to one class in this country
(hear, hear,) but he denied that it had been gained by any other.
(Cheers and laughter.) Lord John Russell said last Friday night week,
that if Mr Henley brought forward a direct motion in favour of
protection, he should be prepared to show that the great mass of
the people were in possession of as great comforts as they ever had
been. Now this was three months after the country had been said to
have been the gainer of L.91,000,000 a-year, and yet all that Lord
John Russell could say was that the people were in "as good" a
position as ever they were. He would admit, if necessary, that this
sum had been lost to one class, but it had not been gained by
another. He should not be so much dissatisfied if the farmers had
lost it, if only some other class had gained it. But the farmers had
lost it and no one in this country had gained it. (Cheers.) Two-thirds
of the people of this country were engaged in agricultural pursuits,
and could any policy, he would ask, be more suicidal than to deprive
them of L.91,000,000 a-year, without conferring any benefit on the
remaining one-third of the population? (Hear, hear.) He had no
hesitation in saying that the agriculturists, as a body, had never been
in a worse position than that in which they were at present placed.
He felt convinced that, if the existing prices for agricultural produce
were to continue much longer, the tenant-farmers would be wholly
unable to afford full employment to labourers; great efforts had
been made last winter to employ the labourers; and when
parliament met we were told, because we had employed them, that
there was no distress. But if the class of able-bodied labourers were
offered no alternative but to perish from destitution or to enter the
workhouse, he had no hesitation in saying that this country would
soon be reduced to a state which he should be most sorry to
witness. Already the agricultural labourers talked of combinations;
and although the farmers might be able to stem the torrent by
affording them employment until the termination of the harvest, he
could not help anticipating the most serious perils after that period.
The labourers did not blame the farmers for their condition, for they
were well aware that the farmers had not the means for affording
them employment; and under those circumstances, could it be
expected that the farmers would mount their horses for the purpose
of opposing the just demands of their humbler fellow-countrymen?
(Hear, hear.) If a man was willing and able to work in this country,
he had a right to have the means of living in comfort in it. (Hear,
hear.) Mr Cobden had said what he would do if a system of
protection were re-established, and what would then become of the
landlords. But I will say openly and publicly, that if the landlords will
stick to us, we will stick to them. (Loud and enthusiastic cheers.) But
I will go further than that—I have not yet quite finished the subject.
We own nine-tenths of the horses of the kingdom, and we have the
men to ride upon them. (Vociferous cheering.) And we go further
still: we will support the Crown as well as the landlords. (Cheers.)
Her Majesty need not fear, if she turn her back upon the towns, that
she will not be supported. Protected ourselves, we will protect her
against all assailants. (Loud cheers.) Mr Chouler then proceeded to
say that, in his opinion, it matters not what prices were, provided all
interests were placed upon the same footing. But if one interest
were reduced below another, if employment were lessened whilst
taxation was kept up, if more money left the country than came into
it, the result must be beggary. (Cries of "Hear," and "Now for the
rents.") He would come to that directly; but first stop a bit.
(Laughter.) He had not quite done yet, (cheers;) but would mention
to them the case of a tenant-farmer who had applied to him for
advice as to what he should do under his present circumstances.
This gentleman occupied three farms, had a large family, and
employed a good deal of capital. The ages of his children varied
from 24 to 9. He stated that his wheat wanted hoeing, and that he
had no money to do it with; that he intended to have placed his
family on the farms, but that if he were to do so they could not live.
What could he do with them? Some of them were too old to be put
to trades, and then, if he were to take out his capital, all his dead
stock would go almost for nothing. He (Mr Chouler) knew he could
not do anything for him. The man was a good cultivator, in good
circumstances, and that was the case of hundreds and thousands of
tenant-farmers. (Hear, hear.) Rent had been alluded to by some one
just now. He had always regarded rent as a private bargain between
two individuals. He did not come there to find fault with either his
own landlord or the landlord class generally, because, as a class, he
had seen them act as the very best friends of the people. But he did
think that in this particular movement, latterly, they had left it almost
entirely not only to the tenants to do the work—that he should not
care anything about; but to defray all the expenses. (Cheers and
laughter.) Now, if the tenant-farmer could not cultivate his land
properly, his labourers and himself would get worse off, and he
would be in a worse position to pay his rent, his tithes, and his
taxes; and if no tithes and rent were paid, how are the clergy and
aristocracy to pay their taxes and servants? (Cheers.) With regard to
taxes, he would ask, was there a class of men in any other country
who produced an article that was taxed from 75 to 100 per cent,
before they could use it themselves? for that was the case with the
malt-tax in this country at the present moment. (Cheers.) Sir Robert
Peel had told them that the food of the labouring man should be
free from taxation; but what was the fact? Why, he held in his hand
a list of no less than 15 articles, all of which were eatables or
drinkables, and necessaries to the poor man, which had to pay taxes
at this moment. They were—butter, cheese, cocoa, coffee, corn and
meal, eggs, fruits, hams, rice, spices, spirits, sugar, refined ditto,
molasses, and tea; and they produced a revenue to the country of
L.13,677,795. And yet this "wiseacre" had said that the food of the
working man should be free from taxation. In addition to that, there
were the articles of tobacco and snuff, which produced upwards of
L.4,000,000 more. (Hear.) And was not tobacco a necessity of the
working man? (Hear, hear.) Well, that brought the amount up to
L.18,000,000 sterling, or more than one-third of the whole of the
general taxation of the country, raised upon articles of food.
(Laughter and cheers.) With regard to the malt tax, he thought that
no impost was more unjust, because there was not a great quantity
of malt liquor consumed by the higher classes, the greater portion
being consumed by the working classes; and, with the exception of
one or two cyder counties, malt liquor, in one shape or other, was
the universal beverage of the labourers. But beer must be taxed,
forsooth! That was not the food of the people! (Hear.) There is only
one other point (continued Mr Chouler) upon which I will make an
observation, and that is with reference to the great "Exhibition" of
1851. (Oh, oh! groans and hisses.) I have heard of many curious
things in my lifetime; but there is one thing which I have always
regarded as visionary, or as never having had an existence—but it
has actually been realised in this 19th century, and in this great city
—ay, in this year of grace 1850—a "mare's" (mayor's) nest has been
discovered. (Roars of laughter.) Yes; and in this "mayor's nest" was
"the Prince," and what does "the Prince" say? Now I beg that it may
be distinctly understood that I mean no disrespect to my Sovereign
or the Prince; but I came here to speak the truth, and I have spoken
it fearlessly, and the truth I will know before I go home. The Prince
says that, when you get the productions of all countries and nations
before you, you have only to choose which is the cheapest and the
best. Well, if you are to do that, is it not to show you that you have
the opportunity of buying them? (Hear, hear.) A little umbrage has
been taken at this exhibition as savouring somewhat of free-trade,
and the royal commissioners have told us that they do not intend
that the articles shall be sold, but that they shall be merely shown.
But do you believe that the foreigner will bring his produce across
the Channel or the Atlantic, and take it back again without receiving
English money for it? Now, I want to know who does speak the
truth? (Cries of "the Prince.") I suppose the Prince does. (Shouts of
"no.") Well, well, have it as you like. (Roars of laughter.) I am come
here as a delegate from the part of the country in which I reside. I
came to seek the truth, and I will know it and declare it. I ask, is the
foreign corn that will be imported into England in the year 1851, to
come in and be looked at without being sold? (Loud cheers.) What
will the foreigner say? Why, he will say "I care nothing about your
'looks,' give me your money" (Cheers and laughter.) That is what he
will say. It is my duty then to ascertain whether or not it is intended
still to encourage the sending out of the country money which it
would be better to circulate at home. And I hope I am not exceeding
my functions as a delegate in asking that question. Now you have
heard my opinions upon this subject, and the concluding remarks I
shall make are these: that without an alteration this country will be
so shaken—after harvest, mind you, as there will be a good deal of
work until then, not before—that I am perfectly confident it will be
totally impossible to preserve the public peace. (Loud cheers.) I am
not surprised at untruths coming from the royal commission,
considering whom that commission is composed of, when I find Peel
and Cobden amongst them. (Groans and hisses.) There is one name
amongst them, however, which I am always in the habit of speaking
of with respect and honour, and that is the name of Lord Stanley.
(Cheers.) How far he will come out from among these royal
commissioners without harm (bravo, loud cheers, and laughter,)
from such a den of—you must supply the rest—I do not know, but I
have confidence in the man. (Loud cheers, and great laughter.)
The resolution was put from the chair, and carried unanimously.
Mr EDWARD BALL, Burwell, Cambridgeshire, then moved the next
resolution:—"That the indifference with which the just complaints of
the people have been received by the House of Commons, its
disinclination to adopt any measures for removing or alleviating the
existing distress; and the want of sympathy it has exhibited for the
sufferings of the people, have produced a widely-diffused feeling of
disappointment, discontent, and distrust, which is fast undermining
their reliance on the justice and wisdom of Parliament, the best
security for loyalty to the Throne, and for the maintenance of the
invaluable institutions of the country." The attendance of the noble
duke this day, observed Mr Ball, imposes a fresh debt of gratitude
upon us, and realises the hope we entertain, that whenever there is
a grand field day he will be found in his right position—at the head
of the troops. As our great commander, it is obligatory upon us that
we should observe his orders, and one of those orders is, that we
should express ourselves temperately and with moderation. (Hear,
hear.) But I am sure that, from his experience of the field of conflict,
he knows that sometimes the ardour and zeal of the British troops
carry them somewhat beyond the exact line marked out by their
leader and chief. (Cheers.) And if we should be found upon this
occasion to advance a little beyond that strict line of propriety which
he has chalked out for us, his kindness will excuse it when he knows
that it is out of the fulness of our hearts, and the deep distress in
which we are plunged, that we are assembled to-day to make our
representations and complaints. (Cheers.) Coming, then, to the
resolution which I have to propose, I ask is the allegation contained
in it true? For if the thing stated in it be not true, it is useless for us
to use it as an argument in justification of our assembling here to-
day. Is it true? (Cries of "Yes; it is true.") Is it true that the House of
Commons has shown great disregard to our petitions? (Cheers.) Is it
true that it has rushed on heedless of the entreaties of the whole
body of agriculturists, and passed a measure which it was elected
for the very end and purpose of preventing? This (proceeded Mr
Ball) constituted the bitterness of their grief, that when Lord John
Russell's commercial measures of 1841 were defeated, a new
parliament was called, and the voice of the nation proclaimed
through that parliament against free trade—that the great mass of
the constituencies rallied around the banner of protection—that they
raised such a number of men to represent them in the House of
Commons, that Lord J. Russell was obliged to throw up the reins of
government into the hands of Sir Robert Peel, who took the
leadership of the House of Commons with a good majority of 100,
who were thought truly and honourably to represent the agricultural
interest, and ready to protect their cause. (Cheers.) Then he wanted
to know if the complaint in the resolution was not just when they
saw that very house, which was congregated for the express
purpose of maintaining protection, unhesitatingly strike that
protection down, defeat all their objects, blast all their hopes, and
prove untrue and unfaithful to the great constituencies of the
empire. (Loud cheers.) I say, exclaimed Mr Ball, that we will never
cease to represent that it was not by fair and legitimate means that
we were beaten (cheers;) but that it was by the unfair, the foul play,
the treacherous betrayal of those who had headed us to lead us on
to victory, but who conducted the enemy into the camp, introduced
the foe into the citadel, and destroyed all our hopes and prospects.
(Loud cheers.) That being true, what is the language of the Free-
trader upon the occasion? He sees a consequence that he never
anticipated. He sees the result which we pointed out, and which he
disbelieved. He finds that prices are as ruinous as we stated that
they would be, and that free trade is as great a hindrance to the
welfare of agriculture as we always reported that it would be. And
now how does he shelter himself? Instead of coming forward, and
honestly saying we have failed—it was only an experiment, which
was forced upon us, and having made an error we will endeavour to
correct it—he says that it is an exceptional case; that it is not the
legitimate consequence, but that there are some particular
circumstances which make the principles of free trade press with
unusual severity just now. (Hear, and oh.) Now, look at the
reasoning of this. If the foreigner, when he had no hope of such a
market being opened to him, could for the last two years send in a
supply of nearly twenty-two million quarters of various descriptions
of corn, and if he could do that out of his surplus produce, what will
he do now that he has the market entirely open to him—when he
has got our capital to improve his cultivation, and when he knows
that he may produce and send an unlimited quantity into our
markets? (Hear.) I want to know how it is that, with an express
declaration of the principles of the people upon the question of free
trade, the landlords in the House of Lords and in the House of
Commons, contrary to their own creed and in opposition to their
own judgment, swerved from all that they had promised us, and
threw up to those who were more impassioned and boisterous than
themselves all that protection which they were bound in honour and
in interest to uphold? (Loud cheers.) I feel that it is painful to speak
of the landlords of this kingdom in the presence of so many of that
aristocracy who shed a lustre upon their order, and whose presence
here shows us how much they respond to our own principles.
(Cheers.) We can never forget that those laurels which adorn the
brow of the noble duke who presides over us were won in the most
terrible and hard-fought encounters that ever brought glory, honour,
and renown to the British arms, and that the noble duke has, from
the period that he turned his sword into a ploughshare, ever stood
true to the best interests of agriculture—(loud cheers)—has ever
stood true to the declarations which he has made; and under all
changes, and in the midst of the vapourings of his opponents, has
been steadfast, untarnished, and unsullied, and now comes before
us with renewed glory and increased claims upon our gratitude and
support. (Loud cheers.) We cannot forget that the noble lord on his
right—the Earl Stanhope—(great cheering)—whom it has been my
privilege for five-and-twenty years to follow in the paths of
philanthropy—who has come to the evening of a long and a useful
life, in which he has shown sympathy to the poor, and has had the
best interests of his fellow-men at heart—that he comes here, too,
for the purpose of giving his powerful support to the great principles
to which he and we are alike devoted. (Loud cheers.) They had also
several other noble and honourable gentlemen present. They all
knew the undaunted courage with which the Marquis of Downshire
had fought for their right. They knew that the gentlemen around him
were noble exceptions to that great defalcation which had been
committed by so large a portion of the aristocracy. (Cheers.)
Therefore, he (Mr Ball) could not discharge what he considered to be
his duty now, without pointing them out as exceptions to the
statement he was about to make—that they had fallen, not by
Cobden's—that they had fallen, not by the League's tricks—that they
had fallen, not by the treachery of Peel; but because their landlords
—the aristocracy—those who should have upheld them—had
swerved from their duty in the houses of Parliament. (Cheers.) We
had the power—we had the majority—we had the voice of the
country, not loud, but strong and firm, and ready to manifest itself
when the moment for action came; but they were faint-hearted,
they failed in the hour of need, and sacrificed us to the discordant
elements of demagogueism and free-tradeism. (Uproarious
cheering.) Moreover, they have contrived to take the full tale from
the poverty and the debilitated circumstances of a struggling
tenantry. (Loud cheers.) Let me put this simple case to you. I take
the free-trade landlord, and I take the tenant-farmer. They are in
partnership, are engaged in the same pursuit, and have a joint
interest in the same property. A is the landlord, B the tenant-farmer.
A comes to B and says, "We must make an experiment upon this
land. We must introduce certain fresh modes of cultivation. We must
change our plan; and if we do so-and-so you will farm better, my
rent will be more secure, and we shall be altogether in more
favourable circumstances than before." B, the tenant, says, "No, it is
too frightful an experiment. No, it may involve me in ruin. No, you
risk nothing—I risk all." (Great cheering.) But A is the richer man—A
has the greater power, and he insists upon the experiment being
made, in spite of the tears and protestations of the tenant. In the
legislature A assents that the experiment shall be made. Thus he
sweeps away and brings down to ruin the tenant who, in his
wretchedness, looks up to the landlord for relief; and I do say that,
according to the immutable principles of justice, and on the ground
of what is due from man to man, the landlord, who is a party to the
passing of free-trade measures, is bound to sustain and uphold his
tenant, and reimburse his losses. (Vehement cheers.) I want to
know, also, if I have L.5000, L.10,000, or L.20,000, placed in the
funds, and a similar sum invested in the land, both of them being
sustained and supported by the law—I want to know if the land be
to pay the interest of the national debt, whether it is fair and just to
take away the income out of which the interest of the national debt
is to be paid, and what right or justice there is in demanding the full
payment of the national debt? (Loud cheers.) If the fundholder has
looked on and encouraged the movement which was made to bring
us to ruin, I want to know with what propriety or consistency he can
ask to gather out of our ruined means the wealth which, under other
circumstances, we would gladly and cheerfully pay him? (Cheers.)
But we are told that our landlords cannot now reverse this policy—
that they have gone too far to recede—and Cobden, in that
celebrated speech of his, which he made at the close of last year in
Leeds, said "Only let the agriculturist come forward and put on one
shilling in the shape of corn duty, and I will create such a tumult as
shall shake the kingdom to its centre." (Laughter.) Most deliberately
and dispassionately my answer to that is—The sooner the better!
(Tremendous cheering; the whole of the vast assemblage rising to
their feet, and waving their hat and hands.) I say that we have a
conscience, that we have a superintending Providence, that we have
laws violated, that we have all these things which will sustain and
give endurance to us in any conflict that may approach; and that,
therefore, we may laugh at all threatenings, and set them at
defiance. (Loud cheering.) But what have the tenant-farmers to fear
at the approach of discord? Can you be worse off? (No, no.) Can any
alteration damage you? (Renewed cries of "no no.") All is lost!
Persevere in your free-trade laws, and there is no concealing the fact
that, as a class, we are swept away. (Hear.) Persevere in those laws,
our homes will be taken from us. Persevere in those laws, our wives
will be without protection. Persevere in those laws, our children will
become paupers. (Cheers.) Will you then tell me, when laws have
been enacted that reduce me to that position, that I, a broken-
hearted man, passing into poverty and my family degraded, that I
shall fear the threats of a demagogue? (Much cheering.) My answer
for the whole body of the tenantry of the country is this—that we
are disposed to risk all, brave all, dare all! (vociferous cheering,
again and again repeated;) and that we are prepared, come what
will, and cost what it may, at the hour of our country's peril, for our
homes, our wives, and our families, to take those terrible steps
which are the most frightful for a good and peaceable man to
imagine, but which necessity and unjust treatment hurry us on and
bring us to the contemplation of. (Vehement plaudits.) The most
abominable part of it is this, however. If it had been a calamity
brought on in the Providence of God—by the failure of the seasons,
or by something which was above legislative control, we would have
humbly bowed to it. But here comes the scourge—we fell through
the cowardice and faint-heartedness of him whom we considered to
be the greatest of modern statesmen; and when the history of the
age that is passing has been recorded, it will tell us that at the same
period there was in Italy a man (Count Rossi) who had been
appointed minister of the Pope; that he was the witness of a rising
tumult and a coming desolation; and that on the very morning of his
death he was told not to go to the Senate, for if he did so there
would be danger attending him. His reply was, "I have taken office—
and when I did that, I took not only its honours and emoluments,
but its duties and its dangers." He went to the Senate, and perished
upon the steps of the Forum. But our statesman (Sir Robert Peel)
saw the approach of the storm, quailed at the tempest, bowed down
to the lowering cloud, dishonoured the country, brought infamy upon
his own name, and poverty upon the people. (Great cheering.)
Mr J. ALLIN WILLIAMS, of Wiltshire, seconded the resolution. He
stood before them that day as a Wiltshire farmer, second to none in
the kingdom in his loyalty and attachment to the throne and his love
of the constitution of old England. (Cheers.) Moreover, he stood
before them deputed by the farmers of the county of Wilts, for the
purpose of protesting against the treatment to which the occupiers
of the soil of Great Britain, as a class, had been subjected by the
measures of her Majesty's Ministers and by the House of Commons.
(Cheers.) He wished he could think that those measures and their
consequences had been properly considered and contemplated by
their framers before they were brought forward. Despite the
remonstrances of the defenders of the agricultural interest in the
House of Commons, and of the noble duke in the chair, and of other
noblemen in the Upper House of the Legislature, her Majesty's
Ministers persisted in those measures which must ultimately reduce
the tenantry of England to beggary. (Hear, hear.) An individual,
whom he would not name, as his name appeared to grate upon the
ears of every honest farmer in this country—(cheers)—but whom it
was impossible to forget, as he had laid down maxims which they
felt obliged to take up and consider—a few years ago that individual
laid down, as a rule, that the British farmer could not grow wheat in
this kingdom under 56s. per quarter. (Hear, hear.) And upon the faith
of that statement many of the men that he saw before him, himself
included, had entered into agreements with their landlords for the
purpose of occupying their estates for a certain period of years.
(Hear, hear.) He himself had taken a lease for 14 years. What, then,
must be the condition of the farmers of those estates when they
were obliged to sell wheat at 36s. per quarter? The consequence
was, that all, or the greater part of those who were similarly situated
with himself, must be ruined. Upon the same figures was also based
the Tithe Commutation Act; and by that act, which, as they too well
knew, was ruled by a septennial clause, last year, when they were
selling their wheat at the price of two guineas per quarter, they were
compelled to pay after the rate of 54s. 10d. per quarter as the tithe
of their produce; and this year, when they were selling their wheat
at from 36s. to 40s. per quarter, they had to pay upon an average of
53s. (Hear, hear.) It was on that account that he came there to
proclaim that her Majesty's Ministers had done the farmers a great
piece of injustice, and that they had in fact emptied the pockets of
the British farmers by their legislation. If there had been a necessity
for the late Free-trade measures, (and he denied that there was any
such necessity,) he contended that every portion of the community
ought to have been made to bear a fair share of the burdens which
had been placed upon the agriculturists. But what was the fact? He
maintained that the industrious classes, the producers, alone were
made to feel the burden, and that property and capital were wholly
exempt. (Hear, hear.) The Free-traders, when proposing their ruinous
measures, appear to have made a grand discovery, and assert, that
we have no right to tax the food of the people. But did it ever enter
their brains that on the wheat produced by the British farmer he
paid a large tax in the shape of the superior wages paid to the
labourers as compared with those of the labourers of the foreigner,
to meet the taxes that are imposed on them upon the necessaries of
life? That in fact the proportion of labour in a quarter of wheat
(which he would assert to be two-thirds) was taxed to the enormous
extent of 33 per cent? (Hear, hear, hear.) Again, was not the wheat
produced by the British farmer taxed by the poor rates, the highway
rates, &c.? and the heavy rents which he paid as compared with the
foreign farmer, (such rents as were not heard of in any other country
in the world,) was it not on account of the heavy taxes the landlords
had to pay? If these things never entered the brains of her Majesty's
Ministers, they were no men of business. (Hear, hear.) If they did
enter into their brains, then their conduct was most knavish, most
scandalous; for thereby they compelled the farmers of England to
compete on most unequal terms with the foreigner. (Hear, hear.) The
aristocracy of this country, he regretted to say, had not as a body
done their duty in this matter. (Hear, hear.) Had the farmers of
England had the aristocracy and the clergy of the country with them,
they might easily have resisted the iniquitous measures of the Free-
traders, and they would not have been in their present deplorable
condition. (Cheers.) But now let them look for a remedy. Let them
from that day call forth those men who had hitherto been blind and
apathetic as regarded their own best interests, as well as those of
their own immediate dependents. Let them call upon the landed
gentry and the clergy throughout the country to do their duty. (Hear,
hear.) He thought he might say with confidence, if they responded to
that call, that the agricultural interest had nothing to fear. If nothing
else would rouse the aristocracy of the country to a proper attention
to their vital interests, as well as those of their common country,
surely the insolent language of Mr Cobden at Leeds was enough to
rouse them from their lethargy. But if they still refused to do their
duty, he would call upon them, in the language of Milton, to
"Awake! arise! or be for ever fallen."
(Cheers.) He knew that time was pressing on, and that he must be
brief. He would therefore conclude by again protesting against the
treatment they had received, and most heartily seconding the
resolution which had been proposed to them by Mr Ball. But he
could not resume his seat before he had conjured them to send
Whig principles to the winds. (Laughter and cheers.) His belief was,
that Dr Samuel Johnson never made so happy a hit in his definition
of those principles, as when he said that the devil was the first Whig.
(Great laughter and cheers.)
The resolution was then put and unanimously carried.
Professor AYTOUN, of Edinburgh then came forward, amidst loud
cheering, to propose the following resolution:—"That this meeting
attributes the depression and distress of the agricultural, colonial,
shipping, and other interests to the rash and impolitic changes in the
laws which had long regulated the importation of foreign
productions; that it is of opinion that those laws were based on the
most just principles, and dictated by the soundest policy; that, under
their salutary influence, the British nation had attained an
unexampled state of prosperity, and a proud pre-eminence in the
scale of nations; and that if their object and spirit in fostering and
protecting native industry be finally abandoned, many of the most
important interests of the state will be sacrificed, and the national
prosperity and greatness be ruinously impaired." The learned
Professor proceeded as follows:—Gentlemen, I have been desired,
perhaps, rather than requested, on the part of the Scottish
Protective Association, (hear, hear,) to attend this meeting, and to
move one of the resolutions. I most sincerely wish that the task had
been confided to abler hands than mine; but all of us have a distinct
duty to perform; and those of my countrymen who act with me feel
that, on such an occasion as this, it would be wrong and faint-
hearted if Scotland, which is so deeply interested in the grand
question of protection to native industry, were to hang back, and
refuse to come forward to testify to you and to the tenantry of
England that our zeal in this cause is as great, our feeling as
decided, our determination as strong as your own. (Cheers.) I
cannot offer to you the testimony of a practical agriculturist, but,
perhaps, I may be allowed to say that I do not consider this is a
meeting entirely of agriculturists. (Hear, hear.) Every man in this
nation, from the lowest to the highest, has, I conceive, a distinct
stake in this question. Every man, whatever be his occupation or his
calling, is entitled to come forward here and declare his opinion
upon those measures which have been thrust on the nation by an
act of perfidy and treachery, to find a parallel for which we shall
search the pages of history in vain. (Hear, hear.) I do not exaggerate
our case when I say that Scotland is, if possible, more interested
than England in the maintenance or the restoration of protection to
native industry. Far later in point of time were our fields broken up,
our moors reclaimed, our morasses drained; and the prosperity of
Scotland, great as it has been, can hardly be reckoned as of older
date than the last seventy years. Glasgow, the largest city of
Scotland, the second city of the United Kingdom, rose to its present
high wealth and distinction by its colonial connexion within a
comparatively recent period. Our counties and our towns are alike
interested in this matter. The "transition state" of suffering which our
opponents now affect to have foreseen as the inevitable result of
their measures—though they took especial care to conceal that
revelation from every human eye—is more than beginning to make
itself felt in the latter: in the former, it is evident and undenied, and
already, I am sorry to say, in our remote Highland districts the work
of desolation has begun. They may call it peace if they please; it is
not peace, alas! it is solitude. (Hear, hear.) Now, there are certain
things you have imported from Scotland for which perhaps you may
not thank us very much, and one of those things is a certain race
called Political Economists. (Hear, hear, and laughter.) I do not,
however, wish to include among the number the father of political
economy, Adam Smith, now in his grave three-quarters of a century,
who wrote at a time and under circumstances very different from
those in which we are at present placed. I observe that Mr Cobden is
going about the country with the works, as he says, of Adam Smith
in his hands, and favouring the public with his comments on those
works; but I hope those comments will be taken by the public, as I
take them, at their true value—estimating the quality of the text at a
different ratio from the perverted interpretations of the expounder.
There is another Scottish Political Economist, Mr M'Culloch, who has
written a great deal on the subject of the corn trade, and who has
been hitherto, during his long life, a decided enemy to all restrictive
duties; but who, I believe, is now discovering at the last hour, that
he has been going too fast in his views, and that the total
withdrawal of protection is not likely to do all the good which he had
at one time anticipated from it. Then, there is another gentleman,
who is an ornament to the present House of Commons—the
illustrious Mr Macgregor, (roars of laughter,) the gifted and infallible
seer, who won the suffrages of a benighted city by telling its electors
from the hustings that the nation was to increase in wealth, under
the free-trade system, at the rate of precisely L.2,000,000 a-week.
(Hear, hear, and laughter.) That was to be the national gain; a gain
in which we were all to participate the moment the corn laws were
swept away. Mr Macgregor also told the people of Glasgow that in
this matter he was the political tutor of Sir R. Peel, (hear, hear, and
laughter;) that he, the two million a-week man, was the individual
who laid down that grand plan under which we are all at present
suffering. If that be true, all I shall remark is this, that surely never
did any pupil select so singular a master. Under these circumstances,
I must admit that, however we may be entitled to appear here as a
deputation, one gift which we have sent you from Scotland, in the
shape of political economists, is a gift for which you cannot be very
thankful. This is, I may add, an age in which men have been more
befooled by figures than by anything else which we can mention.
(Hear) Half a century ago, when any extraordinary account appeared
in the newspapers, it used to be said that it must be true because it
was to be found in print. Now, that delusion seems to have passed
away; the charm of infallibility is broken, and people do not at
present suppose that the press has got any particular exemption
from error. But a delusion quite as great, and even more baneful,
still prevails with respect to figures. There are men seated in their
closets, with blue-books before them, casting up long columns of
accounts, and making out statements which they call statistics,
which are to form the invariable rules by which mankind is to be
governed, and by which the commerce of this country is to be
regulated; and it is by putting their noxious dogmas into effect that
this country has of late been exposed to so much suffering. The
system is older even than the days of Adam Smith; for about a
century ago there went forth from Edinburgh a man of the name of
John Law, the founder of the famous Mississippi scheme—a scheme
for enriching men by foreign trade and for conferring on them
fortunes at once, while it did away with native industry. History has
its cycles, and we have again arrived at a period when quackery and
imposture have usurped the place of sound common-sense, of wise
policy, and I fear not to add, of truthful and Christian legislation.
(Great cheering.) I know well that it is not my part to dwell long
upon topics with which others are better acquainted, but if you will
allow me, I shall make a few observations with regard to the present
state of agricultural industry in Scotland. We have of late years been
much flattered by commendations of our system of farming in that
country. Whenever any of the farmers of England were supposed not
to be quite up to the mark, it used to be said by Sir Robert Peel and
his friends, that those farmers had only to imitate the example of
the men of the same class in the Lothians. But in the beginning of
this year, after a fair trial had been given to the so-called experiment
of free trade, the farmers of the Lothians came forward, and testified
by the leading members of their body that they were losing under
the present system, and that their industry, skill, energy, and
frugality were employed in vain so long as that incubus weighed
upon them. (Hear, hear.) What followed? Why, the note was
immediately changed, and it was said that those men were not
farming high enough! That discovery was made by a gentleman who
now appears to be Sir Robert Peel's great authority upon the subject
—a certain Mr Caird. (Hear, hear, and laughter.) Now that gentleman,
although a farmer, does not happen to be able to say that he ever
made anything himself by farming. But he is acquainted with
another individual, who is the factor on an estate of a very liberal
landlord, who lets him have land for a merely nominal rent. That
individual is at present in possession of a fine peat-moss,
exceedingly well fitted for growing potatoes; and, as there has been
less rot this year in his potatoes than in those of the greater portion
of other farmers, he had derived from them a considerable profit.
That is the farmer whose example is now recommended by Mr Caird
as the grand panacea for all the evils under which the agricultural
class is suffering. (Hear, hear.) So you see, gentlemen, in what you
are to put your trust—peat-moss and potatoes! (Great laughter.)
These are the twin resources with which you are to meet unlimited
importations of grain! Pity, for the sake of Ireland, where both
articles are abundant, that the discovery was made so late! I believe,
indeed I know, you have something of the same sort here. Mr Mechi
—(hear, hear, and laughter)—a gentleman whose razors are of
undeniable excellence—has been attempting to show the farmers of
England how to shave close (a laugh;) and the unclean spirit of free
trade, finding no other place of refuge, has at last flown into the
herd of Mr Huxtable's swine. (Immense cheering.) But I must say a
few words with regard to the poorer districts—with regard to the
Highlands of Scotland. The misery prevailing in many of those
districts, more especially in the west and in the islands, did not
proceed solely from the repeal of the corn laws; for it was also in a
great measure owing to the noxious tariffs of Sir R. Peel, which
admitted provisions duty-free into this country. It appears—indeed I
believe it is an uncontradicted fact—that the British fleet is now
victualled by foreign product. (Cries of "Shame.") I hold in my hand
a letter from a banker in the town of Oban in Argyleshire, stating
that emigration is now taking place to a very considerable extent
there, that most of those who can scrape a few pounds together are
taking their passage to America, and that shortly the landlords will
be left with no class of people on their lands save the reckless, the
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Visual Basic In Easy Steps Covers Visual Basic 2015 Fourth Mcgrath
PPTX
UNIT I.pptx
PPT
Visual basic 6.0
PDF
Introduction To Visual Basic 2015 Mark Maslach
PDF
Visual Basic in easy steps Covers Visual Basic 2015 Fourth Edition Mcgrath
PPTX
Object Oriented Programming I
PPTX
01 Database Management (re-uploaded)
PDF
Ppt on visual basics
Visual Basic In Easy Steps Covers Visual Basic 2015 Fourth Mcgrath
UNIT I.pptx
Visual basic 6.0
Introduction To Visual Basic 2015 Mark Maslach
Visual Basic in easy steps Covers Visual Basic 2015 Fourth Edition Mcgrath
Object Oriented Programming I
01 Database Management (re-uploaded)
Ppt on visual basics

Similar to Microsoft Visual Basic Programs To Accompany Programming Logic And Design 3rd Edition Jo Ann Smith (20)

PPTX
COM 211 PRESENTATION.pptx
PPTX
Presentation on visual basic 6 (vb6)
PPTX
INTRODUCTION-TO-VB (1).pptx introduction
PPTX
INTRODUCTION-TO-VB (2)-PROJECT POWERPOINT.pptx
PPT
Visual programming
PPT
Vb introduction.
PDF
Book HH- vb6 preview
PPT
LESSON 1- VISUAL BASIC PROGRAMMING.ppt
PPT
Programming Notes
PPT
Ms vb
PPT
Advanced Programming Language(Visual basics) .ppt
PPT
visualbasic.ppt
PDF
Programming Visual Basic 2008 Tim Patrick
PDF
Visual Basic 6.0
PPTX
Vb6.0 intro
PPT
Chapter 01
PPT
Chapter 01: Intro to VB2010 Programming
PDF
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
PDF
visual basic 2005 programmer certification
DOCX
Introduction to programming per
COM 211 PRESENTATION.pptx
Presentation on visual basic 6 (vb6)
INTRODUCTION-TO-VB (1).pptx introduction
INTRODUCTION-TO-VB (2)-PROJECT POWERPOINT.pptx
Visual programming
Vb introduction.
Book HH- vb6 preview
LESSON 1- VISUAL BASIC PROGRAMMING.ppt
Programming Notes
Ms vb
Advanced Programming Language(Visual basics) .ppt
visualbasic.ppt
Programming Visual Basic 2008 Tim Patrick
Visual Basic 6.0
Vb6.0 intro
Chapter 01
Chapter 01: Intro to VB2010 Programming
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
visual basic 2005 programmer certification
Introduction to programming per
Ad

Recently uploaded (20)

PDF
Insiders guide to clinical Medicine.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
master seminar digital applications in india
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Pharma ospi slides which help in ospi learning
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Insiders guide to clinical Medicine.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Final Presentation General Medicine 03-08-2024.pptx
master seminar digital applications in india
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPH.pptx obstetrics and gynecology in nursing
O7-L3 Supply Chain Operations - ICLT Program
Pharma ospi slides which help in ospi learning
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
VCE English Exam - Section C Student Revision Booklet
2.FourierTransform-ShortQuestionswithAnswers.pdf
Cell Structure & Organelles in detailed.
Microbial disease of the cardiovascular and lymphatic systems
TR - Agricultural Crops Production NC III.pdf
01-Introduction-to-Information-Management.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

Microsoft Visual Basic Programs To Accompany Programming Logic And Design 3rd Edition Jo Ann Smith

  • 1. Microsoft Visual Basic Programs To Accompany Programming Logic And Design 3rd Edition Jo Ann Smith download https://ebookbell.com/product/microsoft-visual-basic-programs-to- accompany-programming-logic-and-design-3rd-edition-jo-ann- smith-2516288 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Microsoft Visual Basic 2005 Express Edition Build A Program Now Patrice Pelland https://ebookbell.com/product/microsoft-visual-basic-2005-express- edition-build-a-program-now-patrice-pelland-928390 Microsoft Visual Basic 2008 Express Edition Build A Program Now Papcdr Pelland https://ebookbell.com/product/microsoft-visual-basic-2008-express- edition-build-a-program-now-papcdr-pelland-55141900 Microsoft Visual Basic 2010 For Windows Web And Office Applications Complete Sam 2010 Compatible Products 1st Edition Shelly https://ebookbell.com/product/microsoft-visual-basic-2010-for-windows- web-and-office-applications-complete-sam-2010-compatible-products-1st- edition-shelly-55132322 Microsoft Visual Basic 2010 Developers Handbook 1st Edition Klaus Lffelmann https://ebookbell.com/product/microsoft-visual-basic-2010-developers- handbook-1st-edition-klaus-lffelmann-55132362
  • 3. Microsoft Visual Basic 2010 For Windows Applications Introductory Available Titles Skills Assessment Manager Sam Office 2010 1st Edition Shelly https://ebookbell.com/product/microsoft-visual-basic-2010-for-windows- applications-introductory-available-titles-skills-assessment-manager- sam-office-2010-1st-edition-shelly-55132370 Microsoft Visual Basic 2008 Express Programming For The Absolute Beginner 1st Edition Ford https://ebookbell.com/product/microsoft-visual-basic-2008-express- programming-for-the-absolute-beginner-1st-edition-ford-55132374 Microsoft Visual Basic Net Programming For The Absolute Beginner First Edition Harbour https://ebookbell.com/product/microsoft-visual-basic-net-programming- for-the-absolute-beginner-first-edition-harbour-55139964 Microsoft Visual Basic 2012 Reloaded 5th Edition Zak Diane https://ebookbell.com/product/microsoft-visual- basic-2012-reloaded-5th-edition-zak-diane-55141894 Microsoft Visual Basic 2010 Step By Step Michael Halvorson https://ebookbell.com/product/microsoft-visual-basic-2010-step-by- step-michael-halvorson-2310058
  • 6. MI CROSO F T ® VISUAL BASIC® PROGRAMS TO ACCOMPANY PROGRAMMING LOGIC AND DESIGN BY JO ANN SMITH Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States S I X T H E D I T I O N
  • 7. © 2011 Course Technology, Cengage Learning ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored, or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher. Library of Congress Control Number: 2010928662 ISBN-13: 978-0-538-74625-0 ISBN-10: 0-538-74625-4 Course Technology 20 Channel Center Street Boston, MA 02210 USA Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. For your lifelong learning solutions, visit course.cengage.com Visit our corporate Web site at cengage.com. Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or regis- tered trademarks of their respective manufacturers and sellers. Any fictional data related to persons or companies or URLs used through- out this book is intended for instructional purposes only. At the time this book was printed, any such data was fictional and not belonging to any real persons or companies. Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice. The programs in this book are for instructional purposes only. They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes. The author and the publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs. Microsoft® Visual Basic® Programs to Accompany Programming Logic and Design, Sixth Edition Jo Ann Smith Executive Editor: Marie Lee Acquisitions Editor: Amy Jollymore Senior Product Manager: Alyssa Pratt Development Editor: Mary Pat Shaffer Content Project Manager: Jennifer Feltri Art Director: Marissa Falco Proofreader: Suzanne Ciccone Indexer: Sharon Hilgenberg Compositor: Integra For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be e-mailed to permissionrequest@cengage.com Printed in the United States of America 1 2 3 4 5 6 7 14 13 12 11 10
  • 8. Brief Contents Preface . . . . . . . . . . . . . . . . . xi CHAPTER 1 An Introduction to Visual Basic and the Visual Basic Programming Environment Programming Environment . . . . 1 1 CHAPTER 2 Variables, Constants, Operators, and Writing Programs Using Sequential Statements . . . . . . . . . . . . . . . . 11 CHAPTER 3 Writing Structured Visual Basic Programs. . . 31 CHAPTER 4 Writing Programs that Make Decisions . . . . 46 CHAPTER 5 Writing Programs Using Loops . . . . . . . 74 CHAPTER 6 Using Arrays in Visual Basic Programs . . . . 96 CHAPTER 7 File Handling and Applications . . . . . . 112 CHAPTER 8 Advanced Array Techniques . . . . . . . . 127 CHAPTER 9 Advanced Modularization Techniques . . . . 144 CHAPTER 10 Creating a Graphical User Interface (GUI) Using the Visual Studio Integrated Development Environment (IDE) . . . . . . 169 Index . . . . . . . . . . . . . . . . . 193 iii
  • 9. Contents Preface . . . . . . . . . . . . . . . . . xi CHAPTER 1 An Introduction to Visual Basic and the Visual Basic Programming Environment Programming Environment . . . . 1 1 The Visual Basic Programming Language . . . . . . . . . . 2 Three Types of Visual Basic Programs . . . . . . . . . . . . 2 An Introduction to Object-Oriented Terminology . . . . . . . . 3 The Structure of a Visual Basic Program . . . . . . . . . . . 5 The Visual Basic Development Cycle. . . . . . . . . . . . . 6 Writing Visual Basic Source Code . . . . . . . . . . . . . 7 Compiling a Visual Basic Program . . . . . . . . . . . . . 7 Executing a Visual Basic Program . . . . . . . . . . . . . 9 Exercise 1-1: Understanding How to Compile and Execute Visual Basic Programs . . . . . . . . . . .10 Lab 1.1: Compiling and Executing a Visual Basic Program . . . . . . . . . . . . . . . . . . . . .10 CHAPTER 2 Variables, Constants, Operators, and Writing Programs Using Sequential Statements . . . . . . . . . . . . . . . . 11 Variables . . . . . . . . . . . . . . . . . . . . . . . . .12 Variable Names . . . . . . . . . . . . . . . . . . . . .12 Visual Basic Data Types . . . . . . . . . . . . . . . . . .13 Exercise 2-1: Using Visual Basic Variables, Data Types, and Keywords . . . . . . . . . . . . . . .14 Declaring and Initializing Variables. . . . . . . . . . . . . .14 Exercise 2-2: Declaring and Initializing Visual Basic Variables. . . . . . . . . . . . . . . . . . . . .15 Lab 2.1: Declaring and Initializing Visual Basic Variables. . .16 Constants . . . . . . . . . . . . . . . . . . . . . . . . .17 Unnamed Constants . . . . . . . . . . . . . . . . . . .17 Named Constants . . . . . . . . . . . . . . . . . . . .17 iv
  • 10. Exercise 2-3: Declaring and Initializing Visual Basic Constants . . . . . . . . . . . . . . . . . . . .18 Lab 2.2: Declaring and Initializing Visual Basic Constants . . . . . . . . . . . . . . . . . . . .18 Arithmetic and Assignment Operators . . . . . . . . . . . .19 Arithmetic Operators . . . . . . . . . . . . . . . . . . .19 Assignment Operators and the Assignment Statement . . . .20 Precedence and Associativity . . . . . . . . . . . . . . .21 Exercise 2-4: Understanding Operator Precedence and Associativity . . . . . . . . . . . . . . . . . . . .22 Lab 2.3: Arithmetic and Assignment Operators . . . . . . .23 Sequential Statements, Comments, and Interactive Input Statements . . . . . . . . . . . . . . . . . . . . . . .24 Exercise 2-5: Understanding Sequential Statements . . . . .28 Lab 2.4: Using Sequential Statements in a Visual Basic Program . . . . . . . . . . . . . . . . . . . . .29 CHAPTER 3 Writing Structured Visual Basic Programs. . . 31 Using Flowcharts and Pseudocode to Write a Visual Basic Program . . . . . . . . . . . . . . . . . . . . . .32 Lab 3.1: Using Flowcharts and Pseudocode to Write a Visual Basic Program . . . . . . . . . . . . .36 Writing a Modular Program in Visual Basic . . . . . . . . . .38 Lab 3.2: Writing a Modular Program in Visual Basic . . . . .45 CHAPTER 4 Writing Programs that Make Decisions . . . . 46 Boolean Operators . . . . . . . . . . . . . . . . . . . . .47 Comparison Operators . . . . . . . . . . . . . . . . . .47 Logical Operators . . . . . . . . . . . . . . . . . . . .48 Comparison and Logical Operator Precedence and Associativity . . . . . . . . . . . . . . . . . . . .49 Comparing Strings . . . . . . . . . . . . . . . . . . . . .52 Decision Statements . . . . . . . . . . . . . . . . . . . .53 The If Statement . . . . . . . . . . . . . . . . . . . .54 Exercise 4-1: Understanding If Statements . . . . . . . .55 Lab 4.1: Using If Statements . . . . . . . . . . . . . .56 The If Then Else Statement. . . . . . . . . . . . . .57 Exercise 4-2: Understanding If Then Else Statements . .58 Lab 4.2: Using If Then Else Statements . . . . . . . .60 Nested If Statements . . . . . . . . . . . . . . . . . .60 Exercise 4-3: Understanding Nested If Statements . . . .62 Lab 4.3: Using Nested If Statements . . . . . . . . . . .63 v C O N T E N T S
  • 11. The Select Case Statement . . . . . . . . . . . . . .64 Exercise 4-4: Using a Select Case Statement. . . . . . . . . . . 67 Lab 4.4: Using a Select Case Statement . . . . . . . .67 Using Decision Statements to Make Multiple Comparisons . . . . . . . . . . . . . . . . . . . . . .68 Using AND Logic . . . . . . . . . . . . . . . . . . . . .69 Using OR Logic . . . . . . . . . . . . . . . . . . . . .69 Exercise 4-5: Making Multiple Comparisons in Decision Statements . . . . . . . . . . . . . . . . .70 Lab 4.5: Making Multiple Comparisons in Decision Statements . . . . . . . . . . . . . . . . .72 CHAPTER 5 Writing Programs Using Loops . . . . . . . 74 Writing a Do While Loop in Visual Basic . . . . . . . . . .75 Exercise 5-1: Using a Do While Loop . . . . . . . . . .76 Using a Counter to Control a Loop . . . . . . . . . . . . .77 Exercise 5-2: Using a Counter-Controlled Do While Loop . .78 Lab 5.1: Using a Counter-Controlled Do While Loop . . . .78 Using a Sentinel Value to Control a Loop . . . . . . . . . . .79 Exercise 5-3: Using a Sentinel Value to Control a Do While Loop . . . . . . . . . . . . . . . . . . .81 Lab 5.2: Using a Sentinel Value to Control a Do While Loop . . . . . . . . . . . . . . . . . . .81 Writing a For Loop in Visual Basic . . . . . . . . . . . . .82 Exercise 5-4: Using a For Loop . . . . . . . . . . . . . .84 Lab 5.3: Using a For Loop . . . . . . . . . . . . . . . .84 Writing a Do Until Loop in Visual Basic . . . . . . . . . .85 Exercise 5-5: Using a Do Until Loop . . . . . . . . . .86 Lab 5.4: Using a Do Until Loop. . . . . . . . . . . . .86 Nesting Loops. . . . . . . . . . . . . . . . . . . . . . .87 Exercise 5-6: Nesting Loops . . . . . . . . . . . . . . .88 Lab 5.5: Nesting Loops . . . . . . . . . . . . . . . . .88 Accumulating Totals in a Loop . . . . . . . . . . . . . . .89 Exercise 5-7: Accumulating Totals in a Loop . . . . . . . .91 Lab 5.6: Accumulating Totals in a Loop . . . . . . . . . .92 Using a Loop to Validate Input . . . . . . . . . . . . . . .93 Exercise 5-8: Validating User Input . . . . . . . . . . . .94 Lab 5.7: Validating User Input . . . . . . . . . . . . . . .95 CHAPTER 6 Using Arrays in Visual Basic Programs . . . . 96 Array Basics . . . . . . . . . . . . . . . . . . . . . . .97 Declaring Arrays . . . . . . . . . . . . . . . . . . . . .97 Initializing Arrays . . . . . . . . . . . . . . . . . . . .98 vi C O N T E N T S
  • 12. Accessing Array Elements . . . . . . . . . . . . . . . .99 Staying Within the Bounds of an Array . . . . . . . . . . .99 Using Constants with Arrays . . . . . . . . . . . . . . 100 Exercise 6-1: Array Basics . . . . . . . . . . . . . . . 101 Lab 6.1: Using Arrays . . . . . . . . . . . . . . . . . 102 Searching an Array for an Exact Match . . . . . . . . . . 102 Exercise 6-2: Searching an Array for an Exact Match . . . 105 Lab 6.2: Searching an Array for an Exact Match . . . . . 106 Parallel Arrays. . . . . . . . . . . . . . . . . . . . . . 107 Exercise 6-3: Parallel Arrays . . . . . . . . . . . . . . 110 Lab 6.3: Parallel Arrays . . . . . . . . . . . . . . . . 111 CHAPTER 7 File Handling and Applications . . . . . . 112 File Handling . . . . . . . . . . . . . . . . . . . . . . 113 Opening a File for Reading . . . . . . . . . . . . . . . 113 Reading Data from an Input File . . . . . . . . . . . . . 114 Reading Data Using a Loop and EOF . . . . . . . . . . . 114 Opening a File for Writing . . . . . . . . . . . . . . . . 115 Writing Data to an Output File . . . . . . . . . . . . . . 115 Exercise 7-1: Opening Files and Performing File Input . . . 117 Lab 7.1: Using an Input File . . . . . . . . . . . . . . . 118 Understanding Sequential Files and Control Break Logic . . . 119 Exercise 7-2: Accumulating Totals in Single-Level Control Break Programs . . . . . . . . . . . . . . . 124 Lab 7.2: Accumulating Totals in Single-Level Control Break Programs . . . . . . . . . . . . . . . 125 CHAPTER 8 Advanced Array Techniques . . . . . . . . 127 Sorting Data . . . . . . . . . . . . . . . . . . . . . . 128 Swapping Data Values . . . . . . . . . . . . . . . . . . 129 Exercise 8-1: Swapping Values . . . . . . . . . . . . . 129 Lab 8.1: Swapping Values . . . . . . . . . . . . . . . 130 Using a Bubble Sort . . . . . . . . . . . . . . . . . . . 130 The Main() Procedure . . . . . . . . . . . . . . . . 134 The fillArray() Procedure . . . . . . . . . . . . . 135 The sortArray() Procedure . . . . . . . . . . . . . 136 The displayArray() Procedure . . . . . . . . . . . 137 Exercise 8-2: Using a Bubble Sort . . . . . . . . . . . . 137 Lab 8.2: Using a Bubble Sort . . . . . . . . . . . . . . 138 Using Multidimensional Arrays . . . . . . . . . . . . . . 139 Exercise 8-3: Using Multidimensional Arrays . . . . . . . 142 Lab 8.3: Using Multidimensional Arrays . . . . . . . . . 142 vii C O N T E N T S
  • 13. CHAPTER 9 Advanced Modularization Techniques . . . . 144 Writing Procedures with No Parameters . . . . . . . . . . 145 Exercise 9-1: Writing Procedures with No Parameters . . . 147 Lab 9.1: Writing Procedures with No Parameters . . . . . 148 Writing Procedures that Require a Single Parameter . . . . 148 Exercise 9-2: Writing Procedures that Require a Single Parameter . . . . . . . . . . . . . . . . . . 151 Lab 9.2: Writing Procedures that Require a Single Parameter . . . . . . . . . . . . . . . . . . . . . . 152 Writing Procedures that Require Multiple Parameters . . . . 152 Exercise 9-3: Writing Procedures that Require Multiple Parameters . . . . . . . . . . . . . . . . . 154 Lab 9.3: Writing Procedures that Require Multiple Parameters . . . . . . . . . . . . . . . . . 155 Writing Functions that Return a Value . . . . . . . . . . . 156 Exercise 9-4: Writing Functions that Return a Value . . . . 158 Lab 9.4: Writing Functions that Return a Value . . . . . . 159 Passing an Array and an Array Element to a Procedure or Function . . . . . . . . . . . . . . . . . . . . . . 160 Exercise 9-5: Passing Arrays to Procedures and Functions . . . . . . . . . . . . . . . . . . . . 163 Lab 9.5: Passing Arrays to Procedures and Functions . . . 164 Using Visual Basic’s Built-In Functions . . . . . . . . . . . 165 Exercise 9-6: Using Visual Basic’s Built-In Functions . . . . 167 Lab 9.6: Using Visual Basic’s Built-In Functions . . . . . . 167 CHAPTER 10 Creating a Graphical User Interface (GUI) Using the Visual Studio Integrated Development Environment (IDE) . . . . . . 169 Graphical User Interface Programs . . . . . . . . . . . . 170 The Visual Studio Integrated Development Environment . . . 170 Components of a Visual Basic Solution. . . . . . . . . . . 172 The Solution Folder . . . . . . . . . . . . . . . . . . 172 The Designer Window . . . . . . . . . . . . . . . . . 173 The Code Window . . . . . . . . . . . . . . . . . . . 174 Design-Time and Run-Time Operating Modes . . . . . . . . 175 Creating a Visual Basic IDE Program. . . . . . . . . . . . 176 Designing the Form for the Doubler Program . . . . . . . 177 Writing the Code for the Doubler Program . . . . . . . . 180 Exercise 10-1: Elements of a GUI in Microsoft Visual Studio. . . . . . . . . . . . . . . . . . . . . 181 viii C O N T E N T S
  • 14. Lab 10.1: Creating a Visual Basic GUI Program in Microsoft Visual Studio . . . . . . . . . . . . . . . 182 A Programmer-Defined Class . . . . . . . . . . . . . . . 182 Creating a Programmer-Defined Class . . . . . . . . . . 183 Adding Properties to a Class . . . . . . . . . . . . . . 185 Adding Methods to a Class . . . . . . . . . . . . . . . 186 Exercise 10-2: Creating a Class in Visual Basic . . . . . . 189 Lab 10.2: Creating a Class in Visual Basic . . . . . . . . 190 Index . . . . . . . . . . . . . . . . . 193 ix C O N T E N T S
  • 15. Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
  • 16. Preface Microsoft® Visual Basic® Programs to Accompany Programming Logic and Design, Sixth Edition (also known as, VB PAL) is designed to provide students with an opportunity to write Visual Basic programs as part of an Introductory Programming Logic course. It is written to be a companion text to the student’s primary text, Programming Logic and Design, Sixth Edition, by Joyce Farrell. This textbook assumes no programming language experience and provides the beginning programmer with a guide to writing structured programs and simple object-oriented programs using introductory elements of the popular Visual Basic programming language. It is not intended to be a text- book for a course in Visual Basic programming. The writing is non- technical and emphasizes good programming practices. The examples do not assume mathematical background beyond high school math. Additionally, the examples illustrate one or two major points; they do not contain so many features that students become lost following irrelevant and extraneous details. The examples in VB PAL, Sixth Edition are often examples presented in the primary textbook, Programming Logic and Design, Sixth Edition. The following table shows the correlation between topics in the two books. VB PAL, Sixth Edition Programming Logic and Design, Sixth Edition Chapter 1: An Introduction to Visual Basic and the Visual Basic Programming Environment Chapter 1: An Overview of Computers and Logic Chapter 2: Variables, Constants, Operators, and Writing Programs Using Sequential Statements Chapter 2: Working with Data, Creating Modules, and Designing High-Quality Programs Chapter 3: Understanding Structure Chapter 3: Writing Structured Visual Basic Programs Chapter 2: Working with Data, Creating Modules, and Designing High-Quality Programs Chapter 3: Understanding Structure (continues) xi
  • 17. VB PAL, Sixth Edition Programming Logic and Design, Sixth Edition Chapter 4: Writing Programs that Make Decisions Chapter 4: Making Decisions Chapter 5: Writing Programs Using Loops Chapter 5: Looping Chapter 6: Using Arrays in Visual Basic Programs Chapter 6: Arrays Chapter 7: File Handling and Applications Chapter 7: File Handling and Applications Chapter 8: Advanced Array Techniques Chapter 8: Advanced Array Concepts, Indexed Files, and Linked Lists Chapter 9: Advanced Modularization Techniques Chapter 9: Advanced Modularization Techniques Chapter 10: Creating a Graphical User Interface (GUI) Using the Visual Studio Integrated Development Environment (IDE) Chapter 10: Object-Oriented Programming Chapter 11: More Object-Oriented Programming Concepts Chapter 12: Event Driven GUI Programming, Multithreading, and Animation Organization and Coverage Microsoft®Visual Basic®Programs to Accompany Programming Logic and Design, Sixth Edition provides students with a review of the programming concepts they are introduced to in their primary textbook. It also shows them how to use Visual Basic to transform their program logic and design into working programs. The structure of a Visual Basic program, how to compile and run a Visual Basic console program, and introductory object-oriented concepts are introduced in Chapter 1. Chapter 2 discusses Visual Basic’s data types, variables, constants, arithmetic and assignment operators, and using sequential statements to write a complete Visual Basic program. In Chapter 3, students learn how to transform pseudocode and flowcharts into Visual Basic programs. Chapters 4 and 5 introduce students to writing Visual Basic programs that make decisions and programs that use looping constructs. Students learn to use Visual Basic to develop more sophisticated programs that include using arrays, control breaks, and file input and output in Chapters 6 and 7. In Chapter 8, students learn about sorting data items in an array and (continued) xii P R E F A C E
  • 18. using multidimensional arrays. Passing parameters to procedures is introduced in Chapter 9. Lastly, in Chapter 10, students learn about the Visual Studio Integrated Development Environment (IDE), and gain some experience in creating a Graphical User Interface (GUI) and writing event-driven programs. Students also learn to write programs that include programmer-defined classes. This book combines text explanation of concepts and syntax along with pseudocode and actual Visual Basic code examples to provide students with the knowledge they need to implement their logic and program designs using the Visual Basic programming language. This book is written in a modular format and provides paper-and-pencil exercises as well as lab exercises after each major topic is introduced. The exercises provide students with experience in reading and writing Visual Basic code as well as modifying and debugging existing code. In the labs, students are asked to complete partially pre-written Visual Basic programs. Using partially pre-written programs allows students to focus on individual concepts rather than an entire program. The labs also allow students to see their programs execute. VB PAL, Sixth Edition is unique because: It is written and designed to correspond to the topics in the • primary textbook, Programming Language and Design, Sixth Edition. The examples are everyday examples; no special knowledge of • mathematics, accounting, or other disciplines is assumed. It introduces students to introductory elements of the Visual Basic • programming language rather than overwhelming beginning programmers with more detail than they are prepared to use or understand. Text explanations are interspersed with pseudocode from the • primary book, thus reinforcing the importance of programming logic. Complex programs are built through the use of complete • examples. Students see how an application is built from start to finish instead of studying only segments of programs. Features of the Text Every chapter in this book includes the following features. These features are both conducive to learning in the classroom and enable students to learn the material at their own pace. xiii P R E FA C E
  • 19. Objectives: Each chapter begins with a list of objectives so the • student knows the topics that will be presented in the chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid. Figures and illustrations: This book has plenty of visuals, which • provide the reader with a more complete learning experience, rather than one that involves simply studying text. Notes: These notes provide additional information—for example, a • common error to watch out for. Exercises: Each section of each chapter includes meaningful • paper- and-pencil exercises that allow students to practice the skills and concepts they are learning in the section. Labs: Each section of each chapter includes meaningful lab work • that allows students to write and execute programs that implement their logic and program design. Acknowledgments I would like to thank all of the people who helped to make this book possible, especially Mary Pat Shaffer, Developmental Editor, whose expertise and attention to detail have made this a better textbook. She also provided encouragement, patience, humor, and flexibility when I needed it. Thanks also to Alyssa Pratt, Senior Product Manager, and Amy Jollymore, Acquisitions Editor, for their help and encouragement. I am grateful to Jennifer Feltri, Content Project Manager, and Vidya Muralidharan, of Integra Software Services, for overseeing the production of the printed book. It is a pleasure to work with so many fine people who are dedicated to producing quality instructional materials. I am dedicating this book to my son, Tim and his son, my grandson, William. Both add great dimension and joy to my life. Jo Ann Smith xiv P R E F A C E
  • 20. Read This Before You Begin To the User Data Files To complete most of the lab exercises, you will need data files that have been created for this book. Your instructor will provide the data files. You also can obtain the files electronically from the Course Technology Web site by connecting to www.course.com, and then searching for this book title. You can use a computer in your school lab or your own computer to complete the lab exercises in this book. Solutions Solutions to the Exercises and Labs are provided to instructors on the Course Technology Web site at www.course.com. The solutions are password protected. Using Your Own Computer To use your own computer to complete the material in this textbook, you will need the following: Computer with a 1.6 GHz or faster processor • Operating system: • Windows XP (x86) with Service Pack 3 - all editions except • Starter Edition Windows Vista (x86 & x64) with Service Pack 2 - all editions • except Starter Edition Windows 7 (x86 and x64) • xv
  • 21. Windows Server 2003 (x86 & x64) with Service Pack 2 - Users • will need to install MSXML6 if not already present Windows Server 2003 R2 (x86 and x64) • Windows Server 2008 (x86 and x64) with Service Pack 2 • Windows Server 2008 R2 (x64) • Architectures: 32-Bit (x86) and 64-Bit (x64) (WOW) • RAM: • 1024 MB • 1.5 GB if running in a Virtual Machine • 3 GB of available hard-disk space • 5400 RPM hard drive • DirectX 9-capable video card that runs at 1024 x 768 or higher • display resolution DVD-ROM Drive • This book was written using Microsoft Windows Vista and Quality Assurance tested using Microsoft Windows Vista and Windows 7. Updating Your PATH Environment Variable Setting the PATH environment variable allows you to use the Visual Basic compiler (vbc) and execute your programs without having to specify the full path for the command. To set the PATH permanently in Windows 7: 1. Click the Start button in the lower left corner of your Desktop. 2. Select Control Panel, click System and Security, and then click System. 3. Select the Advanced system settings link. Click Yes, if necessary. 4. In the System Properties dialog box, select the Advanced tab, if necessary, and then click the Environment Variables button. 5. Select PATH or Path in the User variables or System variables section, click Edit, and then edit the PATH variable by adding the following to the end of the current PATH: ;C:WindowsMicrosoft.NETFrameworkv4.0.30128 xvi EAD THIS BEFORE YOU BEGIN R E A D T H I S B E F O R E
  • 22. Note that it is important to include the semicolon (;) at the beginning of the path, preceding C:. You may have to replace the “v4.0.30128” with the version number you have installed. You also may have to substitute the drive letter of the partition you are working on if it is not C:. A typical PATH might look like this: C:Windows;C:WindowsSystem32; C:WindowsMicrosoft.NETFrameworkv4.0.30128 6. When you are finished editing the PATH variable, click OK. 7. Click OK on the Environment Variables dialog box. 8. Click OK on the System Properties dialog box. 9. Close the System window. To set the PATH permanently in Windows Vista: 1. Click the Start button in the lower left corner of your Desktop. 2. Select Control Panel and then select Classic View, if necessary. 3. Double-click System. 4. Select the Advanced system settings link. Click Continue, if necessary. 5. In the System Properties dialog box, select the Advanced tab, if necessary, and then click the Environment Variables button. 6. Select PATH or Path in the User variables or System variables section, click Edit, and then edit the PATH variable by adding the following to the end of the current PATH: ;C:WindowsMicrosoft.NETFrameworkv4.0.30128 Note that it is important to include the semicolon (;) at the beginning of the path, preceding C:. You may have to replace the “v4.0.30128” with the version number you have installed. You also may have to substitute the drive letter of the partition you are working on if it is not C:. A typical PATH might look like this: C:Windows;C:WindowsSystem32; C:WindowsMicrosoft.NETFrameworkv4.0.30128 7. When you are finished editing the PATH variable, click OK. 8. Click OK on the Environment Variables dialog box. 9. Click OK on the System Properties dialog box. 10. Close the System window. xvii READ THIS BEFORE YOU BEGIN R E A D T H I S B E F O R E
  • 23. To set the PATH permanently in Windows XP: 1. Click the Start button in the lower left corner of your Desktop. 2. Select Control Panel and then double-click System. 3. In the System Properties dialog box, select the Advanced tab, and then click the Environment Variables button. 4. Select PATH or Path in the User variables or System variables section, click Edit, and then edit the PATH variable by adding the following to the end of the current PATH: ;C:WindowsMicrosoft.NETFrameworkv4.0.30128 Note that it is important to include the semicolon (;) at the beginning of the path, preceding C:. You may have to replace the “v4.0.30128” with the version number you have installed. You also may have to substitute the drive letter of the partition you are working on if it is not C:. A typical PATH might look like this: C:Windows;C:WindowsSystem32; C:WindowsMicrosoft.NETFrameworkv4.0.30128 5. When you are finished editing the PATH variable, click OK. 6. Click OK on the Environment Variables dialog box. 7. Click OK on the System Properties dialog box. 8. Close the System window. Capitalization does not matter when you are setting the PATH variable. The PATH is a series of folders separated by semicolons (;). Windows searches for programs in the PATH folders in order, from left to right. To find out the current value of your PATH, at the prompt in a Command Prompt window, type: path. To the Instructor To complete some of the Exercises and Labs in this book, your students must use the data files provided with this book. These files are available on the Course Technology Web site at www.course.com. Follow the instructions in the Help file to copy the data files to your server or standalone computer. You can view the Help file using a text editor such as WordPad or Notepad. Once the files are copied, you may instruct your students to copy the files to their own computers or workstations. Course Technology Data Files You are granted a license to copy the data files to any computer or computer network used by individuals who have purchased this book. xviii EAD THIS BEFORE YOU BEGIN R E A D T H I S B E F O R E
  • 24. After studying this chapter, you will be able to: Discuss the Visual Basic programming language and  its history Recognize the three types of Visual Basic programs  Explain introductory concepts and terminology used  in object-oriented programming Recognize the structure of a Visual Basic program  Complete the Visual Basic development cycle, which  includes creating a source code file, compiling the source code, and executing a Visual Basic program C H A P T E R 1 An Introduction to Visual Basic and the Visual Basic Programming Programming Environment Environment Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
  • 25. You should do the exercises and labs in this chapter only after you have finished Chapter 1 of your book, Programming Logic and Design, Sixth Edition, by Joyce Farrell. This chapter introduces the Visual Basic (VB) programming language and its history. It explains some introductory object-oriented concepts, and describes the pro- cess of compiling and executing a Visual Basic program. You begin writing Visual Basic programs in Chapter 2 of this book. The Visual Basic Programming Language Visual Basic is a programming language that you can use to cre- ate interactive Web pages and to write Web-based applications that run on Web servers. Web servers are the computers that “serve up” content when you request to view Web pages. An online bookstore and an online course registration system are examples of Web-based applications. Visual Basic is also used to develop Windows-based stand-alone enterprise applications (programs that help manage data and run a business). What makes Visual Basic especially useful is that it is an object- oriented programming language. The term object-oriented encom- passes a number of concepts explained later in this chapter and throughout this book. For now, all you need to know is that an object- oriented programming language is modular in nature, allowing the programmer to build a program from reusable parts of programs called classes, objects, and methods. When Visual Basic was introduced by Microsoft in 1991, it was described as the perfect programming language because it allowed programmers to easily create applications that include a graphical user interface (GUI). A GUI allows users to interact with programs by using a mouse to point, drag, or click. Three Types of Visual Basic Programs Visual Basic programs can be written as Web applications, Windows applications, or console applications. A Web application is a pro- gram that runs on the World Wide Web and is available to end users on any platform (e.g., Windows, Mac, Linux). A Windows applica- tion is a program, such as Microsoft Word or Excel, that runs on a Windows system. A console application is a program, without a GUI, that executes in a console window and produces text-based output. In Chapters 1 through 9 of this book, you write console appli- cations. Visual Basic programmers often use the Microsoft Visual 2 C H A P T E R 1 An Introduction to Visual Basic
  • 26. Studio Integrated Development Environment (IDE) when they write programs. In Chapter 10, you learn to use the IDE to create Visual Basic Windows applications that include a simple GUI. Writing console applications is a good way to learn a language because when you are working on one, you don’t have to be con- cerned with a GUI. Console applications allow you to focus on the syntax of the language and the language constructs, such as how and when you use selection and looping statements. (You’ll learn about selection and looping statements later in this book.) An Introduction to Object-Oriented Terminology You must understand a few object-oriented concepts to be success- ful at reading and working with Visual Basic programs in this book. Note, however, that you will not learn enough to make you a Visual Basic programmer. You will have to take additional Visual Basic courses to become a Visual Basic programmer. This book teaches you only the basics. To fully understand the term object-oriented, you need to know a little about procedural programming. Procedural programming is a style of programming that is older than object-oriented program- ming. Procedural programs consist of statements that the computer runs or executes. Many of the statements make calls (a request to run or execute) to groups of other statements that are known as pro- cedures, modules, methods, or functions. These programs are known as “procedural” because they perform a sequence of procedures. Procedural programming focuses on writing code that takes some data (for example, quarterly sales figures), performs a specific task using the data (for example, adding up the sales figures), and then produces output (for example, a sales report). When people who use procedural programs (the users) decide that they want their programs to do something slightly different, a programmer must revise the pro- gram code, taking great care not to introduce errors into the logic of the program. Today, we need computer programs that are flexible and easy to revise. Object-oriented programming languages, including Visual Basic, were introduced to meet this need. In object-oriented pro- gramming, the programmer can focus on the data that he or she wants to manipulate, rather than the individual lines of code required to manipulate that data (although those individual lines still must eventually be written). An object-oriented program is made up of a collection of interacting objects. 3 An Introduction to Object-Oriented Terminology
  • 27. An object represents something in the real world, such as a car, an employee, or an item in an inventory. An object includes (or encapsulates) both the data related to the object and the tasks you can perform on that data. The term behavior is sometimes used to refer to the tasks you can perform on an object’s data. For example, the data for an inventory object might include a list of inventory items, the number of each item in stock, the number of days each item has been in stock, and so on. The behaviors of the inventory object might include calculations that add up the total number of items in stock and calculations that determine the average amount of time each item remains in inventory. In object-oriented programming, the data items within an object are known collectively as the object’s attributes or properties. You can think of an attribute or property as one of the characteristics of an object, such as its shape, its color, or its name. The tasks the object performs on that data are known as the object’s methods. (You can also think of a method as an object’s behavior.) Because methods are built into objects, when you create a Visual Basic program, you don’t always have to write multiple lines of code telling the program exactly how to manipulate the object’s data. Instead, you can write a shorter line of code, known as a call, that passes a message to the method indicating that you need it to do something. For example, you can display dialog boxes, scroll bars, and buttons for a user of your program to type in or click on simply by sending a mes- sage to an existing object. At other times, you will be responsible for creating your own classes and writing the code for the methods that are part of that class. Whether you use existing, prewritten classes or create your own classes, one of your main jobs as a Visual Basic programmer is to communicate with the various objects in a program (and the methods of those objects) by passing messages. Individual objects in a program can also pass messages to other objects. When Visual Basic programmers begin to write an object-oriented program, they first create a class. A class can be thought of as a template or pattern for a group of similar objects. In a class, the programmer specifies the data (attributes/properties) and behaviors (methods) for all objects that belong to that class. An object is some- times referred to as an instance of a class, and the process of creating an object is referred to as instantiation. To understand the terms class, instance, and instantiation, it’s helpful to think of them in terms of a real-world example—baking a choco- late cake. The recipe is similar to a class, and an actual cake is an object. If you wanted to, you could create many chocolate cakes that are all based on the same recipe. For example, your mother’s birthday 4 C H A P T E R 1 An Introduction to Visual Basic
  • 28. cake, your sister’s anniversary cake, and the cake for your neighbor- hood bake sale all might be based on a single recipe that contains the same data (ingredients) and methods (instructions). In object- oriented programming, you can create as many objects as you need in your program from the same class. The Structure of a Visual Basic Program When a programmer learns a new programming language, the first program he or she traditionally writes is a Hello World program—a program that displays the message “Hello World” on the screen. Creating this simple program illustrates that the language is capable of instructing the computer to communicate with the outside world. The Visual Basic version of the Hello World program is shown in Figure 1-1. Module HelloWorld Sub Main() System.Console.WriteLine("Hello World.") End Sub End Module Figure 1-1 Hello World program At this point, you’re not expected to understand all the code in Figure 1-1. Just notice that the code begins with the word Module. Module is a special word, known as a keyword, which is reserved by Visual Basic to have a special meaning. A Module is one of the pos- sible packages into which you can place code that you want to com- pile and execute. The Module keyword tells the Visual Basic compiler that you are beginning the creation of a Module and that what follows is part of that Module. The name of the Module is up to you; however, to make your program easier to maintain and revise later, take care to choose a meaningful name. Because this program is written to display the words “Hello World.” on the user’s screen, it makes sense to name the Module HelloWorld. The keywords End Module on the last line of Figure 1-1 mark the end of the Module. On the second line in Figure 1-1, you see Sub Main(). This marks the beginning of the procedure named Main(). This is a special procedure in a Visual Basic program; the Main() pro- cedure is the first procedure that executes when any program runs. 5 The Structure of a Visual Basic Program
  • 29. The programs in the first eight chapters of this book will include only the Main() procedure. In later chapters you will be able to include additional procedures. The first part of any procedure is its header. In Figure 1-1, the header for the Main() procedure begins with the Sub keyword and is fol- lowed by the procedure name, which is Main(). The End Sub on the second-to-last line of Figure 1-1 marks the end of the Main() pro- cedure. All the code within the procedure header and the End Sub executes when the Main() procedure executes. In Figure 1-1, there is only this one line of code that executes: System.Console.WriteLine("Hello World.") This is the line that causes the words “Hello World.” to appear on the user’s screen. This line consists of two parts. The first part, System.Console.WriteLine(), prints (that is, displays on the screen) whatever is included within its parentheses and positions the cursor so any subsequent output appears on the next line. In this example, the parentheses contain the message “Hello World.” so that is what will appear on the screen. (The quotation marks will not appear on the screen, but they are necessary to make the program work.) In the statement System.Console.WriteLine("Hello World."), System is a namespace, Console is an object, and WriteLine() is a method. A namespace is a collection of classes. The System namespace includes many of the commonly used classes. Visual Basic programs frequently use the namespace-dot-object-dot-method syntax or the class-dot-object-dot-method syntax. Next, you learn about the Visual Basic development cycle so that later in this chapter, you can compile the Hello World program and execute it. The Hello World program is saved in a file named HelloWorld.vb and is included in the student files for this chapter. The Visual Basic Development Cycle When you finish designing a program and writing the Visual Basic code that implements your design, you must compile and execute your program. This three-step process of writing code, compiling code, and executing code is called the Visual Basic development cycle. It is illustrated in Figure 1-2. Don’t be concerned if you don’t understand all the terms in Figure 1-2. These terms are explained in the following sections. You can tell Main() is a procedure because of the parenthe- ses; all Visual Basic procedure names are followed by parentheses. 6 C H A P T E R 1 An Introduction to Visual Basic
  • 30. Step 1 Write Visual Basic source code Source code file (MyProgram.vb) Step 2 Compile source code (vbc MyProgram.vb) Step 3 Execute the program Common Intermediate Language (CIL) Output Figure 1-2 The Visual Basic development cycle Writing Visual Basic Source Code As you learned in the previous section, you write a Visual Basic pro- gram by creating a Module and including a procedure named Main() in the Module. But what do you use to write the program, and where do you save it? To write a Visual Basic program, you can use any text editor, but the steps in this book assume you are using Windows Notepad. To start Notepad, click the Start button, point to Programs or All Programs, click Accessories, and then click Notepad. Once Notepad starts, you simply type in your Visual Basic source code. Source code is the name used for the statements that make up a Visual Basic program. For example, the code shown in Figure 1-1 is source code. When you save the file that contains the source code, it is important to add the extension .vb to the filename. For the Hello World pro- gram, the Module is named HelloWorld; therefore, it is convenient to name the source code file HelloWorld.vb. Of course, it is also impor- tant to remember the location of the folder in which you choose to save your source code file. Compiling a Visual Basic Program The Visual Basic compiler is named vbc, and it is responsible for taking your source code and transforming it into Common Intermediate Language (CIL). CIL is intermediate, machine- independent code. Intermediate means that the code is between 7 The Visual Basic Development Cycle
  • 31. source code and machine code. Machine code consists of the 1s and 0s that a computer needs to execute a program. Next, the Visual Basic compiler reads the CIL code and produces an executable file. This file has the same name as the source code file, but it has an .exe extension rather than a .vb extension. The following steps show how to compile a source code file. These steps assume you have already created and saved the HelloWorld.vb source code file. 1. Set your PATH environment variable. Refer to “Read This Before You Begin” at the front of this book or ask your instructor for instructions on how to set the PATH environ- ment variable. 2. Open a Command Prompt window. To do this in Windows XP, click the Start button, point to All Programs, point to Accessories, and then click Command Prompt. In Vista or Windows 7, click the Start button, point to All Programs, click Accessories, and then click Command Prompt. The cursor blinks to the right of the current file path. 3. To compile your source code file, you first have to change to the file path containing your source code file. To do this, type cd driveletter:path where driveletter is the drive contain- ing your file, and path is the path to the folder containing your file. For example, to open a file stored in a folder named “Testing,” which is in turn stored in a folder named “My Program,” which is stored on the C: drive, you would type cd c:My ProgramTesting. After you type the command, press Enter. The cursor now blinks next to the file path for the folder containing your source code file. 4. Type the following command, which uses the Visual Basic compiler vbc to compile the program: vbc HelloWorld.vb If there are no syntax errors in your source code, a file named HelloWorld.exe is created, and you will not see anything special happen. If there are syntax errors, you will see error messages on the screen. In that case, you need to go back to Notepad to fix the errors, save the source code file again, and recompile until no syntax errors remain. Syntax errors are messages from the compiler that tell you what your errors are and where they are located in your source code file. 5. After the program is compiled, you can use the dir com- mand to display a directory listing to see the file named HelloWorld.exe. To execute the dir command, you type dir If you are working in a school computer lab, the PATH environment variable might already have been set for you. The PATH environment variable tells your operating system which directories on your sys- tem contain commands. 8 C H A P T E R 1 An Introduction to Visual Basic
  • 32. at the command prompt. For example, if your source code file is located at C:My ProgramTesting, the command prompt and dir command should look like this: C:My Program Testing> dir. The HelloWorld.exe file should be in the same directory as the source code file, HelloWorld.vb. Step 3 in the development cycle is executing the Visual Basic pro- gram. You’ll learn about that next. Executing a Visual Basic Program As you know, a computer can understand only machine code (1s and 0s). The machine code for your Visual Basic program is stored in a file with an .exe extension. To execute the Hello World program, do the following: 1. Open a Command Prompt window. To do this in Windows XP, click the Start button, point to All Programs, point to Accessories, and then click Command Prompt. In Vista or Windows 7, click the Start button, point to All Programs, click Accessories, and then click Command Prompt. Change to the file path containing your executable file, if necessary, and then enter the following command: HelloWorld 2. When the program executes, the words “Hello World.” appear in a Command Prompt window. Figure 1-3 illustrates the steps involved in compiling HelloWorld.vb using the vbc compiler, executing the dir command to verify that the file HelloWorld.exe was created, and executing the Hello World program. Figure 1-3 Compiling and executing the Hello World program At this point in your program- ming career, don’t expect to understand the contents of an .exe file if you open one using a text editor, such as Notepad. You must be in the same directory that contains your .exe file when you execute the program. 9 The Visual Basic Development Cycle
  • 33. Exercise 1-1: Understanding How to Compile and Execute Visual Basic Programs In this exercise, you use what you have learned about compiling and executing Visual Basic programs to answer Questions 1–2. You have written a Visual Basic program and have stored your source code in a file named MyVBProgram.vb. 1. What command would you use to compile the source code? 2. What command would you use to execute the program? LAB 1.1 Compiling and Executing a Visual Basic Program In this lab, you compile and execute a prewritten Visual Basic program, and then answer Questions 1–6. 1. Open the source code file named GoodMorning.vb using Notepad or the text editor of your choice. 2. Save this source code file in a directory of your choice, and then change to that directory. 3. Compile the source code file. There should be no syntax errors. Record the command you used to compile the source code file. 4. Execute the program. Record the command you used to exe- cute the program, and also record the output of this program. 5. Modify the program so that it displays “Good Job!,” and then change the Module name to GoodJob. Save the file as GoodJob.vb. Compile and execute the program. 6. Modify the Good Job program so that it prints two lines of output. Add a second output statement that displays “Have a great day.” Change the Module name to GoodJob2 and then save the modified file as GoodJob2.vb. Compile and execute the program. 10 C H A P T E R 1 An Introduction to Visual Basic
  • 34. After studying this chapter, you will be able to: Name variables and use appropriate data types  Declare and initialize variables  Understand and use unnamed and named constants  Use arithmetic operators in expressions  Use assignment operators in assignment statements  Write Visual Basic comments  Write programs using sequential statements and interactive  input statements C H A P T E R 2 Variables, Constants, Operators, and Writing Programs Using Sequential Statements
  • 35. In this chapter, you learn about writing programs that use variables, constants, and arithmetic operators. You also learn about programs that receive interactive input from a user of your programs. We begin by reviewing variables and constants and learning how to use them in a Visual Basic program. You should do the exercises and labs in this chapter only after you have finished Chapters 2 and 3 of your book, Programming Logic and Design, Sixth Edition, by Joyce Farrell. Variables As you know, a variable is a named location in the computer’s memory whose contents can vary (thus the term variable). You use variables in a program when you need to store values. The values stored in variables often change as a program executes. In Visual Basic, it is a good programming practice to declare variables before you use them in a program. Declaring a variable is a two-part process: first, you give the variable a name, and then you specify its data type. You’ll learn about data types shortly. But first, we’ll focus on the rules for naming variables in Visual Basic. Variable Names Variable names in Visual Basic can consist of letters, numerical digits, and the underscore character, but they cannot begin with a digit. You should avoid variable names that begin with an underscore because they are not compliant with the Common Language Specification (CLS). You will learn more about the CLS in additional courses you take in Visual Basic. You cannot use a Visual Basic keyword for a variable name. As you learned in Chapter 1 of this book, a keyword is a word with a special meaning in Visual Basic. The following are all examples of legal vari- able names in Visual Basic: my_var, num6, intValue, and firstName. Table 2-1 lists some examples of invalid variable names, and explains why each is invalid. Name of Variable Explanation 3wrong Invalid because it begins with a digit don’t Invalid because it contains a single quotation mark public Invalid because it is a Visual Basic keyword Table 2-1 Some examples of invalid variable names When naming variables, keep in mind that Visual Basic is not case sensitive—in other words, Visual Basic does not know the difference A variable is sometimes referred to as an identifier. 12 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 36. between uppercase and lowercase characters. That means value, Value, and VaLuE are the same variable name in Visual Basic. In Visual Basic, variable names can be 1,023 characters in length. A good rule is to give variables meaningful names that are long enough to describe how the variable is used, but not so long that you make your program hard to read or cause yourself unnec- essary typing. For example, a variable named firstName will clearly be used to store someone’s first name. The variable name freshmanStudentFirstName is descriptive but inconveniently long; the variable name fn is too short and not meaningful. One of the naming conventions used by Visual Basic programmers is called camel case. This means: Variable names are made up of multiple words, with no spaces • between them. The first character in the variable name is lowercase. • The first character of each word after the first word is a capitalized • character. Examples of Visual Basic variable names in camel case include firstName, myAge, and salePrice. You do not include spaces between the words in a variable name. Visual Basic Data Types In addition to specifying a name for a variable, you also need to spec- ify a particular data type for that variable. A variable’s data type dic- tates the amount of memory that is allocated for the variable, the type of data that you can store in the variable, and the types of operations that can be performed on the variable. There are many different kinds of data types, but in this book we will focus on the most basic kind of data types, known as primitive data types. There are 12 primitive data types in Visual Basic: Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, Short, Single, and String. Some of these data types (Short, Integer, Long, Double, and Single) are used for vari- ables that store numeric values, and are referred to as numeric data types. The others have specialized purposes. For example, the Boolean data type is used to store a value of either True or False. You will not use all of Visual Basic’s primitive data types in the pro- grams you write in this book. Instead, you will focus on two of the numeric data types (Integer and Double) and one type that holds text (String). The Integer data type is used for values that are whole numbers. For example, you could use a variable with the data type Integer to store someone’s age (for example, 25) or the number of Although Visual Basic is not case sen- sitive, your programs will be easier for you and other programmers to read if you use uppercase and lowercase characters consistently. 13 Visual Basic Data Types
  • 37. students in a class (for example, 35). A variable of the Integer data type occupies 32 bits (4 bytes) of space in memory. You use the data type Double to store a floating point value (that is, a fractional value), such as the price of an item (2.95) or a measurement (2.5 feet). A variable of the Double data type occupies 64 bits (8 bytes) of space in memory. You will learn about using other data types as you continue to learn more about Visual Basic in subsequent courses. The Integer and Double data types will be adequate for all the numeric variables you will use in this book. But what about when you need to store a group of characters (such as a person’s name) in a variable? In programming, we refer to a group of one or more charac- ters as a string. An example of a string is the last name “Wallace” or a product type such as a “desk.” In Visual Basic, the String primitive data type is used for storing strings. Exercise 2-1: Using Visual Basic Variables, Data Types, and Keywords In this exercise, you use what you have learned about naming variables, data types, and keywords to answer Questions 1–2. 1. Is each of the following a legal Visual Basic variable name? (Answer “yes” or “no.”) myAge this_is_a_var NUMBER yourAge number $number Single 1number intNum May25 number Two Number 2. What data type (Integer, Double, or String) is most appro- priate for storing each of the following values? A person’s height (in inches) The amount of interest on a loan, such as 10% The price of a pair of boots The name of your pet The number of CDs you own Declaring and Initializing Variables Now that you understand the rules for naming a variable, and you understand the concept of a data type, you are ready to learn how to declare a variable. In Visual Basic, it is a good programming practice to declare all variables before you use them in a program. When you declare a variable, you tell the compiler that you are going to use the In Program- ming Logic and Design, Sixth Edition, the data type num is used to refer to all numeric data types. That book does not make a distinction between Integer and Double because the pseudocode used in the book is not specific to any one pro- gramming language. However, in Visual Basic this distinction is always maintained. 14 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 38. variable. In the process of declaring a variable, you must specify the variable’s name and its data type. Declaring a variable tells the com- piler that it needs to reserve a memory location for the variable. A line of code that declares a variable is known as a variable declaration. The Visual Basic syntax for a variable declaration is as follows: Dim variableName As dataType For example, the declaration statement Dim counter As Integer declares a variable named counter of the Integer data type. The compiler reserves the amount of memory space allotted to an Integer variable (32 bits, or 4 bytes) for the variable named counter. The compiler then assigns the new variable a specific memory address. In Figure 2-1, the memory address for the variable named counter is 1000, although you wouldn’t typically know the memory address of the variables included in your Visual Basic programs. Figure 2-1 Declaration of variable and memory allocation counter (variable name) another variable value of counter value of the next variable first byte second byte third byte fourth byte 1000 (The memory address is assigned by the compiler; you cannot assign the memory address yourself.) 1004 (This is the next available memory address after counter because 4 bytes [1000, 1001, 1002, and 1003] have been reserved for the variable named counter.) Dim counter As Integer You can also initialize a Visual Basic variable when you declare it. When you initialize a Visual Basic variable, you give it an initial value. For example, you can assign an initial value of 8 to the counter variable when you declare it, as shown in the following code: Dim counter As Integer = 8 You can also declare and initialize variables of data type Double and String as shown in the following code: Dim salary As Double Dim cost As Double = 12.95 Dim firstName As String Dim homeAddress As String = "123 Main Street" Exercise 2-2: Declaring and Initializing Visual Basic Variables In this exercise, you use what you have learned about declaring and initializing variables to answer Questions 1–2. Numeric variables are automatically initialized to zero (0), unless you specify a different value. 15 Declaring and Initializing Variables
  • 39. 1. Write a Visual Basic variable declaration for each of the following. Use Integer, Double, or String and choose meaningful variable names. Declare a variable to store a product number (1–1000). Declare a variable to store the number of pets in your family. Declare a variable to store the price of a pair of boots. Declare a variable to store the name of your favorite book. 2. Declare and initialize variables to represent the following values. Use Integer, Double, or String, and choose meaningful variable names. One side of a rectangle that is 5.1 inches in length The number of days in November The name of your dog, “Duchess” The number of credit hours you are taking this term LAB 2.1 Declaring and Initializing Visual Basic Variables In this lab, you declare and initialize variables in a Visual Basic program provided with the data files for this book. The program, which is saved in a file named NewAge.vb, calculates your age in the year 2040. 1. Open the source code file named NewAge.vb using Notepad or the text editor of your choice. 2. Declare an integer variable named newAge. 3. Declare and initialize an integer variable named currentAge. Initialize this variable with your current age. 4. Declare and initialize an integer variable named currentYear. Initialize this variable with the value of the current year. Use four digits for the year. 5. Save this source code file in a directory of your choice, and then make that directory your working directory. 16 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 40. 6. Compile the source code file NewAge.vb. 7. Execute the program. Record the output of this program. Constants As you know, a constant is a value that never changes. In Visual Basic, you can use both unnamed constants as well as named con- stants in a program. You’ll learn about named constants shortly. But first, we’ll focus on unnamed constants. Unnamed Constants Computers are able to deal with two basic types of data: text and numeric. When you use a specific numeric value, such as 35, in a program, you write it using the numbers, without quotation marks. A specific numeric value is called a numeric constant because it does not change; a 35 always has the value 35. When you use a specific text value, or string of characters, such as “William,” you enclose the string constant in double quotation marks. Both of the preceding examples, 35 and “William,” are examples of unnamed constants because they do not have specified names as variables do. Named Constants In addition to variables, Visual Basic allows you to create named constants. A named constant is similar to a variable, except it can be assigned a value only once. You use a named constant when you want to assign a name to a value that will never be changed when a program executes. To declare a named constant in Visual Basic, you use the keyword Const followed by the name of the constant, followed by the keyword As and the data type. Named constants must be initialized when they are declared, and their contents may not be changed during the execution of the program. For example, the following statement declares an Integer constant named MAX_STUDENTS and initializes MAX_STUDENTS with the value 35. Const MAX_STUDENTS As Integer = 35 By convention, in Visual Basic the names of constants are written in all uppercase letters. This makes it easier for you to spot named constants in a long block of code. 17 Constants
  • 41. Exercise 2-3: Declaring and Initializing Visual Basic Constants In this exercise, you use what you have learned about declaring and initializing constants to answer the following question. 1. Declare and initialize constants to represent the following val- ues. Use Integer, Double, or String and choose meaningful names. The price of a car wash is $14.95. The number of days in November is 30. The name of your dog is “Duchess”. The maximum number of credit hours you may take in a term is 18. LAB 2.2 Declaring and Initializing Visual Basic Constants In this lab, you declare and initialize constants in a Visual Basic program provided with the data files for this book. The program, which is saved in a file named NewAge2.vb, calculates your age in the year 2040. 1. Open the source code file named NewAge2.vb using Notepad or the text editor of your choice. 2. Declare a constant named YEAR and initialize YEAR with the value 2040. 3. Edit the following statement so that it uses the constant named YEAR: newAge = currentAge + (2040 − currentYear) 4. Edit the following statement, so that it uses the constant named YEAR: System.Console.WriteLine ("I’ll be" & newAge & "in 2040.") 5. Save this source code file as NewAge2.vb in a directory of your choice, and then make that directory your working directory. 6. Compile the source code file NewAge2.vb. 7. Execute the program. Record the output of this program. 18 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 42. Arithmetic and Assignment Operators After you declare a variable, you can use it in various tasks. For example, you can use variables in simple arithmetic calculations, such as adding, subtracting, and multiplying. You can also perform other kinds of operations with variables, such as comparing one variable to another to determine which is greater. In order to write Visual Basic code that manipulates variables in this way, you need to be familiar with operators. An operator is a symbol that tells the computer to perform a mathematical or logical operation. Visual Basic has a large assortment of operators. We begin the discussion with a group of operators known as the arithmetic operators. Arithmetic Operators Arithmetic operators are the symbols used to perform arithmetic calculations. You are probably already very familiar with the arithme- tic operators for addition (+) and subtraction (−). Table 2-2 lists and explains Visual Basic’s arithmetic operators. Operator Name and Symbol Example Comment Addition + num1 + num2 Subtraction − num1 − num2 Multiplication * num1 * num2 Integer Division 152 Integer division; result is 7; fraction is truncated Division / 15/2 15.0 / 2.0 15.0 / 2 Floating-point division; result is 7.5 Floating-point division; result is 7.5 Floating-point division; result is 7.5 Modulus MOD hours MOD 24 Performs division and finds the remainder; result is 1 if the value of hours is 25 Negation − −(num1 − num2) If value of (num1 − num2) is 10, then −(num1 − num2) is −10 Exponentiation ^ 2 ^ 3 Raises 2 to the third power; result is 8 Table 2-2 Visual Basic arithmetic operators You can combine arithmetic operators and variables to create expressions. The computer evaluates each expression, and the result is a value. To give you an idea of how this works, assume that the value of num1 is 3 and num2 is 20, and that both are data type Integer. 19 Arithmetic and Assignment Operators
  • 43. With this information in mind, study the examples of expressions and their values in Table 2-3. Expression Value Explanation num1 + num2 23 3+20=23 num1 − num 2 −17 3−20=−17 num2 MOD num1 2 20 / 3=6 remainder 2 num1 * num2 60 3 * 20=60 num2 / num1 6.66666 20 / 3=6.66666 (floating point division) num2 num1 6 20 / 3=6 (remainder is truncated) −num1 −3 Value of num1 is 3, therefore −num1 is −3 num2 ^ num1 8000 20 raised to the third power is 8000 Table 2-3 Expressions and values Assignment Operators and the Assignment Statement Another type of operator is an assignment operator. You use an assignment operator to assign a value to a variable. A statement that assigns a value to a variable is known as an assignment statement. In Visual Basic, there are several types of assignment operators. The one you will use most often is the = assignment operator, which sim- ply assigns a value to a variable. Table 2-4 lists and explains some of Visual Basic’s assignment operators. Operator Name and Symbol Example Comment Assignment = count = 5 Places the value on the right side into the memory location named on the left side Initialization = Dim count As Integer = 5 Places the value on the right side into the memory location named on the left side when the variable is declared Assignment += num += 20 Equivalent to num = num + 20 Assignment −= num −= 20 Equivalent to num = num − 20 Assignment *= num *= 20 Equivalent to num = num * 20 Assignment /= num /= 20 Equivalent to num = num / 20 Assignment = num = 20 Equivalent to num = num 20 Assignment ^= num ^= 20 Equivalent to num = num ^ 20 Table 2-4 Visual Basic assignment operators 20 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 44. When an assignment statement executes, the computer evaluates the expression on the right side of the assignment operator and then assigns the result to the memory location associated with the variable named on the left side of the assignment operator. An example of an assignment statement is shown in the following code: answer = num1 * num2 This assignment statement causes the computer to evaluate the expression num1 * num2. After evaluating the expression, the com- puter stores the result in the memory location associated with answer. If the value stored in the variable named num1 is 3, and the value stored in the variable named num2 is 20, then the value 60 is assigned to the variable named answer. Here is another example: answer += num1 This statement is equivalent to the following statement: answer = answer + num1 If the value of answer is currently 10 and the value of num1 is 3, then the expression on the right side of the assignment statement answer + num1 evaluates to 13, and the computer assigns the value 13 to answer. Precedence and Associativity Once you start to write code that includes operators, you need to be aware of the order in which a series of operations is performed. In other words, you need to be aware of the precedence of operations in your code. Each operator is assigned a certain level of precedence. For example, multiplication has a higher level of precedence than addition. So in the expression 3 * 7 + 2, the 3 * 7 would be multi- plied first; after the multiplication is completed, the 2 is added. But what happens when two operators have the same precedence? The rules of associativity determine the order in which operations are evaluated in an expression containing two or more operators with the same precedence. For example, in the expression 3 + 7 − 2, the addition and subtraction operators have the same precedence. As shown in Table 2-5, the addition and subtraction operators have left- to-right associativity, which causes the expression to be evaluated from left to right (3 + 7 added first; then 2 is subtracted). Table 2-5 shows the precedence and associativity of the operators discussed in this chapter. 21 Arithmetic and Assignment Operators
  • 45. Operator Name Operator Symbol Order of Precedence Associativity Parentheses () First Left to right Exponentiation ^ Second Left to right Negation − Third Right to left Multiplication and division * / Fourth Left to right Integer division Fifth Left to right Modulus MOD Sixth Left to right Addition and subtraction + − Seventh Left to right Assignment = += −= Eighth Right to left *= /= = ^= Table 2-5 Order of precedence and associativity As you can see in Table 2-5, the parentheses operator ( ) has the highest precedence. You use this operator to change the order in which operations are performed. Note the following example: average = test1 + test2 / 2 The task of this statement is to find the average of two test scores. The way this statement is currently written, the compiler will divide the value in the test2 variable by 2, and then add it to the value in the test1 variable. So, for example, if the value of test1 is 90 and the value of test2 is 88, then the value assigned to average will be 134, which is obviously not the correct average of these two test scores. By using the parentheses operator in this example, you can force the addition to occur before the division. The correct statement looks like this: average = (test1 + test2) / 2 In this example, the value of test1, 90, is added to the value of test2, 88, and then the sum is divided by 2. The value assigned to average, 89, is the correct result. Exercise 2-4: Understanding Operator Precedence and Associativity In this exercise, you use what you have learned about operator pre- cedence and associativity. Study the following code and then answer Questions 1–2. 22 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 46. ' This program demonstrates the precedence and ' associativity of operators. Module Operators Sub Main() Dim value1 As Integer = 8 Dim value2 As Integer = 2 Dim value3 As Integer = 11 Dim answer1 As Integer Dim answer2 As Integer Dim answer3 As Integer Dim answer4 As Integer Dim answer5 As Integer Dim answer6 As Integer answer1 = value1 * value2 + value3 System.Console.WriteLine("Answer 1: " & answer1) answer2 = value1 * (value2 + value3) System.Console.WriteLine("Answer 2: " & answer2) answer3 = value1 + value2 − value3 System.Console.WriteLine("Answer 3: " & answer3) answer4 = value1 + (value2 − value3) System.Console.WriteLine("Answer 4: " & answer4) answer5 = value1 + value2 * value3 System.Console.WriteLine("Answer 5: " & answer5) answer6 = value3 / value2 System.Console.WriteLine("Answer 6: " & answer6) End Sub End Module 1. What is the value of answer1, answer2, answer3, answer4, answer5, and answer6? 2. Explain how precedence and associativity affect the result. LAB 2.3 Arithmetic and Assignment Operators In this lab, you complete a Visual Basic program that is provided along with the data files for this book. The 23 Arithmetic and Assignment Operators
  • 47. program, which was written for an appliance company, prints the name of an appliance, its retail price, its wholesale price, the profit made on the appliance, a sale price, and the profit made when the sale price is used. 1. Open the file named Appliance.vb using Notepad or the text editor of your choice. 2. The file includes variable declarations and output statements. Read them carefully before you proceed to the next step. 3. Design the logic and write the Visual Basic code that will use assignment statements to first calculate the profit, then cal- culate the sale price, and finally calculate the profit when the sale price is used. Profit is defined as the retail price minus the wholesale price. The sale price is 20% deducted from the retail price. The sale profit is defined as the sale price minus the wholesale price. Perform the appropriate calculations as part of your assignment statements. 4. Save the source code file in a directory of your choice, and then make that directory your working directory. 5. Compile the program. 6. Execute the program. Your output should be as follows: Item Name: Dishwasher • Retail Price: $425 • Wholesale Price: $275 • Profit: $150 • Sale Price: $340 • Sale Profit: $65 • Next, you see how to put together all you have learned in this chapter to write a Visual Basic program that uses sequential statements, com- ments, and interactive input statements. Sequential Statements, Comments, and Interactive Input Statements The term sequential statements (or sequence), refers to a series of statements that must be performed in sequential order, one after another. You use a sequence in programs when you want to perform actions one after the other. A sequence can contain any number of 24 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 48. actions, but those actions must be in the proper order, and no action in the sequence can be skipped. Note that a sequence can contain comments that are not considered part of the sequence itself. Comments serve as documentation, explaining the code to the programmer and any other people who might read it. In Chapter 2 of Programming Logic and Design, Sixth Edition, you learned about program comments, which are statements that do not execute. You use comments in Visual Basic programs to explain your logic to people who read your source code. The Visual Basic compiler ignores comments. In Visual Basic, you type an apostrophe character (’) at the begin- ning of the text that you want the compiler to ignore. You may place comments anywhere in a Visual Basic program. In the Visual Basic program below, the first five lines of the program are comments that explain some basic information about the program. Comments are included throughout to describe various parts of the program. A sequence often includes interactive input statements, which are statements that ask, or prompt, the user to input data. The Visual Basic program in the following example uses sequential statements and interactive input statements to convert a Fahrenheit temperature to its Celsius equivalent: ' This Visual Basic program converts a Fahrenheit ' temperature to Celsius. ' Input: Interactive ' Output: Fahrenheit temperature followed by ' Celsius temperature Option Explicit On Option Strict On Module Temperature Sub Main() Dim fahrenheitString As String Dim fahrenheit As Double Dim celsius As Double ' Get interactive user input fahrenheitString = InputBox$( _ "Enter Fahrenheit temperature: ") ' Convert String to Double fahrenheit = Convert.ToDouble(fahrenheitString) ' Calculate celsius celsius = (fahrenheit − 32.0) * (5.0/9.0) ' Output System.Console.WriteLine("Fahrenheit temperature:" & _ fahrenheit) System.Console.WriteLine("Celsius temperature:" & _ celsius) End Sub End Module You are responsible for including well-written, meaningful comments in all of the programs that you write. In fact, some people think that commenting your source code is as impor- tant as the source code itself. 25 Sequential Statements, Comments, and Interactive Input Statements
  • 49. This program is made up of sequential statements that execute one after the other. As noted above, it also includes comments explaining the code. The comment lines begin with '. The statement, Option Explicit On, turns on the Visual Basic option that requires you to declare all variables in your program. The default in Visual Basic is that this option is on. The statement, Option Strict On, turns on the Visual Basic option that requires you to declare variables with a specific type and can therefore accept only values of that data type. The Strict option must be turned on to enforce strong typing. The Strict option is turned off by default. It is highly recommended that you turn on this option; you should get in the habit of including this statement in all your Visual Basic programs. After the variable fahrenheitString is declared as a String, and fahrenheit and celsius are declared (using the Double data type), the following assignment statement executes: fahrenheitString = InputBox$( _ "Enter Fahrenheit temperature:") The InputBox$() function (on the right side of the assignment state- ment) is used when you want the program’s user to interactively input data needed by your program. When you use the InputBox$() function, you specify within the parentheses the words you want to appear in the dialog box on the user’s screen. In this example, the phrase “Enter Fahrenheit temperature:” will appear in the dialog box on the user’s screen. The same dialog box also displays a text box where the user can type his or her input, as shown in Figure 2-2. Figure 2-2 An input dialog box In this program, you want the user to input a Fahrenheit temperature value so that the program can convert it to Celsius. You would think, then, that this would be a simple matter of taking the value entered by the user, assigning it to a variable, and then performing the necessary conver- sion calculation. However, Visual Basic considers any input entered into an input dialog box to be a string. In this case, the Fahrenheit value input by the user is assigned to the String variable named fahrenheitString. The problem is that we can’t perform calculations on strings; we can only Notice that the under- score charac- ter (_) is used in the output statement to continue a single statement from one line to the next. 26 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 50. perform calculations on numeric variables. So, before the program can proceed with the calculation required to convert a Fahrenheit value to a Celsius value, we need to transfer the value entered by the user to a vari- able with a numeric data type. That task is performed by the following assignment statement, which is the second statement to execute: fahrenheit = Convert.ToDouble(fahrenheitString) The ToDouble() method is used on the right side of this assignment statement. This method belongs to the Convert class and is used to convert the Fahrenheit value, which the compiler automatically considered a String, to the Double data type. Once the String is converted to Double, it is assigned to the variable fahrenheit (which, at the beginning of the program, was declared as a Double). The third statement to execute is another assignment statement, as follows: celsius = (fahrenheit − 32.0) * (5.0 / 9.0) The formula that converts Fahrenheit temperatures to Celsius is used on the right side of this assignment statement. Notice the use of parentheses in the expression to control precedence. The expression is evaluated, and the resulting value is assigned to the variable named celsius. Notice that the division uses the / operator. This is an example of floating-point division, which results in a value that includes a fraction. If the operator were used, integer division would be performed, and the fractional portion would be truncated. This would result in a value of 0. The next two statements to execute in sequence are both output statements, as follows: System.Console.WriteLine("Fahrenheit temperature:" & _ fahrenheit) System.Console.WriteLine("Celsius temperature:" & _ celsius) The statement System.Console.WriteLine() is used to output what- ever is within the parentheses. The first output statement displays the words “Fahrenheit temperature:” followed by the value stored in the variable fahrenheit. The second output statement displays the words “Celsius temperature:” followed by the value stored in the vari- able celsius. To use the WriteLine() method correctly, you include only one argument within the parentheses. Arguments are discussed briefly in Chapter 3 and in more detail in Chapter 9. The concatena- tion operator is used in both output statements to combine two items into one (a string constant, which is one or more characters within 27 Sequential Statements, Comments, and Interactive Input Statements
  • 51. double quotes, and a Double). The & symbol, when used in this con- text, is the concatenation operator. It is used to combine two values next to each other to create a single string. This program is saved in a file named Temperature.vb and is included in the student files for this chapter. You can see the output produced by the Temperature program in Figure 2-3. Figure 2-3 Output produced by the Temperature.vb program Now that you have seen a complete Visual Basic program that uses sequential statements and interactive input statements, it is time for you to begin writing your own programs. Exercise 2-5: Understanding Sequential Statements In this exercise, you use what you have learned about sequential state- ments. Read the following scenario and then answer Questions 1–4. Suppose you have written a Visual Basic program that calculates the amount of paint you need to cover the walls in your family room. Two walls are 10 feet high and 18.5 feet wide. The other two walls are 10 feet high and 20.5 feet wide. The salesperson at the home improve- ment store told you to buy 1 gallon of paint for every 150 square feet of wall you need to paint. Suppose you wrote the following code, but your program is not compiling. This program is saved in a file named Paint.vb and is included in the student files for this chapter. Take a few minutes to study this code and then answer Questions 1–4. ' This program calculates the number of gallons ' of paint needed. Option Explicit On Option Strict On Module Paint Sub Main() Dim height1 As Double = 10 Dim height2 As Double = 10 Dim width1 As Integer = 18.5 Dim width2 As Double = 20.5 Dim squareFeet As Double Dim numGallons As Integer In Program- ming Logic and Design, Sixth Edition, the comma (,) is used as the concat- enation operator. You will learn how to control the number of places after the decimal point when you output floating-point values in Chapter 9 of this book. 28 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 52. numGallons = squareFeet / 150 squareFeet = (width1 * height1 + width2 * height2) * 2 System.Console.WriteLine("Number of Gallons:" & _ numGallons) End Sub End Module 1. The first error is in this line of code. Dim width1 As Integer = 18.5 What do you have to do to fix this problem? 2. The second error has to do with these three lines of code. Dim squareFeet As Double Dim numGallons As Integer numGallons = squareFeet / 150 What must you do to fix this problem? 3. Even if you fix the problems identified in Question 1 and Question 2, you still have a problem with this program. It has to do with the order in which your statements are written. Identify the problem, and then determine what you need to do to fix the problem. On the following lines, describe how to fix the problem. 4. You have two variables declared in this program to represent the height of your walls, height1 and height2. Do you need both of these variables? If not, how would you change the program? Be sure to identify all of the changes you would make. LAB 2.4 Using Sequential Statements in a Visual Basic Program In this lab, you complete a Visual Basic program provided with the data files for this book. The program calculates the amount of tax withheld from an employee’s weekly salary, the tax deduction to which the employee is entitled for each dependent, and 29 Sequential Statements, Comments, and Interactive Input Statements
  • 53. the employee’s take-home pay. The program output includes state tax withheld, federal tax withheld, dependent tax deductions, salary, and take-home pay. 1. Open the source code file named Payroll.vb using Notepad or the text editor of your choice. 2. Variables have been declared and initialized for you as needed, and the output statements have been written. Read the code carefully before you proceed to the next step. 3. Write the Visual Basic code needed to perform the following: Calculate state withholding tax at 3.0%, and calculate • federal withholding tax at 30.0%. Calculate dependent deductions at 5.0% of the employee’s • salary for each dependent. Calculate total withholding. • Calculate take-home pay as salary minus total withholding • plus deductions. 4. Save this source code file in a directory of your choice, and then make that directory your working directory. 5. Compile the program. 6. Execute the program. You should get the following output: State Tax: $28.5 • Federal Tax: $285 • Dependents: $142.5 • Salary: $950 • Take-Home Pay: $779 • 7. In this program, the variables named salary and numDependents are initialized with the values 950.0 and 3. To make this program more flexible, modify it to accept interac- tive input for salary and numDependents. Name the modified version Payroll2.vb. 30 C H A P T E R 2 Variables, Constants, Operators, and Sequential Statements
  • 54. C H A P T E R 3 Writing Structured Visual Basic Programs After studying this chapter, you will be able to: Use structured flowcharts and pseudocode to write  structured Visual Basic programs Write simple modular programs in Visual Basic 
  • 55. Other documents randomly have different content
  • 56. GLAMORGANSHIRE. Glamorgan.—Rev. Robert Knight, Captain Boteler, Dr Carne; Messrs A. Murray, E. David, William Llewellyn, and R. Franklen. GLOUCESTERSHIRE, EAST. Cirencester and Gloucestershire.—Messrs P. Matthews, Edmund Ruck, David Bowly. HAMPSHIRE, NORTH. Alton District.—Messrs H. Holding, Edward Knight, H. J. Mulcock, W. Garnett, J. Eggan. Basingstoke.—Mr George Harriott. HAMPSHIRE, SOUTH. Botley and South Hants.—Messrs Edward Twynam, Josh. Blundell, Caleb Gater, W. C. Spooner. HEREFORDSHIRE. Herefordshire.—Mr Henry Higgins. Ledbury District.—Rev. Edward Higgins, Messrs Reynolds Petton, Thomas France. Ross District.—Mr H. Chillingworth. HUNTINGDONSHIRE. Huntingdonshire.—Rev. James Linton, Messrs John Mann, Hammond, Ibbot Mason, Robert T. Moseley, Geo. Brighty, Peter Purvis, John Warsop. KENT, EAST. East Kent.—Sir B. W. Bridges, Bart., Messrs D. H. Carttar, Edward Hughes, John Abbot, Edward C. Hughes, Rev. Bradley Dyne, Musgrave Hilton, Charles Neame. KENT, WEST.
  • 57. Cranbrook.—Rev. W. M. S. Marriott, Messrs J. E. King, R. Tooth, Geo. Hinds, J. E. Wilson. Gravesend.—W. M. Smith, Esq., late high sheriff, Messrs W. F. Dobson, T. Collyer, Pinching, W. E. Russell, R. C. Arnold, J. Armstrong, W. Brown, W. Hubble, T. Mace. Rochester.—Messrs W. Mauclark, W. Miles, C. Lake. Maidstone.—Messrs T. Abbott, F. B. Eloy, G. Powell. Edenbridge.—Messrs W. Searle, sen., J. Holmden, Geo. Arnold. Sevenoaks.—Messrs J. Selby, G. Turner, E. Crook. Bromley.—Messrs Hammond, Moysar, and Edgerton. Dartford.—Messrs W. Allen, J. Solomon, and Slaughter. Tonbridge.—Rev. G. Woodgate, and others. Wrotham.—Messrs Leary, Thomas Spencer, and Charlton. LANCASHIRE, SOUTH. Liverpool.—Messrs Richard C. Naylor, II., Clever Chapman, Charles Turner, Lawrence Peel, Thomas Bold. LEICESTERSHIRE, NORTH. Leicestershire.—Messrs Perkins, G. Kilby. Waltham.—Messrs John Clark, F. Vincent. LEICESTERSHIRE SOUTH. Market Harborough.—Messrs Edward Fisher, jun., Josh. Perkins. Hinckley.—Messrs Matthew Oldacres, John Champion, Charles D. Breton, Thomas Swinnerton, John Brown, Richard Warner, John P. Cooke, James H. Ward. LINCOLNSHIRE, NORTH. Lincoln and Lindsey.—Colonel Sibthorp, M.P., R. A. Christopher, Esq., M.P., Mr T. Greetham, Mr J. G. Stevenson.
  • 58. Grimsby.—Mr F. Iles. Caistor.—Mr Wm. Torr. Alford.—Mr W. Loft. LINCOLNSHIRE, SOUTH. Long Sutton and Holbeach.—Messrs Wm. Skelton, Spencer Skelton, George Prest. Sleaford.—Messrs Tinley and Nickolls. LINCOLNSHIRE, EAST. East Lincolnshire.—Messrs Fricker, Joseph Rinder, jun. NORFOLK, EAST. North Walsham.—John Warnes, Esq. NORTHAMPTONSHIRE. Northamptonshire.—Messrs Gray, Rogers, and J. Scriven. NORTHUMBERLAND. Northumberland.—Sir Matthew White Ridley, Bart., Messrs Robert David, John Ayersby, John Robson, Walter Johnson, Thomas Smith, H. Wilkin. NOTTINGHAMSHIRE. North Nottinghamshire.—Messrs John Holmes, John Walker, T. Hopkinson. South Nottinghamshire.—Messrs George Storer, W. Chouler, Richard Milward, W. Champion, J. Parkinson, jun., H. Gilbert. OXFORDSHIRE. Banbury.—Messrs S. Lovell, J. Gardner, J. Selby. RUTLANDSHIRE. Rutland Branch.—Messrs Thomas Spencer, Christopher Smith, Samuel Cheetham.
  • 59. Uppingham Branch.—Messrs Owsley, Edward Wortley. SHROPSHIRE, NORTH. Shropshire.—Four delegates. Oswestry District.—S. Bickerton, Esq. SHROPSHIRE, SOUTH. Bridgnorth.—E. W. Powell, Esq., John Stephens, Esq. SOMERSETSHIRE, WEST. Somerset.—Messrs Cridland and Bult, John Wood, H. G. Andrews, R. Hooke, J. Hooke. Langport and Bridgewater District.—Mr John King, (vice chairman) and Mr T.B. Morle. STAFFORDSHIRE, NORTH. Stafford.—Major Chetwynd, Messrs T. Hartshorne, W. T. Lockyer, C. Keeling, J. Nickisson, J. Aston. STAFFORDSHIRE, SOUTH. Eccleshall Branch.—Rev. V. G. Yonge, Rev. Charles Mainwaring. SUFFOLK. East Suffolk.—Rev. Mr Alston, Messrs John Mosely, N. Barthropp, P. Dykes, W. Bloss. Ipswich Branch.—C. Lillingston, Esq. Deputy Lieutenant, Messrs T. Haward, W. F. Schrieber, J. Garnall, Venn, W. Back, W. Rodwell, J.D. Everett, Morgan, R. C. Perry, Mark Wade, Rev. F. K. Steward. Hartismere Branch.—Dr Chevalier, Messrs Samuel Peck and Deck. Stradbroke District.—W. L. B. Frener, Esq., Rev. A. Cooper. West Suffolk.—Messrs King, Vrall, Simpson, Woodward, George Gayford.
  • 60. Cosford Hundred.—Messrs C. Kersey, P. Postans. Bungay Branch.—Two delegates. SURREY, EAST. Kingston.—Messrs G. Nightingale and Daniels. Croydon Branch.—Messrs Cressingham, (chairman,) Rowland, Raincock, Robinson, Walker, and Gutteridge. Reigate Branch.—Messrs Peter, Caffyn, Jesse Pym. Tandridge Hundred Branch.—Messrs Isaac Stavely, Edward Kelsey. SURREY, WEST. West Surrey United Association.—Col. Holme Summer, Rowland Goldhawk, Esq. Epsom District.—Messrs Francis Garner and King. Dorking District.—Messrs Weller and Dewdney. SUSSEX, EAST. Sussex.—Messrs W. Rigden, A. Denman, S. H. Bigg, Edward Wyatt. East Grinsted.—Messrs George Head, Wm. Turner, John Rose, John Mills, John Payne. WARWICKSHIRE, NORTH. Rugby and Dunchurch Branch.—Messrs H. Townsend, John Perkins. Sutton Coldfield.—The Hon. E. S. Jervis, W. M. Jervis, Esq., Rev. W. K. B. Bedford, Messrs R. Fowler, R. Fowler, jun., Bodington, Sadler, Osborne, Buggins. Coleshill.—Messrs Cook, Gilbert, H. Thornley, John York, and Dr Davies. WARWICKSHIRE, SOUTH.
  • 61. Warwickshire.—Messrs Edward Greaves, C. M. Caldecott, Luke Pearman, J. H. Walker, W. W. Bromfield, R. Hemming, S. Umbers, B. Sedgeley, John Moore, H. Brown. WILTSHIRE, NORTH. Messrs G. Brown, W. Ferris, J. A. Williams, R. Strange, J. Wilkes, E. L. Rumbold, L. Waldron. WILTSHIRE, SOUTH. Salisbury Branch.—Messrs Stephen Mills, F. King, George Burtt, Leonard Maton, B. Pinnegar,—Lush. WORCESTERSHIRE, WEST. Worcestershire Branch.—The Hon. and Rev. W. C. Talbot, F. Woodward, Esq., Richard Gardner. YORKSHIRE, NORTH RIDING. Knaresborough.—Mr T. Collins, jun., of Scotton. Easingwold.—Mr Charles Harland. YORKSHIRE, EAST RIDING. East Riding.—Mr John Almack. Malton.—E. Cayley, Esq. Holderness.—Messrs Josh. Stickney and G. C. Francis. Pocklington.— — Cross. YORKSHIRE, WEST RIDING. Boroughbridge Branch.—Wm. Josh. Coltman, Esq. SCOTLAND. Scottish Protective Association.—Sir J. Drummond, Bart., Professor Aytoun, Professor Low, Dr Gardner, Messrs Geo. Makgill, Jno. Dickson, Jno. Dudgeon, J. Murdoch, J. Shand, Blackwood, Garland, Hugh Watson, Cheyne, Steuart of Auchlunkart.
  • 62. East Lothian.—Sir Jno. Hall, Bart. of Dunglass, Messrs R. Scot Skirving and Aitchison, of Alderston. Aberdeenshire.—Dr Garden. IRELAND. County Down.—The Marquis of Downshire. The noble Chairman rose and said—Gentlemen, it will not be necessary for me upon the present occasion to trespass but a few moments upon your attention, because I am happy to say that there are gentlemen much more able to discuss the question upon which we are met here to-day than the individual who now stands before you—more able, I say; but there is no man in the United Kingdom who is more deeply impressed than I am with the conviction that, if this country is to continue to be great and free, moderate import duties must be imposed (loud cheers.) Though some persons have called free trade a "great experiment," and wish us to wait and see what the result of that "experiment" is to be, I tell them fairly now, that that experiment has been tried—that it has failed—and that common sense always said it would fail (great cheering.) But during the trial of this "great experiment," have they calculated the amount of hazard which they are incurring? Are they aware of the mass of landowners and tenant-farmers of England who must be cast away if this experiment is not immediately put an end to? (loud cheers.) We are met here to-day to receive deputations from different parts of the country, and it has been thought advisable to convene this meeting, because doubts have been expressed in Parliament, whether distress was universal or not. We are met to-day to hear from the tenant-farmers from various parts of the country the prospects of their localities (hear, hear.) Gentlemen, I fear those prospects are bad indeed. But still I will say before you that which I stated in Parliament—that I have the greatest confidence in the good feeling of the people of England (cheers.) I believe that the tenant-farmers will follow the advice which I have ventured to give them, and persevere (hear, hear.) They know the justice of their
  • 63. cause. Let you, all of you, when you return home, tell your neighbours to persevere; and depend upon it, justice will, sooner or later, be done to you (loud cheers.) I will not now detain you longer than to say I hope that the expressions which may be made use of here to-day will be to show that, ill used as we are, we are still loyal to our Sovereign, and firmly attached to the constitution of our country (tremendous cheering.) Mr T. W. BOOKER, Ex-High-Sheriff of Glamorganshire, of Velindra House, near Cardiff, was then called upon by the noble chairman, and amidst great applause stepped forward to propose the first resolution—"That the difficulty and intolerable distress pervading the agricultural and other great interests of the country, and the state of deprivation and suffering to which large masses of the industrial population are reduced, are, in the opinion of this meeting, fraught with consequences the most disastrous to the public welfare, and if not speedily remedied must prove fatal to the maintenance of public credit, will endanger the public peace, and may even place in peril the safety of the state."—Mr Booker spoke as follows: My lord duke, my lords, and gentlemen,—It is, I do most unfeignedly assure you, with the deepest diffidence, if not with the deepest reluctance, that I stand before you thus early in the proceedings of this most eventful day; for, gentlemen, I came here under the sincere hope that I might be allowed to listen to others instead of myself occupying your time. But there are times, and this is an occasion, when I feel that it would ill become any man to shrink from the discharge of a public duty which those with whom he has an identity of feeling and a community of interest will and wish should devolve upon him. Humble, therefore, though my name may be, yet I will, without further apology, proceed at once to the objects which have called us together. (Cheers.) At this time of day, and on this occasion, I need not, I think, enter upon any lengthened argument, nor need I adduce any elaborate statements of statistical facts, to prove that the condition of Great Britain and Ireland and her dependencies is, to say the least, most unsatisfactory. (Hear, hear.) Your own experience will tell you that. Therefore to save your time, and with a
  • 64. knowledge of those who will have to follow me, I will assume three propositions. First of all, I will assume that the agricultural interest is immeasurably the most important interest of the state. (Hear.) Secondly, I will assume that that interest is in a state of alarming and greatly increasing depression. (Hear, hear.) And, thirdly, I will assume that that depression is occasioned and aggravated by the adoption and continuance in that altered policy of the country which now prevails. (Cheers.) I presume that my two first propositions will be conceded to me everywhere; and as to the third, here at least I presume we are unanimous, that the difficulties, the dangers, the distresses, and the disasters that now accompany us are attributable to that vile, suicidal policy falsely called free trade. (Cheers.) Having gone thus far, and having arrived at this point, it will not be of much advantage to you that I should dwell long upon the nature and extent of the distress which now accompanies you, and now environs you. That I will leave to others of those intelligent practical men who, in such multitudinous numbers, have left their homes and have come here to tell, in this central heart of England, their feelings upon the distresses and dangers that have overtaken them. But I will just glance at what is the prevailing symptom of the distress of the present day. And, strange as it may appear, the prevailing symptom is cheapness—cheapness of all the necessaries and conveniences of life—cheapness of the bountiful gifts of Providence, the productions of the earth—cheapness of the works of man, the produce of his skill and labour. And how is it that this cheapness, which augurs plenty and abundance, should not be accompanied with its usual, nay, its invariable concomitants—ease, enjoyment, safety, and repose? (Cheers.) There must be something fundamentally wrong in a state which produces such startling results. It was the opinion of one whose opinion, and whose memory too, ought to be an object of veneration with every Free- trader, as unquestionably they are of respect, from the sterling, amiable, pains-taking qualities of the man—I allude to the late Mr Huskisson—it was his opinion, and he delivered it in his place in the House of Commons so long ago as the year 1815—it was his opinion that nothing could be more delusive than the proposition that
  • 65. cheapness in the price of provisions is always a benefit. On the contrary, cheapness, without a demand for labour, is a symptom of distress. (Cheers.) The French, he adds, in his day, had cheapness without capital, and that was a proof in them of progressive decay. But this all-pervading state of cheapness is so ably glanced at and set forth in a document which I hold in my hand, and which has been transmitted to me since my arrival in town, that I cannot forbear quoting some passages from it. It is the Address of the Metropolitan Trades' Delegates to their fellow-countrymen, on the interests and the present position of the labouring classes of the empire; and if there can be words of solemn warning and import, they are contained in this most extraordinary document. It commences:— "Fellow-Countrymen,—There is not recorded an era in the history of our country, nor, indeed, in the history of all nations, when the great subject of the natural and social rights of those who live by means of their labour was required to be so thoughtfully considered, so clearly explained, and so zealously and faithfully supported, as the present era." It afterwards goes on to treat the question of cheapness thus:— "We have it announced to us that it is under the operation of unregulated, stimulated, and universal competition, we are henceforth to live. "Cheapness is proclaimed to be the one great and desirable attainment. But the cheapness that is attained under this system is not the result of fair and distributory abundance—being mainly acquired by diminishing the enjoyments, or the consumption, of those by whose labour productions are derived, and by that economy of labour by which, in so many instances, the labourer is cast off altogether from employment, because a cheaper, that is, a less consuming instrument than his body, is invented and applied. The labour of the working man thus becomes a superfluous commodity in the market, so that he must either be an outcast altogether from society, or else find some way of doing more work
  • 66. for less of materials of consumption; and even then, if he should succeed in this course of realising cheapness, he becomes instrumental in bringing many others of his fellow-labourers down to the same degraded level to which he is reduced. (Loud cheers.) "Bad and appalling, however, as is the existing condition of so many whose only means of supporting themselves and their families is the exercise of their daily labour, yet we maintain that the prospect before us is still more dark and gloomy. We declare to you our conviction that a far greater degree of suffering and of destitution impends over the labouring class and their families, both of this and of all other nations, unless the falseness of the free or competitive system be thoroughly penetrated, clearly exposed, and a course of general commerce, very different from that emanating from the free system, be entered upon." (Great cheers.) In this manner do these practical men, who are practically groaning under the evils of this altered system, dispose of the question of cheapness. The men whose signatures are appended to that document, have done me the honour also of communicating with me since I have been in town, and of stating to me what their intentions and objects are. They write me on the 4th of May inst. that "The delegates have a desire to collect all the statistics in their power showing the decline in the employment of the people, and also showing the gradual falling-off of wages since the introduction of free-trade measures to their respective trades; and also the condition of those trades which have not been directly interfered with by foreign imports, but which the delegates have reason to believe are indirectly affected by the displaced hands, from other industrial branches, continually forcing themselves into the above-mentioned trades—this is the reason they have appealed to all who are friends to native industry for assistance." But, gentlemen, it is said that free trade has not yet had fair play. Most fortunately I am indebted to the kindness and courtesy of a member of parliament, a personal friend of my own, the invaluable member for Falmouth, Mr Gwyn, for the returns of trade and navigation up to the close of last month, which only appeared and were placed in my hands last night. I have gone
  • 67. through these documents with all the business habits that I am capable of; and I come to this conclusion and result, the truth of which I defy any Free-trader to controvert. (Cheers.) The flourishing state of the cotton trade is boasted of. Why, these documents prove to you that the export of cotton goods has increased 10 per cent, but the consumption of cotton altogether has decreased 20 per cent. (Loud cheers.) And what does this show? That there is a decrease in the consumption of cotton of 30 per cent. What! free trade not had fair play! Why, our colonies have had free trade for the last twenty years. For the last ten years they have had the blessing of free and unrestricted trade, and let me appeal to any colonist, what is the universal language which defies even contradiction—We are ruined! (loud cheers.) Our own British possessions get their supplies cheaper from the United States than they can from Great Britain or our North American colonies. They expend the property of their own colonies, and of ours too, which they get there, in fostering the trade of our rivals to the destruction and exclusion of their own. Free trade not had fair play! Why, what have been its effects in Ireland? (hear, hear.) In the year 1844 or 1845, there were of acres cultivated in wheat in Ireland, 1,059,620; but in 1847, the blessed year that followed the consummation of free trade, the number was reduced to 743,871, and in 1848 it was still further reduced to 565,746, thus showing a decrease in three years of the palmy days of free trade of no less than 500,000 acres of wheat, equal to the production of 2,100,000 quarters, and in value, at what ought to be the price of wheat, upwards of six millions sterling. (Shouts of "hear, hear.") This shows with a vengeance that capital is flowing from the banks of the Shannon to the shores of the Vistula (hear, hear.) Free trade not had fair play! What will you, farmers, your wives and daughters, say to this? In the year 1833, the export of salt butter from Ireland was 25,000 tons, in value L.3,000,000 sterling, and it would take 260,000 cows to produce that quantity of butter. Now, let the Free-traders tell us what has been the export of salt butter from Ireland during the last year (hear, hear.) Ireland has broken up her old pastures, and has sown wheat upon them; and yet with all that forced and ruinous cultivation, the foreigner beats her out-and-out. But it is only a
  • 68. waste of time to go through the extent and the nature of the distress which afflicts you. I will no longer dilate upon it. I will leave its effects upon England to those admirable men whose public spirit and whose private wrongs have brought them here. And I will at once ask, what is to be the remedy? You will answer me with one acclaim, There can be but one, and that is a return to the policy of protection to native industry (cheers.) And how is this remedy to be attained? Why, by a cordial union of all classes whose labour has been invaded, and the produce of whose skill, enterprise, and industry has been excluded by that vile policy which has supplanted us in our own markets. I presume, and I say it with all respect and deep humility, that you can have no remaining hope from the present parliament (cheers), nor from the present advisers of the Crown (tremendous cheering.) But we have a constitutional sovereign, who well knows that her own peace and happiness depend upon the welfare and prosperity of her people. She well knows that upon that peace and prosperity, not only her own happiness, but the security of her throne (cheers,) and the stability of the monarchy that she administers, all alike depend (cheers.) Let us carry to the foot of the throne the wishes of her faithful people. Let us tell her of the distress and difficulties that are overtaking the industrious cultivators of the soil of the empire which she benignly governs. (Loud cries of "hear.") Let us tell her of the dangers and disasters that environ the hard-working, industrious occupiers of the territorial domains of the ancient nobility and gentry of her land (hear, hear.) Let us tell her, as the noble duke said, that, although oppressed, we are still faithful—still uncompromising—still unswerving—still unseduceable—still loyal and true to her; and I will stake my life on it, that she will be compassionate and true to us (hear, hear.) The humble individual who now addresses you is no proud aristocrat—he is no lordly possessor of wide-spread territorial domains; but he has obtained his fortune by the active pursuits of commercial industry (hear, hear.) He affords daily employment to hundreds, and thousands are dependent for their daily bread on his care and success (hear, hear.) I hope, therefore, that I speak with a due sense of the responsibility of my words and actions; and I desire
  • 69. —and, with God's blessing, I shall use every energy and talent that my Maker has endowed me with (loud cheers)—I desire, and with God's help, I shall endeavour to transmit to my children's children unimpaired those laws and liberties, those customs and institutions, which have afforded me protection during my own career of successful toil (cheers.) You will take one word of counsel from me. You, the owners and industrious occupiers of the soil, will, I hope, from this vast assembly hurl back with proud defiance that gross threat, that, if success should attend your exertions for a restoration of protection, the foundations of property would be shaken to their centre (hear, hear.) Such is the language used by Free-traders in fustian, in words as well as in merchandise (hear, hear.) Ay, forsooth, by the apostle of peace, who would have the manly quarrels of nations, as well as of individuals, settled by palaver and humbug, instead of musketry and gunpowder (great cheering.) Hurl back, I say, that defiance, and let your answer reach the ears of all who dare to obstruct the exercise of free discussion, and the results of free discussion in this hitherto free and prosperous land (hear.) But, in the struggle that must of necessity ensue before we can obtain the gracious accession of our beloved Sovereign to the prayers of her people, it may and will happen that our friends who, amidst treachery and desertion unparalleled (hear, hear,) had stood firm and faithful to their principles and professions, may be inconvenienced, and that their seats in the legislature may be jeopardised by the miscellaneous onslaught of our ministerial and jacobinical opponents (hear, hear.) But this must not, this shall not, be; for these men must be protected at the hustings (hear, hear.) When I look at this vast, this magnificent assemblage—when I consider whom and what it represents—I cannot for a moment doubt that there are, in the ranks of the protectionists of England, Ireland, Wales, and Scotland, a thousand men who will put down their hundred pounds a-piece to form a fund against all aggressors (hear, hear.) For myself, I shall at once avow that I will be one, either of a thousand to put down my hundred pounds (hear, hear,) or, if need be, I will be one of a hundred to put down my thousand pounds (loud cheers,) for this national, this necessary object. And then having done our duty, and
  • 70. having among our hereditary legislators a Richmond (cheers,) a Stanhope (hear,) a Stanley (cheers,) an Eglinton, a Talbot, a Downshire, a Malmesbury, a Beaufort, and a host of others, who will forgive me if I now fail to name them; and a Disraeli (great cheering followed the mention of Mr Disraeli's name,) a Granby (hear, hear,) a Manners (hear, hear,) a Beresford, a Stuart, a Newdegate, and many more such whom we will send to aid them in the House of Commons, let us commit our cause, the cause of peace and plenty, the cause of truth and justice (cheers,) the sacred cause of protection to native industry and capital (hear, hear)—let us commend that cause to our Sovereign, to our country, and to our God (loud cheers.) My lords and gentlemen, I must apologise for the undue length at which I have addressed you. I thank you most cordially for the kindness and the enthusiasm with which you have listened to me, and I now beg to propose the resolution with which I have the honour to be intrusted. The honourable gentleman sat down amidst the most deafening cheers. Mr W. CHOULER, South Muskham, Newark, Notts, in rising to second the resolution, said he should not waste their time by offering any apologies for his unfitness to address them upon that occasion. He had come forward to state facts, and he should at once proceed to discharge that duty to the best of his ability. He should first of all advert to the state of the labourers in his own immediate neighbourhood. He could state that the wages of those labourers had of late been reduced nominally from 12s. to 10s., and in some parts of the county to 9s. a-week; while the real reduction was much greater, because, in consequence of the depressed condition of their employers, they had been deprived of that piece-work by which they had formerly earned a further sum of 1s. or 2s. a-week. Since he had come to London he had received a statement of the condition of the labourers in a part of Leicestershire which adjoined South Nottinghamshire, and from that statement he found that during the winter there had been many unemployed labourers in that district; and that latterly, even at the approach of the spring-time, eight of
  • 71. those labourers had been going about begging. They had not asked, however, for alms, but for employment, by which they could have obtained an honest livelihood for themselves and their families. (Hear, hear.) Now, he appealed to every one whom he was addressing, whether a cultivator of the soil could be placed in a more heartrending situation than when he found himself unable to afford employment to an honest and industrious, but necessitous labourer? But, feeling dissatisfied with things at home, he had taken some trouble to ascertain how the labourers are situated in other districts with which he had no immediate connexion. As a matter of course, he had thought that the place in which he might expect to find perfection was the estate of Sir Robert Peel. (Loud cries of "hear, hear," jeers, and laughter.) He had read the document issued some time since by Sir Robert Peel to his tenantry, and through his tenantry to the country at large; and from the wording of that document he had been led to suppose that in the parish of Kingsbury, the property of Sir Robert Peel, the labourers were fully employed, well housed, and well fed. But he would tell them what he had seen there only a few days ago. The parish of Kingsbury was an extensive one, and the farms there were large, for that part of the country, as they varied from 300 to 400 acres. But instead of the labourers in Kingsbury being lodged in comfortable cottages, he found scarcely any labourers' cottages upon the estate. There were no small holdings, no cottage allotments in the parish; and he had been told that the labourers employed in it resided at a distance of two or three miles from the place. The fact was, that for some years a system had been carried on in that parish for reducing the number of its agricultural labourers, (hear, hear,) and removing the poor off the property. He confessed he only wondered that the "Times Commissioner" had not been down there (hear, and laughter,) to tell the tenantry how much of the physical force of the labourer was lost by living so far from his work. But he had found worse than that. He had found that English labourers were being gradually displaced by low-priced Irish labourers. He had found that the tenants of Sir Robert Peel had been employing during the winter, is well as during the summer, six or eight Irish labourers each, to whom they paid
  • 72. little or no money wages. (Cries of "shame.") Now he should not have thought much about that if he had found that the Irish labourers were prospering, as they are British subjects; but he had seen them in a very wretched condition, to which the English labourers also were being rapidly reduced. The Irish there have no house to live in, no bed to lie on, or fire to go to, but lay on straw in an outhouse; therefore this system has this tendency,—to depress the English labourer to the Irish or Continental level, without elevating the other. He would pass, however, from the parish of Kingsbury to a district represented by another lion of the day. (A laugh.) They would recollect that Mr C. Villiers, the member for Wolverhampton, had stated at the commencement of the session that there had been L.91,000,000 a-year saved to the country by the fall in prices which had followed the adoption of the free-trade policy. Now it had occurred to him that the constituents of Mr Villiers must have obtained a pretty good share of that sum. But he had found that in Wolverhampton the poor-rates had been gradually increasing during the last eight or ten years. It appeared that, during the twelve months ending in March 1842, the poor-rates in the union of Wolverhampton had not amounted to half the sum which they had reached during the twelve months ending in March 1850. It further appeared that in the year ending March 25, 1849, they had amounted to only L.10,007, while in the year ending March 25, 1850, they had amounted to L.11,625. He had mentioned these facts for the purpose of showing that the people of Wolverhampton had derived no advantage from the supposed saving of L.91,000,000 a-year effected by the adoption of a free-trade policy. But he said, without fear of contradiction, that no such saving had been made. He admitted that that sum had been lost to one class in this country (hear, hear,) but he denied that it had been gained by any other. (Cheers and laughter.) Lord John Russell said last Friday night week, that if Mr Henley brought forward a direct motion in favour of protection, he should be prepared to show that the great mass of the people were in possession of as great comforts as they ever had been. Now this was three months after the country had been said to have been the gainer of L.91,000,000 a-year, and yet all that Lord
  • 73. John Russell could say was that the people were in "as good" a position as ever they were. He would admit, if necessary, that this sum had been lost to one class, but it had not been gained by another. He should not be so much dissatisfied if the farmers had lost it, if only some other class had gained it. But the farmers had lost it and no one in this country had gained it. (Cheers.) Two-thirds of the people of this country were engaged in agricultural pursuits, and could any policy, he would ask, be more suicidal than to deprive them of L.91,000,000 a-year, without conferring any benefit on the remaining one-third of the population? (Hear, hear.) He had no hesitation in saying that the agriculturists, as a body, had never been in a worse position than that in which they were at present placed. He felt convinced that, if the existing prices for agricultural produce were to continue much longer, the tenant-farmers would be wholly unable to afford full employment to labourers; great efforts had been made last winter to employ the labourers; and when parliament met we were told, because we had employed them, that there was no distress. But if the class of able-bodied labourers were offered no alternative but to perish from destitution or to enter the workhouse, he had no hesitation in saying that this country would soon be reduced to a state which he should be most sorry to witness. Already the agricultural labourers talked of combinations; and although the farmers might be able to stem the torrent by affording them employment until the termination of the harvest, he could not help anticipating the most serious perils after that period. The labourers did not blame the farmers for their condition, for they were well aware that the farmers had not the means for affording them employment; and under those circumstances, could it be expected that the farmers would mount their horses for the purpose of opposing the just demands of their humbler fellow-countrymen? (Hear, hear.) If a man was willing and able to work in this country, he had a right to have the means of living in comfort in it. (Hear, hear.) Mr Cobden had said what he would do if a system of protection were re-established, and what would then become of the landlords. But I will say openly and publicly, that if the landlords will stick to us, we will stick to them. (Loud and enthusiastic cheers.) But
  • 74. I will go further than that—I have not yet quite finished the subject. We own nine-tenths of the horses of the kingdom, and we have the men to ride upon them. (Vociferous cheering.) And we go further still: we will support the Crown as well as the landlords. (Cheers.) Her Majesty need not fear, if she turn her back upon the towns, that she will not be supported. Protected ourselves, we will protect her against all assailants. (Loud cheers.) Mr Chouler then proceeded to say that, in his opinion, it matters not what prices were, provided all interests were placed upon the same footing. But if one interest were reduced below another, if employment were lessened whilst taxation was kept up, if more money left the country than came into it, the result must be beggary. (Cries of "Hear," and "Now for the rents.") He would come to that directly; but first stop a bit. (Laughter.) He had not quite done yet, (cheers;) but would mention to them the case of a tenant-farmer who had applied to him for advice as to what he should do under his present circumstances. This gentleman occupied three farms, had a large family, and employed a good deal of capital. The ages of his children varied from 24 to 9. He stated that his wheat wanted hoeing, and that he had no money to do it with; that he intended to have placed his family on the farms, but that if he were to do so they could not live. What could he do with them? Some of them were too old to be put to trades, and then, if he were to take out his capital, all his dead stock would go almost for nothing. He (Mr Chouler) knew he could not do anything for him. The man was a good cultivator, in good circumstances, and that was the case of hundreds and thousands of tenant-farmers. (Hear, hear.) Rent had been alluded to by some one just now. He had always regarded rent as a private bargain between two individuals. He did not come there to find fault with either his own landlord or the landlord class generally, because, as a class, he had seen them act as the very best friends of the people. But he did think that in this particular movement, latterly, they had left it almost entirely not only to the tenants to do the work—that he should not care anything about; but to defray all the expenses. (Cheers and laughter.) Now, if the tenant-farmer could not cultivate his land properly, his labourers and himself would get worse off, and he
  • 75. would be in a worse position to pay his rent, his tithes, and his taxes; and if no tithes and rent were paid, how are the clergy and aristocracy to pay their taxes and servants? (Cheers.) With regard to taxes, he would ask, was there a class of men in any other country who produced an article that was taxed from 75 to 100 per cent, before they could use it themselves? for that was the case with the malt-tax in this country at the present moment. (Cheers.) Sir Robert Peel had told them that the food of the labouring man should be free from taxation; but what was the fact? Why, he held in his hand a list of no less than 15 articles, all of which were eatables or drinkables, and necessaries to the poor man, which had to pay taxes at this moment. They were—butter, cheese, cocoa, coffee, corn and meal, eggs, fruits, hams, rice, spices, spirits, sugar, refined ditto, molasses, and tea; and they produced a revenue to the country of L.13,677,795. And yet this "wiseacre" had said that the food of the working man should be free from taxation. In addition to that, there were the articles of tobacco and snuff, which produced upwards of L.4,000,000 more. (Hear.) And was not tobacco a necessity of the working man? (Hear, hear.) Well, that brought the amount up to L.18,000,000 sterling, or more than one-third of the whole of the general taxation of the country, raised upon articles of food. (Laughter and cheers.) With regard to the malt tax, he thought that no impost was more unjust, because there was not a great quantity of malt liquor consumed by the higher classes, the greater portion being consumed by the working classes; and, with the exception of one or two cyder counties, malt liquor, in one shape or other, was the universal beverage of the labourers. But beer must be taxed, forsooth! That was not the food of the people! (Hear.) There is only one other point (continued Mr Chouler) upon which I will make an observation, and that is with reference to the great "Exhibition" of 1851. (Oh, oh! groans and hisses.) I have heard of many curious things in my lifetime; but there is one thing which I have always regarded as visionary, or as never having had an existence—but it has actually been realised in this 19th century, and in this great city —ay, in this year of grace 1850—a "mare's" (mayor's) nest has been discovered. (Roars of laughter.) Yes; and in this "mayor's nest" was
  • 76. "the Prince," and what does "the Prince" say? Now I beg that it may be distinctly understood that I mean no disrespect to my Sovereign or the Prince; but I came here to speak the truth, and I have spoken it fearlessly, and the truth I will know before I go home. The Prince says that, when you get the productions of all countries and nations before you, you have only to choose which is the cheapest and the best. Well, if you are to do that, is it not to show you that you have the opportunity of buying them? (Hear, hear.) A little umbrage has been taken at this exhibition as savouring somewhat of free-trade, and the royal commissioners have told us that they do not intend that the articles shall be sold, but that they shall be merely shown. But do you believe that the foreigner will bring his produce across the Channel or the Atlantic, and take it back again without receiving English money for it? Now, I want to know who does speak the truth? (Cries of "the Prince.") I suppose the Prince does. (Shouts of "no.") Well, well, have it as you like. (Roars of laughter.) I am come here as a delegate from the part of the country in which I reside. I came to seek the truth, and I will know it and declare it. I ask, is the foreign corn that will be imported into England in the year 1851, to come in and be looked at without being sold? (Loud cheers.) What will the foreigner say? Why, he will say "I care nothing about your 'looks,' give me your money" (Cheers and laughter.) That is what he will say. It is my duty then to ascertain whether or not it is intended still to encourage the sending out of the country money which it would be better to circulate at home. And I hope I am not exceeding my functions as a delegate in asking that question. Now you have heard my opinions upon this subject, and the concluding remarks I shall make are these: that without an alteration this country will be so shaken—after harvest, mind you, as there will be a good deal of work until then, not before—that I am perfectly confident it will be totally impossible to preserve the public peace. (Loud cheers.) I am not surprised at untruths coming from the royal commission, considering whom that commission is composed of, when I find Peel and Cobden amongst them. (Groans and hisses.) There is one name amongst them, however, which I am always in the habit of speaking of with respect and honour, and that is the name of Lord Stanley.
  • 77. (Cheers.) How far he will come out from among these royal commissioners without harm (bravo, loud cheers, and laughter,) from such a den of—you must supply the rest—I do not know, but I have confidence in the man. (Loud cheers, and great laughter.) The resolution was put from the chair, and carried unanimously. Mr EDWARD BALL, Burwell, Cambridgeshire, then moved the next resolution:—"That the indifference with which the just complaints of the people have been received by the House of Commons, its disinclination to adopt any measures for removing or alleviating the existing distress; and the want of sympathy it has exhibited for the sufferings of the people, have produced a widely-diffused feeling of disappointment, discontent, and distrust, which is fast undermining their reliance on the justice and wisdom of Parliament, the best security for loyalty to the Throne, and for the maintenance of the invaluable institutions of the country." The attendance of the noble duke this day, observed Mr Ball, imposes a fresh debt of gratitude upon us, and realises the hope we entertain, that whenever there is a grand field day he will be found in his right position—at the head of the troops. As our great commander, it is obligatory upon us that we should observe his orders, and one of those orders is, that we should express ourselves temperately and with moderation. (Hear, hear.) But I am sure that, from his experience of the field of conflict, he knows that sometimes the ardour and zeal of the British troops carry them somewhat beyond the exact line marked out by their leader and chief. (Cheers.) And if we should be found upon this occasion to advance a little beyond that strict line of propriety which he has chalked out for us, his kindness will excuse it when he knows that it is out of the fulness of our hearts, and the deep distress in which we are plunged, that we are assembled to-day to make our representations and complaints. (Cheers.) Coming, then, to the resolution which I have to propose, I ask is the allegation contained in it true? For if the thing stated in it be not true, it is useless for us to use it as an argument in justification of our assembling here to- day. Is it true? (Cries of "Yes; it is true.") Is it true that the House of Commons has shown great disregard to our petitions? (Cheers.) Is it
  • 78. true that it has rushed on heedless of the entreaties of the whole body of agriculturists, and passed a measure which it was elected for the very end and purpose of preventing? This (proceeded Mr Ball) constituted the bitterness of their grief, that when Lord John Russell's commercial measures of 1841 were defeated, a new parliament was called, and the voice of the nation proclaimed through that parliament against free trade—that the great mass of the constituencies rallied around the banner of protection—that they raised such a number of men to represent them in the House of Commons, that Lord J. Russell was obliged to throw up the reins of government into the hands of Sir Robert Peel, who took the leadership of the House of Commons with a good majority of 100, who were thought truly and honourably to represent the agricultural interest, and ready to protect their cause. (Cheers.) Then he wanted to know if the complaint in the resolution was not just when they saw that very house, which was congregated for the express purpose of maintaining protection, unhesitatingly strike that protection down, defeat all their objects, blast all their hopes, and prove untrue and unfaithful to the great constituencies of the empire. (Loud cheers.) I say, exclaimed Mr Ball, that we will never cease to represent that it was not by fair and legitimate means that we were beaten (cheers;) but that it was by the unfair, the foul play, the treacherous betrayal of those who had headed us to lead us on to victory, but who conducted the enemy into the camp, introduced the foe into the citadel, and destroyed all our hopes and prospects. (Loud cheers.) That being true, what is the language of the Free- trader upon the occasion? He sees a consequence that he never anticipated. He sees the result which we pointed out, and which he disbelieved. He finds that prices are as ruinous as we stated that they would be, and that free trade is as great a hindrance to the welfare of agriculture as we always reported that it would be. And now how does he shelter himself? Instead of coming forward, and honestly saying we have failed—it was only an experiment, which was forced upon us, and having made an error we will endeavour to correct it—he says that it is an exceptional case; that it is not the legitimate consequence, but that there are some particular
  • 79. circumstances which make the principles of free trade press with unusual severity just now. (Hear, and oh.) Now, look at the reasoning of this. If the foreigner, when he had no hope of such a market being opened to him, could for the last two years send in a supply of nearly twenty-two million quarters of various descriptions of corn, and if he could do that out of his surplus produce, what will he do now that he has the market entirely open to him—when he has got our capital to improve his cultivation, and when he knows that he may produce and send an unlimited quantity into our markets? (Hear.) I want to know how it is that, with an express declaration of the principles of the people upon the question of free trade, the landlords in the House of Lords and in the House of Commons, contrary to their own creed and in opposition to their own judgment, swerved from all that they had promised us, and threw up to those who were more impassioned and boisterous than themselves all that protection which they were bound in honour and in interest to uphold? (Loud cheers.) I feel that it is painful to speak of the landlords of this kingdom in the presence of so many of that aristocracy who shed a lustre upon their order, and whose presence here shows us how much they respond to our own principles. (Cheers.) We can never forget that those laurels which adorn the brow of the noble duke who presides over us were won in the most terrible and hard-fought encounters that ever brought glory, honour, and renown to the British arms, and that the noble duke has, from the period that he turned his sword into a ploughshare, ever stood true to the best interests of agriculture—(loud cheers)—has ever stood true to the declarations which he has made; and under all changes, and in the midst of the vapourings of his opponents, has been steadfast, untarnished, and unsullied, and now comes before us with renewed glory and increased claims upon our gratitude and support. (Loud cheers.) We cannot forget that the noble lord on his right—the Earl Stanhope—(great cheering)—whom it has been my privilege for five-and-twenty years to follow in the paths of philanthropy—who has come to the evening of a long and a useful life, in which he has shown sympathy to the poor, and has had the best interests of his fellow-men at heart—that he comes here, too,
  • 80. for the purpose of giving his powerful support to the great principles to which he and we are alike devoted. (Loud cheers.) They had also several other noble and honourable gentlemen present. They all knew the undaunted courage with which the Marquis of Downshire had fought for their right. They knew that the gentlemen around him were noble exceptions to that great defalcation which had been committed by so large a portion of the aristocracy. (Cheers.) Therefore, he (Mr Ball) could not discharge what he considered to be his duty now, without pointing them out as exceptions to the statement he was about to make—that they had fallen, not by Cobden's—that they had fallen, not by the League's tricks—that they had fallen, not by the treachery of Peel; but because their landlords —the aristocracy—those who should have upheld them—had swerved from their duty in the houses of Parliament. (Cheers.) We had the power—we had the majority—we had the voice of the country, not loud, but strong and firm, and ready to manifest itself when the moment for action came; but they were faint-hearted, they failed in the hour of need, and sacrificed us to the discordant elements of demagogueism and free-tradeism. (Uproarious cheering.) Moreover, they have contrived to take the full tale from the poverty and the debilitated circumstances of a struggling tenantry. (Loud cheers.) Let me put this simple case to you. I take the free-trade landlord, and I take the tenant-farmer. They are in partnership, are engaged in the same pursuit, and have a joint interest in the same property. A is the landlord, B the tenant-farmer. A comes to B and says, "We must make an experiment upon this land. We must introduce certain fresh modes of cultivation. We must change our plan; and if we do so-and-so you will farm better, my rent will be more secure, and we shall be altogether in more favourable circumstances than before." B, the tenant, says, "No, it is too frightful an experiment. No, it may involve me in ruin. No, you risk nothing—I risk all." (Great cheering.) But A is the richer man—A has the greater power, and he insists upon the experiment being made, in spite of the tears and protestations of the tenant. In the legislature A assents that the experiment shall be made. Thus he sweeps away and brings down to ruin the tenant who, in his
  • 81. wretchedness, looks up to the landlord for relief; and I do say that, according to the immutable principles of justice, and on the ground of what is due from man to man, the landlord, who is a party to the passing of free-trade measures, is bound to sustain and uphold his tenant, and reimburse his losses. (Vehement cheers.) I want to know, also, if I have L.5000, L.10,000, or L.20,000, placed in the funds, and a similar sum invested in the land, both of them being sustained and supported by the law—I want to know if the land be to pay the interest of the national debt, whether it is fair and just to take away the income out of which the interest of the national debt is to be paid, and what right or justice there is in demanding the full payment of the national debt? (Loud cheers.) If the fundholder has looked on and encouraged the movement which was made to bring us to ruin, I want to know with what propriety or consistency he can ask to gather out of our ruined means the wealth which, under other circumstances, we would gladly and cheerfully pay him? (Cheers.) But we are told that our landlords cannot now reverse this policy— that they have gone too far to recede—and Cobden, in that celebrated speech of his, which he made at the close of last year in Leeds, said "Only let the agriculturist come forward and put on one shilling in the shape of corn duty, and I will create such a tumult as shall shake the kingdom to its centre." (Laughter.) Most deliberately and dispassionately my answer to that is—The sooner the better! (Tremendous cheering; the whole of the vast assemblage rising to their feet, and waving their hat and hands.) I say that we have a conscience, that we have a superintending Providence, that we have laws violated, that we have all these things which will sustain and give endurance to us in any conflict that may approach; and that, therefore, we may laugh at all threatenings, and set them at defiance. (Loud cheering.) But what have the tenant-farmers to fear at the approach of discord? Can you be worse off? (No, no.) Can any alteration damage you? (Renewed cries of "no no.") All is lost! Persevere in your free-trade laws, and there is no concealing the fact that, as a class, we are swept away. (Hear.) Persevere in those laws, our homes will be taken from us. Persevere in those laws, our wives will be without protection. Persevere in those laws, our children will
  • 82. become paupers. (Cheers.) Will you then tell me, when laws have been enacted that reduce me to that position, that I, a broken- hearted man, passing into poverty and my family degraded, that I shall fear the threats of a demagogue? (Much cheering.) My answer for the whole body of the tenantry of the country is this—that we are disposed to risk all, brave all, dare all! (vociferous cheering, again and again repeated;) and that we are prepared, come what will, and cost what it may, at the hour of our country's peril, for our homes, our wives, and our families, to take those terrible steps which are the most frightful for a good and peaceable man to imagine, but which necessity and unjust treatment hurry us on and bring us to the contemplation of. (Vehement plaudits.) The most abominable part of it is this, however. If it had been a calamity brought on in the Providence of God—by the failure of the seasons, or by something which was above legislative control, we would have humbly bowed to it. But here comes the scourge—we fell through the cowardice and faint-heartedness of him whom we considered to be the greatest of modern statesmen; and when the history of the age that is passing has been recorded, it will tell us that at the same period there was in Italy a man (Count Rossi) who had been appointed minister of the Pope; that he was the witness of a rising tumult and a coming desolation; and that on the very morning of his death he was told not to go to the Senate, for if he did so there would be danger attending him. His reply was, "I have taken office— and when I did that, I took not only its honours and emoluments, but its duties and its dangers." He went to the Senate, and perished upon the steps of the Forum. But our statesman (Sir Robert Peel) saw the approach of the storm, quailed at the tempest, bowed down to the lowering cloud, dishonoured the country, brought infamy upon his own name, and poverty upon the people. (Great cheering.) Mr J. ALLIN WILLIAMS, of Wiltshire, seconded the resolution. He stood before them that day as a Wiltshire farmer, second to none in the kingdom in his loyalty and attachment to the throne and his love of the constitution of old England. (Cheers.) Moreover, he stood before them deputed by the farmers of the county of Wilts, for the
  • 83. purpose of protesting against the treatment to which the occupiers of the soil of Great Britain, as a class, had been subjected by the measures of her Majesty's Ministers and by the House of Commons. (Cheers.) He wished he could think that those measures and their consequences had been properly considered and contemplated by their framers before they were brought forward. Despite the remonstrances of the defenders of the agricultural interest in the House of Commons, and of the noble duke in the chair, and of other noblemen in the Upper House of the Legislature, her Majesty's Ministers persisted in those measures which must ultimately reduce the tenantry of England to beggary. (Hear, hear.) An individual, whom he would not name, as his name appeared to grate upon the ears of every honest farmer in this country—(cheers)—but whom it was impossible to forget, as he had laid down maxims which they felt obliged to take up and consider—a few years ago that individual laid down, as a rule, that the British farmer could not grow wheat in this kingdom under 56s. per quarter. (Hear, hear.) And upon the faith of that statement many of the men that he saw before him, himself included, had entered into agreements with their landlords for the purpose of occupying their estates for a certain period of years. (Hear, hear.) He himself had taken a lease for 14 years. What, then, must be the condition of the farmers of those estates when they were obliged to sell wheat at 36s. per quarter? The consequence was, that all, or the greater part of those who were similarly situated with himself, must be ruined. Upon the same figures was also based the Tithe Commutation Act; and by that act, which, as they too well knew, was ruled by a septennial clause, last year, when they were selling their wheat at the price of two guineas per quarter, they were compelled to pay after the rate of 54s. 10d. per quarter as the tithe of their produce; and this year, when they were selling their wheat at from 36s. to 40s. per quarter, they had to pay upon an average of 53s. (Hear, hear.) It was on that account that he came there to proclaim that her Majesty's Ministers had done the farmers a great piece of injustice, and that they had in fact emptied the pockets of the British farmers by their legislation. If there had been a necessity for the late Free-trade measures, (and he denied that there was any
  • 84. such necessity,) he contended that every portion of the community ought to have been made to bear a fair share of the burdens which had been placed upon the agriculturists. But what was the fact? He maintained that the industrious classes, the producers, alone were made to feel the burden, and that property and capital were wholly exempt. (Hear, hear.) The Free-traders, when proposing their ruinous measures, appear to have made a grand discovery, and assert, that we have no right to tax the food of the people. But did it ever enter their brains that on the wheat produced by the British farmer he paid a large tax in the shape of the superior wages paid to the labourers as compared with those of the labourers of the foreigner, to meet the taxes that are imposed on them upon the necessaries of life? That in fact the proportion of labour in a quarter of wheat (which he would assert to be two-thirds) was taxed to the enormous extent of 33 per cent? (Hear, hear, hear.) Again, was not the wheat produced by the British farmer taxed by the poor rates, the highway rates, &c.? and the heavy rents which he paid as compared with the foreign farmer, (such rents as were not heard of in any other country in the world,) was it not on account of the heavy taxes the landlords had to pay? If these things never entered the brains of her Majesty's Ministers, they were no men of business. (Hear, hear.) If they did enter into their brains, then their conduct was most knavish, most scandalous; for thereby they compelled the farmers of England to compete on most unequal terms with the foreigner. (Hear, hear.) The aristocracy of this country, he regretted to say, had not as a body done their duty in this matter. (Hear, hear.) Had the farmers of England had the aristocracy and the clergy of the country with them, they might easily have resisted the iniquitous measures of the Free- traders, and they would not have been in their present deplorable condition. (Cheers.) But now let them look for a remedy. Let them from that day call forth those men who had hitherto been blind and apathetic as regarded their own best interests, as well as those of their own immediate dependents. Let them call upon the landed gentry and the clergy throughout the country to do their duty. (Hear, hear.) He thought he might say with confidence, if they responded to that call, that the agricultural interest had nothing to fear. If nothing
  • 85. else would rouse the aristocracy of the country to a proper attention to their vital interests, as well as those of their common country, surely the insolent language of Mr Cobden at Leeds was enough to rouse them from their lethargy. But if they still refused to do their duty, he would call upon them, in the language of Milton, to "Awake! arise! or be for ever fallen." (Cheers.) He knew that time was pressing on, and that he must be brief. He would therefore conclude by again protesting against the treatment they had received, and most heartily seconding the resolution which had been proposed to them by Mr Ball. But he could not resume his seat before he had conjured them to send Whig principles to the winds. (Laughter and cheers.) His belief was, that Dr Samuel Johnson never made so happy a hit in his definition of those principles, as when he said that the devil was the first Whig. (Great laughter and cheers.) The resolution was then put and unanimously carried. Professor AYTOUN, of Edinburgh then came forward, amidst loud cheering, to propose the following resolution:—"That this meeting attributes the depression and distress of the agricultural, colonial, shipping, and other interests to the rash and impolitic changes in the laws which had long regulated the importation of foreign productions; that it is of opinion that those laws were based on the most just principles, and dictated by the soundest policy; that, under their salutary influence, the British nation had attained an unexampled state of prosperity, and a proud pre-eminence in the scale of nations; and that if their object and spirit in fostering and protecting native industry be finally abandoned, many of the most important interests of the state will be sacrificed, and the national prosperity and greatness be ruinously impaired." The learned Professor proceeded as follows:—Gentlemen, I have been desired, perhaps, rather than requested, on the part of the Scottish Protective Association, (hear, hear,) to attend this meeting, and to move one of the resolutions. I most sincerely wish that the task had been confided to abler hands than mine; but all of us have a distinct
  • 86. duty to perform; and those of my countrymen who act with me feel that, on such an occasion as this, it would be wrong and faint- hearted if Scotland, which is so deeply interested in the grand question of protection to native industry, were to hang back, and refuse to come forward to testify to you and to the tenantry of England that our zeal in this cause is as great, our feeling as decided, our determination as strong as your own. (Cheers.) I cannot offer to you the testimony of a practical agriculturist, but, perhaps, I may be allowed to say that I do not consider this is a meeting entirely of agriculturists. (Hear, hear.) Every man in this nation, from the lowest to the highest, has, I conceive, a distinct stake in this question. Every man, whatever be his occupation or his calling, is entitled to come forward here and declare his opinion upon those measures which have been thrust on the nation by an act of perfidy and treachery, to find a parallel for which we shall search the pages of history in vain. (Hear, hear.) I do not exaggerate our case when I say that Scotland is, if possible, more interested than England in the maintenance or the restoration of protection to native industry. Far later in point of time were our fields broken up, our moors reclaimed, our morasses drained; and the prosperity of Scotland, great as it has been, can hardly be reckoned as of older date than the last seventy years. Glasgow, the largest city of Scotland, the second city of the United Kingdom, rose to its present high wealth and distinction by its colonial connexion within a comparatively recent period. Our counties and our towns are alike interested in this matter. The "transition state" of suffering which our opponents now affect to have foreseen as the inevitable result of their measures—though they took especial care to conceal that revelation from every human eye—is more than beginning to make itself felt in the latter: in the former, it is evident and undenied, and already, I am sorry to say, in our remote Highland districts the work of desolation has begun. They may call it peace if they please; it is not peace, alas! it is solitude. (Hear, hear.) Now, there are certain things you have imported from Scotland for which perhaps you may not thank us very much, and one of those things is a certain race called Political Economists. (Hear, hear, and laughter.) I do not,
  • 87. however, wish to include among the number the father of political economy, Adam Smith, now in his grave three-quarters of a century, who wrote at a time and under circumstances very different from those in which we are at present placed. I observe that Mr Cobden is going about the country with the works, as he says, of Adam Smith in his hands, and favouring the public with his comments on those works; but I hope those comments will be taken by the public, as I take them, at their true value—estimating the quality of the text at a different ratio from the perverted interpretations of the expounder. There is another Scottish Political Economist, Mr M'Culloch, who has written a great deal on the subject of the corn trade, and who has been hitherto, during his long life, a decided enemy to all restrictive duties; but who, I believe, is now discovering at the last hour, that he has been going too fast in his views, and that the total withdrawal of protection is not likely to do all the good which he had at one time anticipated from it. Then, there is another gentleman, who is an ornament to the present House of Commons—the illustrious Mr Macgregor, (roars of laughter,) the gifted and infallible seer, who won the suffrages of a benighted city by telling its electors from the hustings that the nation was to increase in wealth, under the free-trade system, at the rate of precisely L.2,000,000 a-week. (Hear, hear, and laughter.) That was to be the national gain; a gain in which we were all to participate the moment the corn laws were swept away. Mr Macgregor also told the people of Glasgow that in this matter he was the political tutor of Sir R. Peel, (hear, hear, and laughter;) that he, the two million a-week man, was the individual who laid down that grand plan under which we are all at present suffering. If that be true, all I shall remark is this, that surely never did any pupil select so singular a master. Under these circumstances, I must admit that, however we may be entitled to appear here as a deputation, one gift which we have sent you from Scotland, in the shape of political economists, is a gift for which you cannot be very thankful. This is, I may add, an age in which men have been more befooled by figures than by anything else which we can mention. (Hear) Half a century ago, when any extraordinary account appeared in the newspapers, it used to be said that it must be true because it
  • 88. was to be found in print. Now, that delusion seems to have passed away; the charm of infallibility is broken, and people do not at present suppose that the press has got any particular exemption from error. But a delusion quite as great, and even more baneful, still prevails with respect to figures. There are men seated in their closets, with blue-books before them, casting up long columns of accounts, and making out statements which they call statistics, which are to form the invariable rules by which mankind is to be governed, and by which the commerce of this country is to be regulated; and it is by putting their noxious dogmas into effect that this country has of late been exposed to so much suffering. The system is older even than the days of Adam Smith; for about a century ago there went forth from Edinburgh a man of the name of John Law, the founder of the famous Mississippi scheme—a scheme for enriching men by foreign trade and for conferring on them fortunes at once, while it did away with native industry. History has its cycles, and we have again arrived at a period when quackery and imposture have usurped the place of sound common-sense, of wise policy, and I fear not to add, of truthful and Christian legislation. (Great cheering.) I know well that it is not my part to dwell long upon topics with which others are better acquainted, but if you will allow me, I shall make a few observations with regard to the present state of agricultural industry in Scotland. We have of late years been much flattered by commendations of our system of farming in that country. Whenever any of the farmers of England were supposed not to be quite up to the mark, it used to be said by Sir Robert Peel and his friends, that those farmers had only to imitate the example of the men of the same class in the Lothians. But in the beginning of this year, after a fair trial had been given to the so-called experiment of free trade, the farmers of the Lothians came forward, and testified by the leading members of their body that they were losing under the present system, and that their industry, skill, energy, and frugality were employed in vain so long as that incubus weighed upon them. (Hear, hear.) What followed? Why, the note was immediately changed, and it was said that those men were not farming high enough! That discovery was made by a gentleman who
  • 89. now appears to be Sir Robert Peel's great authority upon the subject —a certain Mr Caird. (Hear, hear, and laughter.) Now that gentleman, although a farmer, does not happen to be able to say that he ever made anything himself by farming. But he is acquainted with another individual, who is the factor on an estate of a very liberal landlord, who lets him have land for a merely nominal rent. That individual is at present in possession of a fine peat-moss, exceedingly well fitted for growing potatoes; and, as there has been less rot this year in his potatoes than in those of the greater portion of other farmers, he had derived from them a considerable profit. That is the farmer whose example is now recommended by Mr Caird as the grand panacea for all the evils under which the agricultural class is suffering. (Hear, hear.) So you see, gentlemen, in what you are to put your trust—peat-moss and potatoes! (Great laughter.) These are the twin resources with which you are to meet unlimited importations of grain! Pity, for the sake of Ireland, where both articles are abundant, that the discovery was made so late! I believe, indeed I know, you have something of the same sort here. Mr Mechi —(hear, hear, and laughter)—a gentleman whose razors are of undeniable excellence—has been attempting to show the farmers of England how to shave close (a laugh;) and the unclean spirit of free trade, finding no other place of refuge, has at last flown into the herd of Mr Huxtable's swine. (Immense cheering.) But I must say a few words with regard to the poorer districts—with regard to the Highlands of Scotland. The misery prevailing in many of those districts, more especially in the west and in the islands, did not proceed solely from the repeal of the corn laws; for it was also in a great measure owing to the noxious tariffs of Sir R. Peel, which admitted provisions duty-free into this country. It appears—indeed I believe it is an uncontradicted fact—that the British fleet is now victualled by foreign product. (Cries of "Shame.") I hold in my hand a letter from a banker in the town of Oban in Argyleshire, stating that emigration is now taking place to a very considerable extent there, that most of those who can scrape a few pounds together are taking their passage to America, and that shortly the landlords will be left with no class of people on their lands save the reckless, the
  • 90. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com