100% found this document useful (3 votes)
16 views

Immediate download Programming with Visual C Concepts and Projects 1st Edition James Allert ebooks 2024

Visual

Uploaded by

mafaneadoga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
16 views

Immediate download Programming with Visual C Concepts and Projects 1st Edition James Allert ebooks 2024

Visual

Uploaded by

mafaneadoga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Download the full version of the ebook at

https://ebookultra.com

Programming with Visual C Concepts and


Projects 1st Edition James Allert

https://ebookultra.com/download/programming-with-
visual-c-concepts-and-projects-1st-edition-james-
allert/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Visual C Net programming 1st Edition Harold Davis

https://ebookultra.com/download/visual-c-net-programming-1st-edition-
harold-davis/

ebookultra.com

Concepts in programming languages 1st Edition John C.


Mitchell

https://ebookultra.com/download/concepts-in-programming-languages-1st-
edition-john-c-mitchell/

ebookultra.com

Programming Concepts in C 2nd Edition Robert Burns

https://ebookultra.com/download/programming-concepts-in-c-2nd-edition-
robert-burns/

ebookultra.com

Windows Game Programming with Visual Basic and DirectX 1st


Edition Freeze

https://ebookultra.com/download/windows-game-programming-with-visual-
basic-and-directx-1st-edition-freeze/

ebookultra.com
Programming the Web with Visual Basic NET 1st Edition Lynn
Torkelson

https://ebookultra.com/download/programming-the-web-with-visual-basic-
net-1st-edition-lynn-torkelson/

ebookultra.com

Programming with Microsoft Visual Basic 2012 6th Edition


Diane Zak

https://ebookultra.com/download/programming-with-microsoft-visual-
basic-2012-6th-edition-diane-zak/

ebookultra.com

Programming with C Zambak 1st Edition Osman Ay

https://ebookultra.com/download/programming-with-c-zambak-1st-edition-
osman-ay/

ebookultra.com

An introduction to programming using Visual Basic 2008


with Visual Studio Expression edition DVD Schneider

https://ebookultra.com/download/an-introduction-to-programming-using-
visual-basic-2008-with-visual-studio-expression-edition-dvd-schneider/

ebookultra.com

Parallel Programming with Microsoft Visual C Design


Patterns for Decomposition and Coordination on Multicore
Architectures Patterns and Practices 1st Edition Colin
Campbell
https://ebookultra.com/download/parallel-programming-with-microsoft-
visual-c-design-patterns-for-decomposition-and-coordination-on-
multicore-architectures-patterns-and-practices-1st-edition-colin-
campbell/
ebookultra.com
Programming with Visual C Concepts and Projects 1st
Edition James Allert Digital Instant Download
Author(s): James Allert
ISBN(s): 9781423901860, 142390186X
Edition: 1
File Details: PDF, 34.02 MB
Year: 2008
Language: english
PROGRAMMING WITH VISUAL C++
CONCEPTS AND PROJECTS

JAMES ALLERT

Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Programming with Visual C++: Concepts ª2009 Course Technology, a part of Cengage Learning
and Projects
ALL RIGHTS RESERVED. No part of this work covered by the
by James Allert copyright hereon may be reproduced or used in any form or
Senior Product Manager: Alyssa Pratt by any means—graphic, electronic, or mechanical, including
photocopying, recording, taping, Web distribution, or
Acquisitions Editor: Amy Jollymore information storage and retrieval systems—without the written
Development Editor: Ann Shaffer permission of the publisher.
Content Project Manager: Erin Dowler
Editorial Assistant: Patrick Frank For product information and technology assistance, contact us at
Cengage Learning Academic Resource Center, 1-800-423-0563
Marketing Manager: Bryant Chrzan For permission to use material from this text or product, submit
Print Buyer: Julio Esperas all requests online at www.cengage.com/permissions
Cover Designer: Lisa Kuhn, Curio Press, LLC Further permissions questions can be emailed to
permissionrequest@cengage.com
Compositor: Integra
Art Director: Marissa Falco
ª2009 Cengage Learning. All Rights Reserved.
Cover Photo: Jupiterimages Corporation
ISBN-13: 9781423901860
Copyeditor: Mark Goodin
Proofreader: Brandy Lilly ISBN-10: 1-4239-0186-X
Indexer: Michael Brackney Course Technology Cengage Learning
25 Thomson Place
Boston, MA 02210
USA
Or find us on the World Wide Web at: www.course.com.
Cengage Learning products are represented in Canada by
Nelson Education, Ltd.

PowerPoint is a registered trademark of the Microsoft


Corporation; Pentium is a registered trademark of Intel
Corporation; IBM is a registered trademark of International
Business Machines Corporation.

Disclaimer
Course Technology 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
authors and the publisher do not offer any warranties or
representations, nor do they accept any liabilities with respect
to the programs.

Printed in Canada
1 2 3 4 5 6 7 12 11 10 09 08

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
TO

My loving, albeit long-suffering wife,

Deb

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
BRIEF CONTENTS

PREFACE xviii

1. Introduction 1

2. Reading, Processing, and Displaying Data 73

3. Integral Data 117

4. Selection 163

5. Repetition 219

6. Methods 269

7. Arrays 327

8. Binary Search 369

9. Sorting 417

10. Recursion 459

11. Pointers 511

12. Linked Lists: The Node Class 573

13. Object-Oriented Programming 635

APPENDIX A Concepts and Features Covered in Each Chapter 681

APPENDIX B Documentation and Reference Materials 693

APPENDIX C Common Errors 703

INDEX 715

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
TABLE OF CONTENTS

Preface xviii

INTRODUCTION 1
1 Object-Oriented Programming 2

Hardware Fundamentals 6

History of Hardware Development 8

Software Fundamentals 11

History of Software Development 17

The Programming Process 19

Types of Errors 21

A Project Development Strategy 22

The Visual Studio IDE 23

Tutorial: ‘‘Hello World!’’ (1 Button Version) 25


Problem Analysis 25
Design 25
Development and Preliminary Testing 26
Understanding the Code 46

Testing the Completed Program 49

Debugging a Program 50

On Your Own 53

Quick Review 57

Terms to Know 60

Exercises 63

Programming Exercises 69

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
viii | Programming with Visual C++: Concepts and Projects

READING, PROCESSING, AND DISPLAYING DATA 73


2 Solving Problems 74

Data and Data Types 76


Variables 79
Initializing Variables 82

Data Input 84
The TryParse() Method 85
Arithmetic Operations 86
Operator Precedence in Arithmetic Expressions 88
Arithmetic Operators and Strings 90
Shorthand Assignment 92
The Math Library 93

Data Output 94
The ToString()Method 94

Tutorial: Addition Program 95


Problem Analysis 95
Design 95
Development 97
Testing 103

On Your Own 104

Quick Review 106

Terms to Know 109

Exercises 111

Programming Exercises 114

INTEGRAL DATA 117


3 The Binary Number System 118

Integral Data Types 119

Data Type Conversion 121


Explicit Type Conversion 122
Implicit Type Conversion 122

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Table of Contents | ix

Integer Arithmetic 124


Integer Division 124
The Mod Operator (%) 126

Tutorial: Binary Conversion Program 127


Problem Analysis 127
Design 130
Development 134
Testing 151

On Your Own 152

Quick Review 153

Terms to Know 155

Exercises 156

Programming Exercises 157

SELECTION 163
4 Control Structures 164

Sequential Control Structures 164

Selection Control Structures 166

Relational Operators 167

Using if Statements to Provide a Single Alternative 168

Using if...else Statements to Provide


Two Alternatives 171

Logical Operators 172


The not Operator (!) 173
The and Operator (&&) 174
Determining When to Use the and Operator (&&)
and the or Operator (||) 176
The or Operator (||) 178

Nested Control Structures 180

Multiple Alternative Selection 182

switch Statements 185

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
x | Programming with Visual C++: Concepts and Projects

Tutorial: Vacation Planner 186


Problem Analysis 186
Design 188
Development 200

On Your Own 207

Quick Review 208

Terms to Know 210

Exercises 211

Projects 214

REPETITION 219
5 User-Controlled Repetition 220
Accumulating a Sum and Counting 225
Instance Variables 226

Repetition Control Structures 229


The while Loop 230
do...while Loops 233
The for Loop 235

Common Loop Tasks 241


Formula Translation 241
Accumulating a Product 243
Building a String 245
Generating Random Numbers 246
Finding the Largest Value 249
Counting Specific Values 250
Nested Loops 252

Tutorial: Quality Control Production Log 254


Problem Analysis 254
Design 255
Development 257
Testing 259

On Your Own 259

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Table of Contents | xi

Quick Review 260

Terms to Know 261

Exercises 263

Programming Exercises 265

METHODS 269
6 Methods 270

System-Defined Class Methods 271

The System::Math Class Library 272

System-Defined Instance Methods 274

Application Methods 274

Programmer-Defined Methods 276


Methods without Parameters or a Return Type 277
Methods with Value Parameters 281
Methods with Reference Parameters 285
Methods with a Return Value 288

Graphics Class Objects and Methods 290

The Use of Constants 294

Tutorial: Planetary Motion 296


Problem Analysis 296
Design 298
Development 302

On Your Own 310

Quick Review 311

Terms to Know 313

Exercises 315

Programming Exercises 319

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xii | Programming with Visual C++: Concepts and Projects

ARRAYS 327
7 Arrays 328

Array Declaration and Initialization 329

Using Arrays 330

Arrays and Instance Methods 332


Passing a Single Element into a Method by Value 332
Passing a Single Element into a Method by Reference 333
Passing an Entire Array into a Method 333

Sequential Search 337


Sequential Search Example 337
Searching with a for Loop 338
Counting Comparisons 340
The Search Comparison Log 341

Parallel Arrays 342

Multidimensional Arrays 345

Tutorial: Classroom Seating 348


Problem Analysis 348
Design 349
Development 355
Testing 361

On Your Own 361

Quick Review 362

Terms to Know 363

Exercises 363

Programming Exercises 366

BINARY SEARCH 369


8 Searching a Sorted List 370

Binary Search Algorithm 371

Binary Search Example 378

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Table of Contents | xiii

Search Analysis 380


Direct Lookup 380
Sequential Search 383
Binary Search 384
Determining the Best Approach to Searching 386

Searching for Strings 387


The array Class 387
String Operations 391

Tutorial: Video Store Inventory 392


Problem Analysis 392
Design 394
Development 398

Testing 403

On Your Own 404

Quick Review 404

Terms to Know 406

Exercises 406

Programming Exercises 410

SORTING 417
9 Exchanging Data Values in an Array 418

Sorting Strategies 422

The Selection Sort 424

The Selection Sort’s Inner Loop:


Locating the Smallest Unsorted Value 426

The Bubble Sort 428

The Bubble Sort’s Inner Loop:


Exchanging Values in Adjacent Elements 429

The Insertion Sort 432

The Insertion Sort’s Inner Loop:


Shifting Data Through Reassignment 438

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xiv | Programming with Visual C++: Concepts and Projects

Comparing Sorting Algorithms 440

Tutorial: Vertical Bar Chart 441


Problem Analysis 441
Design 442
Development 445
Testing 449

On Your Own 449

Quick Review 450

Terms to Know 451

Exercises 451

Programming Exercises 455

RECURSION 459
10 Factorial Numbers 460

Recursion 462

Recursion Versus Iteration 468

Creating Fractal Images 470

Computer-Generated Fractal Images 473


Drawing Lines with DrawLine() 473
The Recursive DrawBranch() Method 474

Tutorial: Generating a Fractal Image 477


Problem Analysis 477
Design 478
Development 487
Testing 495

Analysis 496

On Your Own 497

Quick Review 499

Terms to Know 500

Exercises 500

Programming Exercises 504

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Table of Contents | xv

POINTERS 511
11 Introduction 512

Basic Pointer Concepts 513


Memory Cell Addresses 514
Creating Pointer Variables 515
Accessing Data Indirectly Through Pointers 519

Pointers and Methods 522

Pointer Return Types 525

Pointers and Arrays 526

Pointer Arithmetic 528

Deleting Pointers 531

Arrays of Pointers 532

Sorting With Pointers 534


The Swap() Method 541

Tutorial: Sorting with a Pointer Array 545


Problem Description 545
Design 548
Development 557
Testing 562

On Your Own 563

Quick Review 563

Terms to Know 564

Exercises 565

Programming Exercises 569

LINKED LISTS: THE Node CLASS 573


12 The List Data Structure 574

The Problem with Arrays 575

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xvi | Programming with Visual C++: Concepts and Projects

Linked Lists 578


Creating a Linked List 580
Inserting a Node 580
Deleting a Node 582
Efficiency 583

Class Definitions 583

The Node Class 585


Constructors 587
Destructors 588

Class Diagrams 589

Class Definition Files 591


Header Files 591
Implementation Files 592

Class Definition Files and Client Code 595

Using Node Objects 596


Instantiating Node Objects 597
Accessing Node Attributes 597
Accessing static Variables 598

Tutorial: Linked List 598


Problem Description 598
Design 603
Development 611
Testing 621

On Your Own 622

Quick Review 623

Terms to Know 624

Exercises 626

Programming Exercises 629

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Table of Contents | xvii

OBJECT-ORIENTED PROGRAMMING 635


13 OOP Example 637

The Frog Class Definition 638

Instantiation and Use 639

Initializing Constructors 640

Data Hiding 642

Accessor and Mutator Methods 643

Utility Methods 645

Complete Frog Class Definition 646

Client Code 648

Tutorial: Maze Program 650


Problem Analysis 651
Mouse Class Definition 652
The Cell Class Definition 655
Design 657
Development 664

Testing 671

On Your Own 671

Quick Review 672

Terms to Know 672

Exercises 673

Programming Exercises 676

Appendix A 681

Appendix B 693

Appendix C 703

INDEX 715

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
PREFACE TO THE FIRST EDITION

This is the programmer’s friend, the black box console application. As a college student
thirty years ago, I learned how to program black boxes like this, and I have been teaching
students to do the same ever since. At least that was the case until recently, when I began
cutting back.
It is not that black boxes are bad. In fact one could make the point that they are the most
efficient way to learn programming. No fancy graphical user interface (GUI) to confuse
us. No nonstandard terminology and syntax. Just good, old-fashioned (and I do mean
old-fashioned) C++ coding.
Still, the argument that less is more, the minimalist philosophy of computer science
education, doesn’t seem to fit today. Every computer program people use, from the
Internet to the Xbox, is an interactive visual experience with a robust graphics environ-
ment. Compared to them, the black box console application is uninspiring at best. These
programs look nothing like the programs most of us actually use. ‘‘What is the point?
Why are we doing this?’’ I have been asked on more than one occasion. The traditional
answer of course is, ‘‘We are doing this because GUI programming is too difficult or
distracting for beginners. You can learn those skills in future courses.’’
However, the argument about waiting until the second or third year of programming
before learning how to create a user interface is less compelling than it once was. Visual
Basic students for example (usually novice, non-computer science majors) routinely create
elaborate GUI programs in introductory courses and have done so for years, while

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Preface to the First Edition | xix

Computer Science I (CS1) students (computer science majors) make black boxes in Java
or C++.
This book is built around the philosophy that computer programs should be inter-
esting and fun to develop at the same time that they challenge you to learn new
skills. Microsoft Visual C++ 2008 makes the construction of graphical interfaces
quick and easy. It opens up the world of Windows applications to students in a
way that still allows an introductory course to focus on the core conceptual issues.
CS1 can now go GUI.
This book is the outgrowth of several years of experimenting with Visual Studio
and Visual C++ in CS1. I thought it would be tricky integrating a GUI approach
into the course, but it was not a formidable task. No prior programming experience
is assumed. There is some nonstandard Microsoft Visual C++ terminology, but the
trade-off is that it greatly expands the programming possibilities and helps create an
educational experience that can be more enjoyable for the student and the professor.

How to Use This Book: Suggestions for Students


This book’s guided instruction method presents the step-by-step development of a
project, and then challenges students to build and enhance it. It presents key concepts
in computer science, along with methods for their implementation in each tutorial. I
hope you enjoy the projects in this book and find the inspiration to tinker with them or
create new projects based on what you learn. Programming should be challenging and
fun. Each chapter is organized into the sections listed below. Here are some suggestions
about how to best utilize the resources in each chapter.

Concepts
Each chapter starts with a discussion of important concepts and programming commands.
These are the fundamental ideas that allow you to advance your programming knowledge
and are intended to have broad application. The concepts section is not intended to
be an exhaustive reference work, but targets selected concepts that will apply to
the chapter’s main project. Each project incorporates both general computer science
concepts and implementation techniques specific to the Windows platform. The tables in
Appendix A show which concepts are covered in each chapter.

Tutorials
The second half of each chapter centers on a tutorial that demonstrates how to construct a
program that implements the concepts learned earlier. A consistent project development
strategy is used for each project. The tutorials guide you through the process required to
complete a project. Students are encouraged to experiment with their project once it is

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xx | Programming with Visual C++: Concepts and Projects

complete, to teach themselves more by venturing into new territory. An effective way to
advance learning is to be creative and to explore new possibilities using something you
already know.

On Your Own
The On Your Own section is intended to allow you to expand the capabilities of the
tutorial, using knowledge you have gained from the chapter to guide you.

Exercises
At the end of each chapter are a series of short exercises that cover both the conceptual
foundation of that project and its implementation.

Quick Review
This section lists the major concepts covered in the chapter. It is a great tool to use when
studying for an exam or just reviewing your comprehension of what you read.

Terms to Know
The important terms in each chapter appear in boldface in the text. In addition, a
complete list of them is provided at the end of the chapter. An expanded glossary
accompanies the book and is available online at www.course.com.

Programming Exercises
The exercises at the end of the chapters challenge you to build your programming
skills. You are encouraged to create at least one project from the end of each chapter.
These projects encourage you to build on your knowledge to create new applications
without telling you what to do at each step along the way. Creating your own
projects and working along with a tutorial helps solidify both the important ideas and
your knowledge of the specific Visual C++ instructions used to illustrate them. It is
quite satisfying to know that you created a program, from scratch, with minimal
assistance.

Chapter Concepts and Projects


Each of the chapters in this text introduces concepts first and then presents a tutorial. Each
chapter is described briefly below. After the chapter-by-chapter explanation, you’ll find a
figure illustrating the various projects students can create in this book.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Preface to the First Edition | xxi

Chapter 1
Chapter 1 introduces computers and computer programming. Topics include the funda-
mental components of a computer, hardware and software concepts, and the basics of
program compilation. This overview of essential terms is important to understand the
explanations in later chapters. The tutorial in Chapter 1 can be completed quickly and
easily in one 50-minute lab session.

Chapter 2
Chapter 2 presents a simple programming task involving arithmetic expressions. With the
skills acquired from the completion of the tutorial in Chapter 1, students should be able
to work on the tutorial in Chapter 2 on their own.

Chapter 3
Chapter 3 centers on integral data and the arithmetic operators integer division (/) and
mod (%). The tutorial makes use of material related to both the binary number system as
well as integer division (/) and mod (%). The instructor can consider Chapter 3 optional if
he or she prefers to move more rapidly into control structures.

Chapter 4
Chapter 4 covers selection structures in detail. The tutorial implements a vacation
reservation system similar to those used on many travel Web sites.

Chapter 5
Chapter 5 covers repetition structures. The project for this chapter generates random
numbers and processes them in a variety of ways in the context of a manufacturing
program. The more end-of-chapter programming exercises a student does in Chapters 4
and 5, the more comfortable the student will be going on to later chapters.

Chapter 6
Chapter 6 introduces the concept of a method. It also introduces graphical program-
ming using the special drawing tools to create the image of planets revolving around
a sun.

Chapter 7
Chapter 7 introduces the concept of an array and uses the data structure to construct a
color-coded student seating chart that shows the different achievement levels.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xxii | Programming with Visual C++: Concepts and Projects

Chapter 8
Chapter 8 implements a search program that demonstrates two kinds of search techni-
ques, sequential and binary. The search program is designed to locate movie names in a
video store inventory.

Chapter 9
Chapter 9 experiments with various sorting techniques and draws randomly generated
data values, in unsorted and sorted order, as a vertical bar chart.

Chapter 10
Chapter 10 explores the topic of recursion. In this chapter, students create a fractal image
and then use menu controls to change its look.

Chapter 11
Chapter 11 introduces pointers. An array of pointers is used to sort data in another array
without moving data in the second array.

Chapter 12
Chapter 12 draws linked list by requiring the programmer to create the class definition for
a node and then use that definition to create Node objects and then link them.

Chapter 13
Chapter 13 requires the student to create several class definitions and add a variety of
methods to each. In the end, a two-dimensional array is created in which a mouse runs
around looking for a piece of cheese. This project can be expanded to direct the mouse to
the cheese using walls within the maze.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Preface to the First Edition | xxiii

This Figure shows some of the tutorial programs and programming exercises the student
creates in this book.

How to Use This Book


Perhaps the most valuable parts of this book are the On Your Own sections at the end of
each tutorial and the Programming Exercises at the end of each chapter. These are
designed to reinforce the lessons learned during the tutorial and provide the opportunity
for original intellectual effort.
The topics in this book necessarily follow in consecutive order with several notable
exceptions. Chapter 3 specializes in integral data issues (integer division and mod) as well
as binary data representation. These may be too specialized for some tastes, especially for
those who wish to get on to control structures as soon as possible. In that case Chapter 3
can be skipped in favor of moving directly into Chapter 4 (selection structures). If
possible, the tutorials in Chapter 4 and Chapter 5 (loops) should be supplemented by at
least one Programming Exercise project to challenge students to create programs from
scratch and to provide extra practice with control structures.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xxiv | Programming with Visual C++: Concepts and Projects

Chapter 6 introduces instance methods and graphics objects. Both are important in later
chapters. Chapter 6 is important because it emphasizes the development of instance
methods and sets up the use of graphical programming throughout the remainder of
the text. The Chapter 6 tutorial is one of the most interesting in the book and a student
favorite; it assumes familiarity with both the sine and cosine concepts.
Chapter 7 (arrays), Chapter 8 (binary search), and Chapter 9 (sorting) are topics com-
monly addressed by CS1 textbooks. Chapter 10 (recursion), however, is a topic often
reserved for courses beyond CS1. Like Chapter 6, Chapter 10 is a student favorite, but
the topic is challenging. Skipping this chapter will not adversely affect the student’s
success with Chapters 11, 12, or 13.
Chapter 11 (pointers) is a traditional C++ topic. The tutorial is an academic exercise
designed to demonstrate pointer arrays. Chapter 12 is a way of visualizing a linked list. It
is not a fully developed abstract data type (common in CS2 courses). The project is
used as a transition from pointers to the larger, object-oriented concepts presented in
Chapter 13.
Instructors who want to drill down into C++ basics can skip Chapters 3, 10, and even 12,
substituting week-long Programming Exercise projects instead. On the other hand,
instructors who want to experience a broader range of topics and challenges can follow
the book chapter by chapter.
I have found that teaching this material is enjoyable and stimulating. I hope you will too.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
FEATURES OF THE BOOK

Over 425
color
illustrations
and diagrams
explain key
concepts.
Diagrams are
often linked to
code
examples.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Numbered algorithms
and examples are
used to show how
key concepts are
implemented.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Previews of the
interface provide a
guide to the
construction of the
tutorial program

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Screen captures
are used to show
the student exactly
what is required

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
The On Your Own
section at the end of
each tutorial
challenges students
to demonstrate their
understanding of
key concepts
covered in the
tutorial.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Quick Review
sections at the
end of each
chapter
summarize key
points

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Exercises provide
students with short skill
and knowledge tests.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Programming Exercises
provide additional ‘‘on
your own’’ skill building.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
SUPPLEMENTAL RESOURCES

The following supplemental materials are available when this book is used in a classroom
setting. All instructor teaching tools outlined below are provided to the instructor on a single
CD-ROM.

Electronic Instructor’s Manual


The Instructor’s Manual that accompanies this textbook includes:
• Additional instructional material to assist in class preparation, including suggestions
for lecture topics
• Solutions to all the end-of-chapter materials, including the Programming Exercises

ExamView
This textbook is accompanied by ExamView, a powerful testing software package that allows
instructors to create and administer printed, computer (LAN-based), and Internet exams.
ExamView includes hundreds of questions that correspond to the topics covered in this text,
enabling students to generate detailed study guides that include page references for further
review. These computer-based and Internet testing components allow students to take exams
at their computers, and save the instructor time because each exam is graded automatically.

PowerPoint Presentations
This book comes with Microsoft PowerPoint slides for each chapter. These are included as a
teaching aid for classroom presentations, either to make available to students on the network
for chapter review or to be printed for classroom distribution. Instructors can add their own
slides for additional topics that they introduce to the class.

Distance Learning
Course Technology is proud to offer online content in WebCT and Blackboard to provide
the most complete and dynamic learning experience possible. For more information on how
to bring distance learning to your course, contact your local Cengage Course Technology
sales representative.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
xxxiv | Programming with Visual C++: Concepts and Projects

Solution Files and Source Code


The solution files for all tutorials and programming exercises are available at www.course.com, as
well as on the Instructor Resources CD-ROM. The solution files also include the source
code for the tutorials and programming exercises.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
ACKNOWLEDGMENTS

I want to thank many people for their role in the production of this volume. I received great
encouragement from mentors, colleagues, and others at the University of Minnesota,
Duluth—especially Steve Holtz and others in the Department of Computer Science. I would
like to especially thank the Archibald Bush Foundation for its efforts to promote the study of
teaching and learning at the University of Minnesota and to the many faculty members in the
Bush group who provided advice, support, and encouragement.
Many thanks to the following reviewers, who provided thorough, precise, and insightful
suggestions: Kevan Croteau, Francis Marion University; Brian English, Henderson State
University; Catherine Leach, Henderson State University; Heh Miao, Tennessee State Uni-
versity; Katherine Salch, Illinois Central College; Jijun Tang, University of South Carolina;
Vitalie Volosin, Troy University; and Emily Wenk, Penn State York. I would like to extend a
special thanks to Debbie Sorrentino, Niagara County Community College, and Victor
Shtern, Boston University, for their extremely detailed and rigorous critiques of the manu-
scripts. I have benefited immensely from the work of this fine group of reviewers and
endeavored to incorporate much of their wisdom into this book.
I have learned that writing a book is a monumental team effort and would like to thank all of
those at Cengage Course Technology who made this book possible. Thanks especially to Amy
Jollymore (Acquisitions Editor) for initiating the project and overseeing it and to Alyssa Pratt
(Senior Product Manager) for actively coordinating things from the top down. This book would
never have been possible without the tireless work of Ann Shaffer, Development Editor, who
was always supportive and cheerful. A special thanks to you, Ann. I also gratefully acknowledge
the work of Erin Dowler, Content Project Manager, and Tintu Thomas, of Integra, for their
many labors in producing this volume. Thanks, also, to Nicole Ashton and John Bosco, whose
keen eyes for detail never seemed to miss anything as they tested the code for each chapter.
Finally, thanks to Mark Goodin, who served as our able and always helpful copy editor.
This book is dedicated to the people who have helped me the most. First, to my wife Debbie,
who patiently waited for me to get through this and never doubted that I would. Second, to
my parents, Don and Maxine Allert, for their many years of love and caring. Finally, to my
many past and present students, who never stop asking questions and creating interesting new
solutions to my perfectly straightforward homework problems.
Thank you all for your contributions and support.
Jim Allert

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
CHAPTER

1
I NTRODUCTION
IN THIS CHAPTER, YOU WILL:

n Learn about the fundamental concepts of object-oriented


programming
n Explore the fundamental hardware components of a computer
n Learn about the fundamental types of software
n Study important people and events in the history of computer
hardware and software development
n Learn about the program compilation process and the project
design methodology
n Explore the Visual Studio IDE
n Create your first Microsoft Visual C++ program
n Create and use TextBox and Button controls
n Write and run C++ code that responds to a button click
n Read and interpret error messages

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
2 | Chapter 1: Introduction

This chapter lays the foundation you need to write your own computer programs. It
addresses basic computer science terminology and concepts, as well as the specifics of
how to create your first program using Microsoft Visual C++ 2008. Although
computer programming may sound like a complicated undertaking, modern tools
make it easy for almost anyone to do it. This chapter will introduce you to some of
these tools. Very soon, you should be able to take what you have learned here and
create fun and useful programs that address your own interests.

Object-Oriented Programming
Visual C++ is a programming language developed by Microsoft for computers running
Windows. It is based on the standard C++ programming language. It also includes a
wide assortment of features that allow you to create visual elements with which users can
interact.
Visual C++ is one of a group of languages classified as object-oriented. Generally
speaking, an object is something with identifiable features that you may be able to
manipulate. In a computer program, an object could be something you see on the
screen, such as a button the user clicks, or it could be something within the program
that you don’t see on the screen, such as a list of student exam scores used for
computing a grade point average. An object-oriented programming language is
one in which objects are created from a specific list of instructions. These objects can
interact with the user or with other objects. Objects usually have a set of components
consisting of attributes and methods. An attribute is a characteristic feature of an
object. Often, attributes are data items, such as the size (width and height) of an object.
A method is an operation the object can perform, such as averaging a group of
numbers or changing its width and height.
All objects are constructed from a specific set of instructions, or design specifications.
Taken as a whole, the design specifications for an object are called its class definition.
Class definitions specify the object’s attributes and methods. The programs you write
in Visual C++ are really just class definitions, from which a rather large object, your
program interface, is created. The program interface is what you see when your
program runs. An interface that contains visual elements for the user to interact
with (such as buttons and menus) is called a graphical user interface (GUI). In
Visual C++, there is a more general term for the GUI object, however; it is simply
called a form.
To get a better handle on the concepts related to object-oriented programming, let’s
consider a more general example. Imagine you want to create a robot. Further,
imagine that, after you create the robot, you want to make it possible for other
people to make an identical one. You would start by devising a plan that included a

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Object-Oriented Programming | 3

rough sketch of the final product. You could also make a list of attributes this robot
should possess and the methods (operations) you would expect it to carry out, as 1
shown in Figure 1-1.

Attributes Methods

Antenna Receive
instructions

2 arms Pick things up

Face (2 eyes, Show


nose, mouth) expressions
2 feet Walk
(rubberized)

FIGURE 1-1 Rough sketch of a robot and list of attributes and methods

You could then use the sketch and the list to build the robot. Building the robot is, of
course, more complicated than what is described here, but let’s assume that you
eventually get it to work. To accomplish the second part of your plan—making it
possible for other people to build an identical robot—you would need to develop a set
of design specifications that list the required parts (for example, a box for the robot’s
body, rubber treads for the feet, etc.). The design specifications would also have to
include illustrations explaining exactly how to put the robot together. Figure 1-2 shows
a crude set of design specifications for a robot.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
4 | Chapter 1: Introduction

Feet

Rubber
treads
Circuit Board
Feet and arms should be wired to circuit board

Attach arms
here
1ft
Aluminum
housing

Cut out
eyes and mouth
Rubber
Feet go claws
here

FIGURE 1-2 Design specifications for a robot

The goal of your design specifications would be to allow anyone to create a real,
functioning robot object. Assuming people followed your specifications exactly, they
would produce a robot that looks and behaves just like your original.
Creating an object-oriented computer program is similar to designing a robot. First,
you make a rough sketch of what it will look like on the screen—that is, you sketch
the interface. As you design the interface, you must also list the attributes you feel
are important, and the methods (operations) you would like the program to
perform. Figure 1-3 shows a sample sketch as well as a list of attributes and methods
for a program.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Object-Oriented Programming | 5

1
Hello World!

Attributes Methods
green
textBox1 Display text
button1 Change colors to green
red
button2 Change colors to red

yellow button3 Change colors to yellow


button4 Change colors to blue

blue

FIGURE 1-3 Program interface and list of attributes and methods (operations)

After you create the sketch and the list of attributes like those shown in Figure 1-3, you
need to create the design specifications—or, class definition. A class definition defines the
size, location, and functionality of every control (such as buttons, textboxes or other
visual elements) placed on the form. Among other things, the class definition for a control
specifies what that control should do in response to certain events. For example, it
specifies what a button should do when the user clicks it. The part of the class definition
that tells the control what to do in response to an event is called its event-handler.
In Visual C++, as you create the interface for a program, a good part of your class
definition is automatically written for you behind the scenes by a program known as the
Windows Forms Designer. It automatically generates Visual C++ code to define many
of the properties of your controls. However, you, the programmer, must write the
instructions that go into the event-handlers. You are the one who determines how the
program will respond when the user starts interacting with the controls on the form. You
need to write the Visual C++ instructions that tell each control what to do.
When your program runs, the controls wait for certain events to occur before respond-
ing. An example of a common event is a click on a button. When the user clicks a button,
the program responds by running the Visual C++ commands, called Visual C++ code,
in the button’s click event-handler.
In this chapter’s tutorial, you will create a simple program. First, you will create the
program interface and place commonly used controls (that is, a button and a textbox) on
it. You will then write short Visual C++ instructions for the button so that when it is
clicked your program will respond by displaying a message in the textbox. Additional
tasks provided at the end of the chapter allow you to be more creative by adding

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
6 | Chapter 1: Introduction

instructions to change the color of various aspects of the interface. Before getting to these
exercises, however, we should review some basic concepts that explain what a computer
is and how it works. A firm grounding in these concepts will allow you to more fully
appreciate the programs you create.

Hardware Fundamentals
Most computers have a similar set of components, which are typically grouped into five
essential categories:
• input
• output
• processing
• memory
• storage
Input and output are fundamental operations in every computer. You are already familiar
with numerous input devices, such as a mouse, keyboard, microphone, scanner, and video
camera. Any device with the primary purpose of transmitting data to the internal memory
of a computer is classified as an input device. Any device with the primary purpose of
receiving data from a computer is considered an output device. Common output devices
include monitors and printers.
Processing is carried out by the central processing unit (CPU). Among other things, the
CPU is responsible for logical, numeric, and scheduling tasks. Modern desktop and laptop
computers carry out these tasks using microprocessor chips. A modern CPU has a complex
structure, but it is possible, to identify elements that all CPUs have in common:
• The controller unit is in charge of the transfer of data and instructions to
and from memory. It fetches instructions and decodes them so they can
be executed.
• The arithmetic logic unit (ALU) carries out logical tasks (such as compar-
isons) and the numerical tasks most often associated with computation.
• Other components include registers, which temporarily store data while
processing is taking place, and instruction position indicators, which
keep track of which tasks are up next.
Memory (often called primary storage) is responsible for storing data and instructions
when a computer is running. A computer’s memory utilizes microchips. While these are
not part of the CPU, they work in tandem with it. Most computers use a type of memory
known as random access memory (RAM), which requires the presence of an electric
current to sustain itself. When power is turned off, its contents vanish. For this reason,
RAM is often referred to as being ‘‘volatile.’’ Read-only memory (ROM) is more
expensive, but stores information for long periods of time even when the computer is
turned off.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Hardware Fundamentals | 7

Storage devices (often called secondary storage) are used to save programs and data
cheaply and efficiently outside of the computer’s main memory. Storage devices have 1
both input and output capabilities, but their primary purpose is to save information. This
includes devices such as magnetic disks (that is, hard and floppy drives), optical disks (such
as CDs and DVDs), and flash memory devices (such as USB drives).

One type of storage device, flash memory, deserves special consideration. Flash memory
is a form of storage that is chip-based, much like RAM, but is not volatile. It stores data
for long periods of time without the constant presence of an electric current. Flash
memory devices have largely replaced magnetic disks as convenient ways of storing and
transporting files. You may find them to be the best method of saving and transporting
your projects; however, you will find that it is faster to develop your projects when they are
stored on the computer’s hard drive.

The relationship between these components is shown in Figure 1-4.

CPU

Storage controller
(CD/DVD,
Hard drive) Processing
ALU

other
components

Memory

both input
Input Output
and output
devices devices
(external storage,
(keyboard, mouse) (monitor, printer)
communications)

FIGURE 1-4 The fundamental components of a computer

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
8 | Chapter 1: Introduction

History of Hardware Development


The fundamental components of a computer that we have just discussed evolved from
technological advances in a number of fields. Mechanical devices that tabulated numbers
or performed tasks in response to instructions have been around for hundreds of years.
Among the first programmable machines was a remarkable invention by French weaver
Joseph Marie Jacquard. In 1801, he devised an automated loom using sequences of
punched cards to regulate the woven patterns. The cards stored instructions, represented
as a configuration of holes, and were processed in order as the loom operator controlled
and provided power to the device by hand. Punched card technology was adapted to
mechanical tabulating devices later in the 1800s and remained popular in computing
environments through the late 1900’s, as a means of storing both program instructions
and data.
The most direct ancestors of the modern computer, however, are the various computing
‘‘engines’’ designed by British mathematician, Charles Babbage, in the 1840s. Often
called the ‘‘Father of the Computer,’’ Babbage foresaw the day when computing
machines that had all five of the components identified in the previous section (that is,
input, output, storage, memory, and central processor) could be developed. He devel-
oped his own plans for such machines. The technology of the time prevented him from
realizing their construction, but his ideas showed remarkable foresight.
Babbage enlisted the aid of Ada Lovelace (also known as the Countess of Lovelace), a
mathematician and translator who happened to be the daughter of the English poet, Lord
Byron. Babbage benefited from her suggestions on how his Analytical Engine could solve
specific mathematical problems. For this reason, she is commonly called the first computer
programmer.
These early developments laid the groundwork for the modern computer. However, the
computer as we know it was not a realistic possibility until these three crucial advances of
the 1900s:
• the invention of electronic binary methods of computing
• the development of machines that were able to store their own programs
• the advent of large-scale electronic circuitry
The first of these advances, the invention of electronic binary methods of computing, was
pioneered in the early 1940s by German engineer, Konrad Zuse (inventor of the binary,
programmable Z3 computer), and John Vincent Atanasoff and Clifford Berry at Iowa
State College in the United States (inventors of the binary, programmable ABC compu-
ter). The early binary computers represented a real conceptual leap. After all, for
human beings who have ten fingers, the most natural method of counting is a base-10
method. Early calculators and tabulating equipment were, therefore, founded on base-10
methods of numeric representation and arithmetic. However, much faster calculation
rates could be achieved through the use of binary arithmetic (that is, base-2 numbers).

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Exploring the Variety of Random
Documents with Different Content
obtain from said physician the means wherewith to commit suicide;
for should any poison be furnished or administered by physicians,
under such circumstances, the course of justice would be greatly
obstructed. Should any physician be guilty of this offence, he shall
be liable to punishment for the same.

III. Where a Physician Treats Disease under a Contract.


Where any person demands that a physician treat him for
disease, or cure his wound under a contract; after the physician has
seen the wound, or diagnosed the disease, he may undertake the
treatment of said sick person under such conditions as may be
agreed upon, and set forth in an instrument in writing.

IV. Where a Sick Person Dies, while a Physician is Treating


him under a Contract.
Where a physician undertakes the treatment of a sick person
under a contract reduced to writing, he must restore said sick person
to health; and, if the latter should die, the physician shall not be
entitled to the compensation stipulated in said contract, and no
liability shall attach to either of the parties to the same.

V. Where a Physician Removes a Cataract from the Eye.


Where a physician removes a cataract from the eye of any
person, and restores the invalid to his former health, he shall be
entitled to five solidi for his services.

VI. Where a Freeman or a Slave Dies from Being Bled.


Where a physician bleeds a patient, and the latter is greatly
weakened in consequence, said physician shall be compelled to pay
him forty solidi. If the patient should die as the result of being bled,
the physician shall be delivered up to the relatives of said patient, to
be disposed of at their pleasure. Where the patient is a slave, and is
seriously weakened, or dies, the physician must give his master
another slave of equal value, in his stead.
VII. Concerning the Compensation to be Received for the
Instruction of a Student in Medicine.
Where a physician receives a slave for the purpose of instruction
in medicine, he shall be entitled to twelve solidi by way of
compensation.

VIII. No Physician shall be Imprisoned without a Hearing.


No physician shall be imprisoned without a hearing, except in
case of homicide. Where he is charged with debt, he must provide a
surety.
TITLE II. CONCERNING THOSE WHO DISTURB SEPULCHRES.

I. Concerning Persons who Deface or Injure Tombs.


II. Where a Coffin is Removed from a Grave.

I. Concerning Persons who Deface or Injure Tombs.


Where any person injures a tomb; or robs a corpse; or strips it of
any ornaments or clothing; if he should be freeborn, he shall be
compelled to pay a pound of gold to the heirs of the deceased, and
to restore the stolen property. Where there are no heirs, he shall pay
the above-named sum to the royal treasury, and shall receive in
addition a hundred lashes. If a slave should commit this crime, he
shall receive two hundred lashes; shall be put to death by fire; and
whatever he stole shall be returned.

II. Where a Coffin is Removed from a Grave.


If anyone should steal the coffin of a dead person, for any
purpose of his own, he shall be forced, by order of the judge, to pay
twelve solidi to the heirs of the deceased. If, however, a slave should
commit this offence under the direction of his master, his master
shall at once render satisfaction for his act. Should a slave do this of
his own accord, he shall receive a hundred lashes, and shall restore
to the place, and to the body of the deceased, whatever he took
therefrom.
TITLE III. CONCERNING MERCHANTS WHO COME FROM BEYOND SEAS.

I. Where Foreign Merchants are Detected Selling Stolen Property.


II. Foreign Merchants shall be Judged by their own Magistrates, and
According to their own Laws.
III. Where a Foreign Merchant Carries Away with him, from our Kingdom, a
Person whom he has Hired.
IV. Where a Foreign Merchant takes Away a Slave for Purposes of
Commerce.

I. Where Foreign Merchants are Detected Selling Stolen


Property.
Where any foreign merchant sells gold, silver, clothing, or
ornaments of any description, for a fair price, to any of our subjects,
and said property should afterwards prove to have been stolen, the
purchaser shall incur no liability therefor.

II. Foreign Merchants shall be Judged by their own


Magistrates, and According to their own Laws.
When any legal cause of action arises between foreign
merchants, it shall not be heard by any of our judges, but by their
own, and it shall be decided according to their own laws.[52]

III. Where a Foreign Merchant Carries Away with him, from


our Kingdom, a Person whom he has Hired.
No foreign merchant shall dare to remove, to his own country, a
person hired by him, and who belongs to our kingdom. Whoever
attempts to do so, shall pay a pound of gold to the royal treasury,
and shall receive a hundred lashes in addition.

IV. Where a Foreign Merchant takes Away a Slave for


Purposes of Commerce.
If any foreign merchant should take away with him, a slave
belonging to our kingdom, for the purpose of conveying his
merchandise, he shall pay three solidi a year for his services; and, at
the termination of his contract, shall restore said slave to his master.
BOOK XII.
CONCERNING THE PREVENTION OF OFFICIAL OPPRESSION,
AND THE THOROUGH EXTINCTION OF HERETICAL SECTS.

TITLE I. CONCERNING THE EXERCISE OF MODERATION IN JUDICIAL


DECISIONS, AND THE AVOIDING OF OPPRESSION BY THOSE INVESTED
WITH AUTHORITY.

I. Concerning the Admonition of the King, by which Judges are Ordered to


Display Moderation in the Administration of Justice.
II. No Official, Invested with Power Over the People and Supervision Over
their Acts, shall Subject them to Unnecessary Expense, or Other
Impositions.

I. Concerning the Admonition of the King, by which Judges


are Ordered to Display Moderation in the Administration of
Justice.
It is but proper that we, who impose necessary penalties for the
misconduct of men, should render aid to the unfortunate, by means
agreeable to God. We, therefore, order all judges and other officials
to whom has been delegated the power of dispensing justice, and
we also admonish them in the name of the omnipotent God, the
exemplar of all virtues, that they diligently use their skill in the
discovery of truth, in every case which is brought before them; and
that they examine, with the utmost care, the claims of the parties to
each action, without regard to the rank or condition of said parties;
and that they moderate, in some degree, the severity of the law,
where parties have lost their cases, especially where said parties are
oppressed by poverty; for if the authority of the law were enforced to
the utmost in every instance, there would be no opportunity for the
exercise of mercy.

II. No Official, Invested with Power Over the People and


Supervision Over their Acts, shall Subject them to Unnecessary
Expense, or Other Impositions.
We provide laws for all the subjects of our kingdom who are
under our sovereignty, for no other reason than the protection of their
interests, and to the end that they may not be subjected to
unnecessary expense or injury. For who is more concerned in the
administration of justice, or who should be more familiar with it than
ourselves, who, in the various affairs of life, extend the hand of
assistance to our faithful subjects, and aid those whom we rule with
equity? We therefore decree, by the following law, that no governor
of a city, deputy, or other official, shall presume to oppress the
people, for his own benefit, by means of any taxes, exactions,
labors, or journeys; or shall accept unnecessary donations of grain
from a city or a province; for we are well aware that when we appoint
judges, we, at the same time, provide them with the means of
subsistence. In like manner, we admonish governors of provinces,
those in charge of the royal demesnes, and the officials of our
treasury, that they have no power over private persons, and shall not
in any way molest them. But where a private person has a lawsuit
against any of the slaves of the Crown, the public agent, or attorney
of the province, having been notified of the fact, shall cause the
matter to be brought before the governor, or the judge of the district,
and shall present his case, in order that the action may be legally
determined, and such amends made as are equitable.
In order that proper supervision may be exercised over the royal
officials in charge of our domains, we have agreed that the tax
collectors and defensores shall be changed every year; and, as we
are well aware that in consequence of this, much injury results to our
people, we hereby decree that any tax collector or defensor, who
has been elected by the bishops or the people, shall serve the full
term for which he was chosen. Where any tax collector or defensor
has been appointed, he shall not give any present to a judge, nor
shall a judge presume to accept or exact anything from him. If any
judge should violate this law, he shall be deprived of his office, and
shall be compelled to pay ten pounds of gold to the royal treasury.
Should the priests, whom we address with God as our witness, learn
of any misconduct of judges, or of other officials, and not bring the
same to our notice, they shall be liable to the sentence imposed by
the council, and shall be compelled to make reparation from their
own property for such losses as the poor may have suffered through
their silence.
TITLE II. CONCERNING THE ERADICATION OF THE ERRORS OF ALL
HERETICS AND JEWS.

I. Laws Having Been Given to True Believers, it is Now Necessary to Place


Restraints upon Infidels.
II. Concerning the Renunciation of the Errors of all Heresies.
III. Concerning the Laws Promulgated on Account of the Wickedness of the
Jews.
IV. Concerning the Extirpation of the Errors of the Jews in General.
V. Jews shall not Celebrate the Passover According to their Custom.
VI. Jews shall not Contract Marriage According to their Custom.
VII. Jews shall not Perform the Rite of Circumcision.
VIII. Jews shall not Divide their Food into Clean and Unclean, According to
their Custom.
IX. No Jew shall Subject a Christian to Torture.
X. No Jew shall Testify Against a Christian; and Under what Circumstances
the Descendants of Jews may Testify.
XI. No Jew shall Circumcise a Christian Slave.
XII. Concerning the Penalties to be Inflicted for Offences Committed by Jews.
XIII. Concerning Christian Slaves who are Known to have been Sold or
Liberated by Jews.
XIV. Under no Circumstances shall Christian Slaves Attach themselves to
Jews, or be Admitted into their Sect.
XV. All Christians are Forbidden to Defend or Protect a Jew, by Either Force
or Favor.
XVI. Memorial of the Jews Presented to the King.
XVII. Concerning Judaizing Christians.
XVIII. Concerning the Perfidy of the Jews.

THE GLORIOUS FLAVIUS RECESVINTUS, KING.


I. Laws Having Been Given to True Believers, it is Now
Necessary to Place Restraints upon Infidels.
Hitherto, we have directed our steps cautiously through the
arduous paths which traverse the iniquities of the Jews; and have
used moderation in the restraint of human crimes and infirmities. For
it has been our manifest purpose and task, both to remove ill-
founded opinions, and to prohibit what is evil, as well as to abolish
what has been wrongfully done, and is abhorrent to decency and
honor. As the law penetrates the secret recesses of minds conscious
of guilt, so its censure corrects the depravity of morals, and prevents
the perpetration of crime. And, indeed, we do not attempt to bring
about this purity of soul for any other purpose than for the sake of
the Church of the living God, which has invested so many different
nations and peoples with the robe of immortality, and has united
them to herself with the bonds of one holy religion. For the
excellence of our strength and earthly glory are derived from the
virtues of God, and his influence, sometimes acting through
compassion, sometimes through fear of the sword of justice,
prevents the commission of sin; and on one occasion diminishes
crime by the practice of moderation, on another, extirpates it by an
exhibition of severity. Following, not only the example of noble and
illustrious races who restrained the illegal excesses of the people by
leniency and rational laws, but also copying the rules and imitating
the example of the Holy Fathers throughout the entire globe of the
earth, we shall endeavor, as far as lies in our power, to reduce to
action the precepts which we have received from them. For this
reason, our relatives and subjects will know that our decrees are
suitable, and dictated by honesty of purpose, in that they forbid the
commission of crime, and are not opposed to the opinions of the
Holy Fathers heretofore promulgated. And we are confident that we
shall receive two rewards from the generosity of God: one, that we
will be permitted to remain in the enjoyment of peace with our
neighbors, as we are now; and the other, that, when our rule is
ended, we shall receive a due acknowledgment from heaven. Thus,
when, by means of the laws directed to our faithful people, this
salutary remedy shall have been administered to the adherents of
the Holy Faith, (as medicine is absorbed by the members of the
body), and peace and charity shall everywhere prevail; confiding in
the virtue of God, we shall attack his enemies, pursue his rivals, and
conquer his adversaries; contending manfully, and constantly
persevering; dispersing and overcoming those enemies, as dust is
driven by the wind, or as mud is dried up in the fields, we shall
acquire the reward of Faith; and when we shall include all people as
true believers in our holy religion, and shall bring all infidels to belief
in its truths, our glory shall increase, and our kingdom shall be
exalted.[53]
FLAVIUS RECESVINTUS, KING.
II. Concerning the Renunciation of the Errors of all Heresies.
The eternal counsel of Almighty wisdom and Divine piety, as we
understand it, and revealed to us in former ages, for the benefit of
our own times, dissipated the errors of perfidious heretics, as well as
abolished the false maxims of impious doctrines. Nevertheless, that
such a time may not come during our lives, as that of which the
representative of Divine Grace formerly said: “A time will come when
persons will not desire sound doctrine, but with eager ears, and
according to their desires, will seek masters for themselves; and who
will not listen to the truth, but will turn to false doctrines; and, as it is
proper that whatever remains in the light of the Faith should be
defended, by legal edicts, from the efforts of all who seek to
contradict it; and that whatever ideas have arisen through the
influence of error, be removed by legal proceedings; therefore, we
decree that no man of whatever race or lineage, either native or
foreigner, proselyte or old in faith, visitor or resident, shall openly or
silently, impugn the unity of the Catholic faith; or take part in any
injurious disputes affecting the truth of said faith; or countenance the
same by remaining silent.” No one shall attack the decrees of the
Gospel, or criticise the institutions of the Church, or call in question
the sacred institutions established by the ancient Fathers; no one
shall treat with contempt discussions concerning points of doctrine
which arise in modern assemblies; no one shall entertain any
thoughts against the holy edicts or the true religion, or shall utter any
words in depreciation of the same; or perfidiously cause a
controversy to arise with an obstinate unbeliever; or engage in a
quarrel on account of the contempt of honor exhibited by a listener.
Any person who violates any of the provisions aforesaid shall be
arrested; and should he be an ecclesiastic, or belong to any religious
order, he shall lose his rank and dignity; shall be regarded forever as
a criminal; and shall be punished by the loss of all his property. If he
should belong to the laity, he shall be deprived of honor and position,
and stripped of all his possessions. Every violator of this law shall be
condemned to perpetual exile, unless he should be converted from
his errors by the interposition of Divine mercy, when he may be
suffered to remain and live in accordance with the commands of
God.
FLAVIUS RECESVINTUS, KING.
III. Concerning the Laws Promulgated on Account of the
Wickedness of the Jews.
The execrable errors of heretics in general, having been already
prohibited and disposed of, it now becomes our duty to make special
provision for some that exist in our days, and of which we are, at
present, well aware. For while the virtue of God, by the sword of his
Word, extirpated all other heresies, root and branch, we have to
lament that the soil of our kingdom is still only defiled by the infamy
of the Jews. Therefore, to the end that we may establish peace in
our realm, by the spirit of God (which, indeed, seems folly to pagans,
and scandal to the Jews themselves), we, who believe in the virtues
of Christ, and the wisdom of God, for the sake of whose
commiseration we attempt, with pious intentions, to put an end to
ancient errors, that others may not arise in future ages; decree by
this law, which shall be forever observed, and by the mandate of the
Holy Scriptures, that our edicts, as well as those promulgated by our
royal predecessors against the perfidy and persons of the Jews,
shall be forever inviolate, and shall be obeyed for all time. And if
anyone should violate said laws, he shall be liable for the damages
provided by them, and to the punishments especially prescribed for
their infraction.
FLAVIUS RECESVINTUS, KING.
IV. Concerning the Extirpation of the Errors of the Jews in
General.
No Jew who has received the sacred rite of baptism shall
renounce the faith of the holy Christian religion, or blaspheme said
faith, in any way. No Jew shall impugn its precepts by deed or word;
or speak insultingly of it either secretly or openly. No Jew shall flee to
avoid being received into the Church, or conceal himself for such a
purpose, after having taken to flight. No Jew shall entertain the hope
of resuming his errors, or of performing the ceremonies of his
infamous belief. No Jew shall entertain in his heart any perfidy
against the Christian religion, and in favor of his own sect, or exhibit
such perfidy by word or deed. No Jew shall attempt to infringe, or
oppose, any regulations or laws of the Christians which have been
published. No one shall venture to conceal a Jew who is aware of
the existence of these offences which have been prohibited, or who
has committed them. No one shall delay to denounce a fugitive Jew
when he is found, or to reveal his hiding place. Any person who
violates the provisions of the aforesaid law, shall be subjected to the
punishment prescribed for the same.

V. Jews shall not Celebrate the Passover According to their


Custom.
No Jew shall celebrate the Passover upon the fourteenth day of
the month, nor shall perform any of the ceremonies customary at
such times. Nor shall any Jew, in honor of his ancient, erroneous
belief, observe any festival days, great or small; or attempt their
observance; or desist from labor upon any holidays; or hereafter
keep the Sabbath, or any other sacred days prescribed by his rites,
or attempt to do so. Anyone detected violating this law shall be liable
to the condemnation and penalty prescribed for the same.

VI. Jews shall not Contract Marriage According to their


Custom.
No Jew shall marry, or defile with adultery or incest, anyone
nearly related to him by blood. No Jew shall marry another within the
seventh degree of relationship; nor shall he desire or practice any
other nuptial ceremony than that customary among Christians.
Whenever detected, he shall be punished according to law.

VII. Jews shall not Perform the Rite of Circumcision.


No Jew shall circumcise another; nor shall a person who has
permitted himself to be circumcised be exempt from the operation of
the law. No slave, freeborn person, or freedman, native or foreigner,
shall practise or submit to this detestable operation. Whoever is
proved to have voluntarily performed, or submitted to it, shall be
punished with the utmost severity of the law.

VIII. Jews shall not Divide their Food into Clean and Unclean,
According to their Custom.
The blessed apostle Paul said, “To the pure all things are pure,”
but nothing is pure to those who are defiled, because they are
unbelievers; and, for this reason, the execrable life of the Jews and
the vileness of their horrible belief, which is more foul than any other
detestable error, must be destroyed and cast out. Therefore, no Jew
shall make a distinction between food which is clean and unclean, as
established by the customs and traditions of his ancient rites. No one
shall perversely refuse to eat food of any kind, whose condition is
proved to be good. No one shall reject one article of food, and
accept another, unless the distinction be such as is considered
salutary and proper by all Christians. Anyone detected in the
violation of this law shall be subjected to the punishment instituted
for the same.

IX. No Jew shall Subject a Christian to Torture.


We especially decree, by the following law, that it shall not be
lawful for any Jew to testify against a Christian in any legal
proceeding, or business transaction, even though said Christian
should be of the lowest rank or a slave; nor shall a Jew prosecute a
Christian, in any action at law; or sue him upon any written contract;
or subject him to torture for any reason whatever. For it seems
sacrilegious to prefer an infidel to him who is a believer, and to
subject the members of the followers of Christ to torture inflicted by
his adversaries. If, however, Jews should have causes of action
among themselves, they shall have the right, under the law, to testify
against each other; and to put their slaves to the torture in the
presence of Christian judges.

X. No Jew shall Testify Against a Christian; and Under what


Circumstances the Descendants of Jews may Testify.
If he who is convicted of having uttered a falsehood becomes
infamous in the sight of all men, with how much more reason should
he be excluded from giving testimony who denies the truth of the
Divine Faith? Jews, whether baptized or unbaptized, are therefore
forbidden to testify against Christians. The descendants of Jews,
however, if they are of good morals, and adherents of the Faith, shall
be permitted to give evidence among Christians; but not unless their
morals and their belief shall be vouched for by either the king, a
priest or a judge.

XI. No Jew shall Circumcise a Christian Slave.


It shall not be lawful for a Jew to purchase a Christian slave, or to
accept of one as a gift. Should a Jew purchase such a slave or
accept of him as a gift and then circumcise him, he shall lose the
price of said slave, and the latter shall be free. The Jew who
circumcises a Christian slave shall forfeit all his property to the king.
Any slave of either sex who is unwilling to become a Jew, shall
receive his or her freedom.

XII. Concerning the Penalties to be Inflicted for Offences


Committed by Jews.
The following law is derived from others of great severity, which
have been enacted to punish the perfidy of the Jews; and it is hereby
decreed that whoever attempts to commit any of the crimes
prohibited by former laws, or contained in any amendments to the
same, or presumes to act in defiance of said laws, shall be either
stoned to death, or burned by such of his own countrymen as may
have entered into an agreement to do so. However, if the king, in his
mercy, should decide to spare the life of such a criminal, he shall be
delivered up as a slave to whomever the king may select, and all his
property shall be given to others; and this shall be done in such a
way that the culprit can never come into possession of his property
again, or recover his liberty in the future.

XIII. Concerning Christian Slaves who are Known to have


been Sold or Liberated by Jews.
To the most holy and blessed Agapius and Cecilius, bishops, and
to the judges of their districts, as well as to other ecclesiastics and
magistrates, of the provinces of Barbia, Ausgia, Sturgia, Viatula,
Tutigia, Gabrus, and Epagrus, greeting: The authority of the law
promulgated by our lord and predecessor, Recaredus, declaring that
Christian slaves shall under no circumstances remain in the power of
Jews, would be sufficient, if the depravity of the Jews had not
afterwards corrupted the minds of princes, and they had not
demanded and obtained benefits for themselves contrary to the
principles of justice. And that we may, with the assistance of God,
promulgate a law by which these frauds may hereafter be abolished,
and for the reason that, in past times, the edict of said king has been
nullified, we hereby decree: that if any Christian slave should be in
the possession of a Jew after this law is published, whether said
slave should have been set free or not, he shall have the same right
as a Roman citizen. And if said slave, through any unlawful act,
should have been transferred to the possession of any other person
by an instrument in writing, when he should have been liberated
according to law, he shall be given his liberty; the contract shall be
cancelled; the price paid for him shall be returned to the vendor; and
said slave shall have a right to pass his life in freedom, supported by
his own labor, have his name inscribed upon the public records, and
be taxed according to an equitable estimate of his property.
If any slaves should have been acquired by any just title, after the
time in which the law of said king was promulgated, their masters
shall have the right, until the Kalends of July, to sell, or liberate said
slaves, as they choose. Any Christian slaves who have been
circumcised by the Jews, at any time, or have joined their sect, shall
be punished as prescribed by law. Where such slaves as we have
declared to be free, are again reduced to slavery by the Jews, or are
retained by them, without being emancipated; the Jews, guilty of
such offences, shall be punished as in the case of freemen, where
the latter are restrained of their liberty. All Jews who have been
converted to the Holy Faith, shall be entitled to their share in the
inheritance of their fathers.
Where sales have been made of slaves at a certain time, in the
division of the same there shall be no separation of parents and
children, but all shall be transferred together to the purchaser. Where
a Jew has been proved to have obtained property by fraud, from the
ancestors of any person, he shall be deprived of it, and it shall be
forfeited to the royal treasury. Any slaves belonging to the Jews, who
have been baptized, shall, with their children, be returned to their
masters, and be liberated by them; and any property they may have
acquired shall be given them along with their freedom. Those who
have no property shall be aided by the person who sets them free,
as far as he is able to do so; and said emancipated slaves shall be
classed as other freedmen, and shall be taxed in proportion to the
property they own.

XIV. Under no Circumstances shall Christian Slaves Attach


themselves to Jews, or be Admitted into their Sect.
We provide for the health and safety of our subjects, and of all
other persons within the provinces of our kingdom, when we rescue
the adherents of our religion from the hands of infidels. For, by this
means, the orthodox faith will be greatly exalted, when the execrable
perfidy of the Jews shall no longer have power over Christians. The
fatal control of Jews over Christians should therefore be abominated,
and the people consecrated by the favor of God brought under the
influence of Divine Love. Therefore, we promulgate the following law,
to be forever obeyed, and admonish every royal officer, in all future
times: that, from the first year of our reign no Jew shall be permitted
to have a freeborn Christian, or a Christian slave, under his
patronage, or in his service. Nor shall a Jew be allowed to employ
any such person for hire, or avail himself of his services, under any
pretext whatsoever. A Jew shall, however, be permitted to sell his
slave, for a just price, to a Christian, under proper circumstances,
anywhere he resides within the limits of our kingdom. It shall not be
lawful to sell such slaves in foreign countries, unless it should be
proved that said slaves reside there. Where slaves sold by Jews into
foreign countries, as aforesaid, have no property of their own, the
vendor shall give to said slaves such sums as, in the opinion of the
purchaser, will be sufficient for supporting and clothing them; and
this is provided in order that a transaction concluded under the name
of purchase, may not appear to be exile.
Where a Jew wishes to free a Christian slave, he must do so in
such a way that the latter may attain the rank of a Roman citizen, to
wit: that, by the act of emancipation, no services shall be reserved
for the benefit of any Hebrew, or of anyone else; and that said
liberated slave may have the power to pass his life wherever he
chooses, free from all obligation to, or association with, the Jews. If,
however, any Hebrew should fraudulently sell or liberate a slave, and
evidence of said illegal act should be proved at any future time, and
any damage to the slave should result; where a freeborn person
exposes such a fraudulent transaction, he shall be entitled to all the
property of the parties, both vendor and purchaser, who perpetrated
the fraud. Should a Christian be concerned in such a proceeding, he
shall be given as a slave to whomever the king may direct; and
where he has property, half of it shall be confiscated for the benefit of
the public treasury, and the offender shall be branded with eternal
infamy. Should a slave detect a fraud of this kind, he shall be given
his freedom, and shall remain under the patronage of him in whose
service he was until that time; and in order that exact justice may be
done, the master of said slave shall receive another from the Crown
in his stead, and, in addition, shall be entitled to a pound of gold from
him whose deceit was exposed by the slave.
Where a Hebrew circumcises a Christian, or induces one to join
his sect, or perform any of his rites, he shall be beheaded; the
informer shall receive a proper reward; and the property of said Jew
shall be forfeited to the royal treasury. All slaves who are known to
be the issue of marriages between Christians and Jews, we hereby
declare shall be made Christians. And if such slaves as have been
converted to the Jewish religion should desire to remain in that
perfidious belief, and and should refuse to return to the true faith,
they shall be scourged, and scalped, in the presence of the
assembled people, and delivered up to whomever we may select, to
remain in perpetual servitude. Where the unlawful marital unions
hereinbefore mentioned have already taken place, we hereby decree
that the infidel party to the same shall have a right to embrace the
true faith, should he or she desire to do so. Should, however, said
party refuse, the marriage shall be dissolved, and the recalcitrant
person shall be driven into perpetual exile. To the other provisions of
this law we add the following: that whenever any Jew desires
sincerely to embrace the Catholic faith, and has been purified by the
holy water of baptism, he shall be entitled to retain, without
molestation, all the property which he possessed at that time.
This edict we declare shall be in force, and shall be observed by
all our subjects throughout our dominions, after the Kalends of July
of the present year. If, after said date, a Christian slave should be
found in the possession of a Jew, half the property of said Jew shall
be forfeited for the benefit of the royal treasury, and said slave shall
be set at liberty; nor shall any Jew have any claim to the person or
property of said slave thereafter.
The aforesaid law which we, induced by piety and religion, have
framed for the benefit of our people and ourselves, we hereby
decree, with the aid of God, shall be forever valid. And may Christ,
the Conqueror, make all our successors, guardians of this law,
victorious, and confirm in the enjoyment of His kingdom those who
He knows will faithfully enforce it. While we are not of the opinion
that its provisions will be violated by anyone; nevertheless, should
such a person exist, may he who audaciously disobeys it, or does
not reverently observe it, be regarded by all men as the most
infamous person of the century; may he lose his life at the moment
when he forms the detestable resolution to break said law; and may
he be oppressed by the accumulated mass of his sins through all
eternity, inasmuch as, by his transgression, he has infringed this
salutary decree. And, in the terrible time of the Day of Judgment,
reserved for the coming of the Lord, may the said culprit be
separated from the flock of Christ; and, placed at the left hand with
the Jews, be burned with eternal fire, with the devil for his
companion; in order that avenging punishment may be inflicted upon
all transgressors, and that true Christians may receive a rich and
eternal reward.
XV. All Christians are Forbidden to Defend or Protect a Jew,
by Either Force or Favor.
To the former laws, which we, and our predecessors, have
promulgated for the purpose of annihilating the perfidy of the Jews, it
becomes necessary to add the following one to sanction and
strengthen those which have been heretofore published. Now, after
we have repudiated the profane enemies of the Holy Faith, and put
an end to the wicked schemes of these perfidious wretches, it
becomes necessary for us to confirm those things which have
already been done, and arrange them suitably and in order; for, in
the exact proportion as the skilful artificer gives form to the invention
of his genius, so, in just such proportion does his work disclose the
strength and beauty of his mind.
Therefore, lest the Jews should, by means of any artifice, and
through their unremitting perseverance, obtain the legal sanction for
their profane rites so much desired by them, we hereby decree that
no person belonging to any religious order or rank whatsoever, or
any of the royal officials, of high or low degree, or any individual of
any station or family, or any prince, or person in authority, shall
encourage any Jew, whether baptized or not baptized, to remain in
the practice of his detestable faith and customs; or shall conceal the
fact that he is doing so; or shall induce those who have been
baptized to return to the observance of their perfidious ceremonies.
No one shall attempt, under any pretext, to defend such persons in
the continuance of their depravity, even should they be under his
patronage. No one, for any reason, or in any manner, shall attempt
by word or deed, to aid or protect such persons, either openly or
secretly, in their opposition to the Holy Faith and the Christian
religion.
If any bishop or other ecclesiastic should be guilty of such an
offence, or if any member of the laity should be convicted of the
same, he shall be excluded from the society of Christians, be
excommunicated, and forfeit the fourth of all his property, which shall
be confiscated for the benefit of the royal treasury. For it is eminently
proper that those should be separated from the communion of the
faithful, and be punished by the loss of their possessions, who reject

You might also like