100% found this document useful (1 vote)
69 views

(Ebook) C++ Programming: From Problem Analysis to Program Design, 5th by D. S. Malik ISBN 9780538798082, 0538798084 2024 Scribd Download

The document provides information on various C++ programming ebooks authored by D. S. Malik, including details on their ISBNs and links for downloading. It highlights the fifth edition of 'C++ Programming: From Problem Analysis to Program Design' and lists additional related titles. The document also includes a brief overview of the contents and structure of the C++ programming book.

Uploaded by

shiehpalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
69 views

(Ebook) C++ Programming: From Problem Analysis to Program Design, 5th by D. S. Malik ISBN 9780538798082, 0538798084 2024 Scribd Download

The document provides information on various C++ programming ebooks authored by D. S. Malik, including details on their ISBNs and links for downloading. It highlights the fifth edition of 'C++ Programming: From Problem Analysis to Program Design' and lists additional related titles. The document also includes a brief overview of the contents and structure of the C++ programming book.

Uploaded by

shiehpalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) C++ Programming: From Problem Analysis to


Program Design, 5th by D. S. Malik ISBN
9780538798082, 0538798084

_____ Click the link below to download _____


https://ebooknice.com/product/c-programming-from-
problem-analysis-to-program-design-5th-2336846

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) C++ Programming: From Problem Analysis to Program Design by D.


S. Malik ISBN 9781133626381, 1133626386

https://ebooknice.com/product/c-programming-from-problem-analysis-to-
program-design-4334672

ebooknice.com

(Ebook) C++ Programming: From Problem Analysis to Program Design by D.


S. Malik ISBN 9781337102087, 1337102083

https://ebooknice.com/product/c-programming-from-problem-analysis-to-
program-design-7031230

ebooknice.com

(Ebook) C++ programming : from problem analysis to program design by D


S Malik ISBN 9781423902096, 1423902092

https://ebooknice.com/product/c-programming-from-problem-analysis-to-
program-design-4700604

ebooknice.com

(Ebook) Java Programming: From Problem Analysis to Program Design, 4th


Edition by D. S. Malik ISBN 1439035660

https://ebooknice.com/product/java-programming-from-problem-analysis-
to-program-design-4th-edition-2365278

ebooknice.com
(Ebook) Java(TM) Programming: From Problem Analysis to Program Design
by D. S. Malik ISBN 9781111530532, 111153053X

https://ebooknice.com/product/java-tm-programming-from-problem-
analysis-to-program-design-2271130

ebooknice.com

(Ebook) Java programming : from problem analysis to program design by


D S Malik ISBN 9781111530532, 9781111577643, 111153053X, 1111577641

https://ebooknice.com/product/java-programming-from-problem-analysis-
to-program-design-4130342

ebooknice.com

(Ebook) C++ Programming: Program Design Including Data Structures, 5th


Edition by D. S. Malik ISBN 9780538798099, 0538798092

https://ebooknice.com/product/c-programming-program-design-including-
data-structures-5th-edition-2476526

ebooknice.com

(Ebook) C# Programming: From Problem Analysis to Program Design by


Barbara Doyle ISBN 1423901460

https://ebooknice.com/product/c-programming-from-problem-analysis-to-
program-design-2444624

ebooknice.com

(Ebook) C# Programming: From Problem Analysis to Program Design by


Barbara Doyle ISBN 9781285096261, 1285096266

https://ebooknice.com/product/c-programming-from-problem-analysis-to-
program-design-4178294

ebooknice.com
C++ PROGRAMMING:
FROM PROBLEM ANALYSIS TO PROGRAM DESIGN

FIFTH EDITION

D.S. MALIK

Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States
C++ Programming: From Problem Analysis
to Program Design, Fifth Edition For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
D.S. Malik For permission to use material from this text or product, submit
all requests online at www.cengage.com/permissions
Executive Editor: Marie Lee
Further permissions questions can be emailed to
Acquisitions Editor: Amy Jollymore permissionrequest@cengage.com
Senior Product Manager: Alyssa Pratt
Editorial Assistant: Zina Kresin Library of Congress Control Number: 2009942948
Content Project Manager: Matthew ISBN-13: 978-0-538-79808-2
Hutchinson
ISBN-10: 0-538-79808-4
Art Director: Faith Brosnan
Print Buyer: Julio Esperas Course Technology
20 Channel Center Street
Cover Designer: Roycroft Design/
Boston, MA 02210
www.roycroftdesign.com
USA
Cover Photo: ª Guntmar Fritz/Masterfile
Some of the product names and company names used in this
Proofreader: Green Pen QA book have been used for identification purposes only and may
Indexer: Elizabeth Cunningham be trademarks or registered trademarks of their respective
Compositor: Integra manufacturers and sellers.
Any fictional data related to persons or companies or URLs used
throughout this book is intended for instructional purposes only.
ª 2011 Course Technology, Cengage Learning At the time this book was printed, any such data was fictional
ALL RIGHTS RESERVED. No part of this work and not belonging to any real persons or companies.
covered by the copyright herein may be Course Technology, a part of Cengage Learning, reserves the
reproduced, transmitted, stored or used in any right to revise this publication and make changes from time to
form or by any means graphic, electronic, or time in its content without notice.
mechanical, including but not limited to
photocopying, recording, scanning, digitizing, The programs in this book are for instructional purposes only.
taping, Web distribution, information They have been tested with care, but are not guaranteed
networks, or information storage and retrieval for any particular intent beyond educational purposes. The
systems, except as permitted under Section author and the publisher do not offer any warranties or
107 or 108 of the 1976 United States Copyright representations, nor do they accept any liabilities with respect
Act, without the prior written permission of to the programs.
the publisher. 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:
www.cengage.com/global
Cengage Learning products are represented in Canada
by Nelson Education, Ltd.
To learn more about Course Technology, visit
www.cengage.com/coursetechnology
Purchase any of our products at your local college store or at
our preferred online store www.CengageBrain.com

Printed in the United States of America


1 2 3 4 5 6 7 16 15 14 13 12 11 10
TO

My Daughter

Shelly Malik
This page intentionally left blank
B RIEF C ONTENTS

1. An Overview of Computers and Programming Languages 1

2. Basic Elements of C++ 27

3. Input/Output 117

4. Control Structures I (Selection) 175

5. Control Structures II (Repetition) 247

6. User-Defined Functions I 319

7. User-Defined Functions II 361

8. User-Defined Simple Data Types, Namespaces,


and the string Type 433

9. Arrays and Strings 485

10. Applications of Arrays (Searching and Sorting)


and the vector Type 563

11. Records (structs) 611

12. Classes and Data Abstraction 649

13. Inheritance and Composition 723

14. Pointers, Classes, Virtual Functions, and Abstract Classes 793

15. Overloading and Templates 861

16. Exception Handling 951

17. Recursion 991


vi | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

18. Linked Lists 1023

19. Stacks and Queues 1115

APPENDIX A Reserved Words 1215

APPENDIX B Operator Precedence 1217

APPENDIX C Character Sets 1219

APPENDIX D Operator Overloading 1223

APPENDIX E Additional C++ Topics 1225

APPENDIX F Header Files 1247

APPENDIX G Memory Size on a System and Random


Number Generator 1257

APPENDIX H Standard Template Library (STL) 1259

APPENDIX I Answers to Odd-Numbered Exercises 1301

INDEX 1331
TABLE OF C ONTENTS

Preface xxvii

AN OVERVIEW OF COMPUTERS AND PROGRAMMING


1 LANGUAGES 1
Introduction 2

A Brief Overview of the History of Computers 2

Elements of a Computer System 3


Hardware 4
Central Processing Unit and Main Memory 4
Input /Output Devices 5
Software 6

The Language of a Computer 6

The Evolution of Programming Languages 8

Processing a C++ Program 10

Programming with the Problem


Analysis–Coding–Execution Cycle 12

Programming Methodologies 20
Structured Programming 20
Object-Oriented Programming 20

ANSI/ISO Standard C++ 22

Quick Review 22

Exercises 23
viii | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

BASIC ELEMENTS OF C++ 27


2 A C++ Program 28
The Basics of a C++ Program 31
Comments 32
Special Symbols 32
Reserved Words (Keywords) 33
Identifiers 33
Whitespaces 34
Data Types 35
Simple Data Types 35
Floating-Point Data Types 38

Arithmetic Operators and Operator Precedence 39


Order of Precedence 43

Expressions 44
Mixed Expressions 45

Type Conversion (Casting) 47

string Type 49
Input 50
Allocating Memory with Constants and Variables 50
Putting Data into Variables 53
Assignment Statement 53
Saving and Using the Value of an Expression 56
Declaring and Initializing Variables 57
Input (Read) Statement 58
Variable Initialization 61

Increment and Decrement Operators 65


Output 67
Preprocessor Directives 75
namespace and Using cin and cout in a Program 76
Using the string Data Type in a Program 76

Creating a C++ Program 77

Debugging: Understanding and Fixing Syntax Errors 80


Table of Contents | ix

Program Style and Form 84


Syntax 84
Use of Blanks 85
Use of Semicolons, Brackets, and Commas 85
Semantics 85
Naming Identifiers 85
Prompt Lines 86
Documentation 87
Form and Style 87

More on Assignment Statements 89

Programming Example: Convert Length 91

Programming Example: Make Change 94

Quick Review 98

Exercises 100

Programming Exercises 109

INPUT/OUTPUT 117
3 I/O Streams and Standard I/O Devices 118
cin and the Extraction Operator >> 119

Using Predefined Functions in a Program 124


cin and the get Function 127
cin and the ignore Function 128
The putback and peek Functions 130
The Dot Notation between I/O Stream Variables
and I/O Functions: A Precaution 132

Input Failure 133


The clear Function 135

Output and Formatting Output 137


setprecision Manipulator 137
fixed Manipulator 138
showpoint Manipulator 139
setw 142
x | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Additional Output Formatting Tools 144


setfill Manipulator 144
left and right Manipulators 146

Input/Output and the string Type 148

Debugging: Understanding Logic Errors


and Debugging with cout Statements 149

File Input/Output 152

Programming Example: Movie Tickets Sale


and Donation to Charity 156

Programming Example: Student Grade 162

Quick Review 165

Exercises 166

Programming Exercises 170

CONTROL STRUCTURES I(SELECTION) 175


4 Control Structures 176

Relational Operators 177


Relational Operators and Simple Data Types 178
Comparing Characters 179
Relational Operators and the string Type 180

Logical (Boolean) Operators and Logical Expressions 182


Order of Precedence 184
int Data Type and Logical (Boolean) Expressions 187
bool Data Type and Logical (Boolean) Expressions 188

Selection: if and if...else 188


One-Way Selection 189
Two-Way Selection 191
Compound (Block of) Statements 195
Multiple Selections: Nested if 195
Comparing if...else Statements with a Series of
if Statements 198
Short-Circuit Evaluation 199
Table of Contents | xi

Comparing Floating-Point Numbers for Equality:


A Precaution 200
Associativity of Relational Operators: A Precaution 201
Avoiding Bugs by Avoiding Partially Understood
Concepts and Techniques 203
Input Failure and the if Statement 206
Confusion between the Equality Operator (==) and
the Assignment Operator (=) 209
Conditional Operator (?:) 211
Program Style and Form (Revisited): Indentation 211

Using Pseudocode to Develop, Test, and Debug a Program 212

switch Structures 215


Avoiding Bugs by Avoiding Partially Understood Concepts and
Techniques (Revisited) 221

Terminating a Program with the assert Function 223

Programming Example: Cable Company Billing 225

Quick Review 231

Exercises 232

Programming Exercises 241

CONTROL STRUCTURES II (REPETITION) 247


5 Why Is Repetition Needed? 248

while Looping (Repetition) Structure 249

Designing while Loops 251


Case 1: Counter-Controlled while Loops 252
Case 2: Sentinel-Controlled while Loops 255
Case 3: Flag-Controlled while Loops 259
Case 4: EOF-Controlled while Loops 263
eof Function 263
More on Expressions in while Statements 268

Programming Example: Fibonacci Number 269

for Looping (Repetition) Structure 273

Programming Example: Classifying Numbers 281


xii | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

do...while Looping (Repetition) Structure 284


Choosing the Right Looping Structure 289

break and continue Statements 289

Nested Control Structures 291

Avoiding Bugs by Avoiding Patches 296

Debugging Loops 299

Quick Review 300

Exercises 301

Programming Exercises 313

USER-DEFINED FUNCTIONS I 319


6 Predefined Functions 320

User-Defined Functions 324

Value-Returning Functions 324


Syntax: Value-Returning Functions 326
Syntax: Formal Parameter List 326
Function Call 326
Syntax: Actual Parameter List 327
return Statement 327
Syntax: return Statement 327
Function Prototype 331
Syntax: Function Prototype 332
Value-Returning Functions: Some Peculiarity 333
More Examples of Value-Returning Functions 335
Flow of Execution 340

Programming Example: Largest Number 341

Programming Example: Cable Company 343

Quick Review 349

Exercises 350

Programming Exercises 356


Table of Contents | xiii

USER-DEFINED FUNCTIONS II 361


7 Void Functions 362

Value Parameters 367

Reference Variables as Parameters 368

Value and Reference Parameters


and Memory Allocation 372

Reference Parameters and Value-Returning Functions 382

Scope of an Identifier 382

Global Variables, Named Constants, and Side Effects 386

Static and Automatic Variables 391

Debugging: Using Drivers and Stubs 392

Function Overloading: An Introduction 395

Functions with Default Parameters 396

Programming Example: Classify Numbers 399

Programming Example: Data Comparison 404

Quick Review 414

Exercises 416

Programming Exercises 424

USER-DEFINED SIMPLE DATA TYPES,


8 NAMESPACES, AND THE string TYPE 433

Enumeration Type 434


Declaring Variables 436
Assignment 436
Operations on Enumeration Types 437
Relational Operators 437
Input /Output of Enumeration Types 438
Functions and Enumeration Types 440
Declaring Variables When Defining the Enumeration Type 442
xiv | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Anonymous Data Types 442


typedef Statement 443

Programming Example: The Game of Rock,


Paper, and Scissors 444

Namespaces 452

string Type 458


Additional string Operations 461

Programming Example: Pig Latin Strings 471

Quick Review 475

Exercises 477

Programming Exercises 481

ARRAYS AND STRINGS 485


9 Arrays 487
Accessing Array Components 488
Processing One-Dimensional Arrays 491
Array Index Out of Bounds 494
Array Initialization During Declaration 495
Partial Initialization of Arrays During Declaration 496
Some Restrictions on Array Processing 496
Arrays as Parameters to Functions 497
Constant Arrays as Formal Parameters 498
Base Address of an Array and Array in Computer Memory 501
Functions Cannot Return a Value of the Type Array 503
Integral Data Type and Array Indices 506
Other Ways to Declare Arrays 507

Searching an Array for a Specific Item 507

C-Strings (Character Arrays) 510


String Comparison 512
Reading and Writing Strings 514
String Input 514
String Output 515
Table of Contents | xv

Specifying Input/Output Files at Execution Time 516


string Type and Input/Output Files 516

Parallel Arrays 517

Two- and Multidimensional Arrays 518


Accessing Array Components 520
Two-Dimensional Array Initialization During Declaration 521
Two-Dimensional Arrays and Enumeration Types 521
Initialization 524
Print 525
Input 525
Sum by Row 525
Sum by Column 526
Largest Element in Each Row and Each Column 526
Passing Two-Dimensional Arrays as Parameters to Functions 527
Arrays of Strings 530
Arrays of Strings and the string Type 530
Arrays of Strings and C-Strings (Character Arrays) 530
Another Way to Declare a Two-Dimensional Array 531
Multidimensional Arrays 532

Programming Example: Code Detection 534

Programming Example: Text Processing 540

Quick Review 547

Exercises 548

Programming Exercises 558

APPLICATIONS OF ARRAYS (SEARCHING AND SORTING)


10 AND THE Vector TYPE 563

List Processing 564


Searching 564
Bubble Sort 565
Selection Sort 569
Insertion Sort 572
Binary Search 576
xvi | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Performance of Binary Search 580

vector Type (class) 580

Programming Example: Election Results 585

Quick Review 601

Exercises 603

Programming Exercises 606

RECORDS ( structS) 611


11 Records (structs) 612
Accessing struct Members 614
Assignment 616
Comparison (Relational Operators) 617
Input /Output 618
struct Variables and Functions 618
Arrays versus structs 619
Arrays in structs 620
structs in Arrays 622
structs within a struct 624

Programming Example: Sales Data Analysis 628

Quick Review 642

Exercises 642

Programming Exercises 645

CLASSES AND DATA ABSTRACTION 649


12 Classes 650
Unified Modeling Language Class Diagrams 654
Variable (Object) Declaration 654
Accessing Class Members 655
Built-in Operations on Classes 656
Assignment Operator and Classes 657
Class Scope 657
Table of Contents | xvii

Functions and Classes 658


Reference Parameters and Class Objects (Variables) 658
Implementation of Member Functions 659
Accessor and Mutator Functions 664
Order of public and private Members of a Class 667
Constructors 669
Invoking a Constructor 671
Invoking the Default Constructor 671
Invoking a Constructor with Parameters 671
Constructors and Default Parameters 674
Classes and Constructors: A Precaution 674
Arrays of Class Objects (Variables) and Constructors 675
Destructors 677

Data Abstraction, Classes, and Abstract Data Types 678

A struct Versus a class 680

Information Hiding 681

Executable Code 685

Static Members of a Class 691

Programming Example: Candy Machine 697

Quick Review 711

Exercises 713

Programming Exercises 718

INHERITANCE AND COMPOSITION 723


13 Inheritance 724
Redefining (Overriding) Member Functions
of the Base Class 727
Constructors of Derived and Base Classes 734
Destructors in a Derived Class 742
Multiple Inclusions of a Header File 743
C++ Stream Classes 744
Protected Members of a Class 746
xviii | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Inheritance as public, protected, or private 746


(Accessing protected Members in the Derived Class) 747

Composition (Aggregation) 750

Object-Oriented Design (OOD) and


Object-Oriented Programming (OOP) 755
Identifying Classes, Objects, and Operations 757

Programming Example: Grade Report 758


Quick Review 779

Exercises 780
Programming Exercises 787

POINTERS, CLASSES, VIRTUAL FUNCTIONS,


14 AND ABSTRACT CLASSES 793
Pointer Data Type and Pointer Variables 794
Declaring Pointer Variables 794

Address of Operator (&) 795


Dereferencing Operator (*) 796

Classes, Structs, and Pointer Variables 800


Initializing Pointer Variables 803

Dynamic Variables 803


Operator new 804
Operator delete 805

Operations on Pointer Variables 807

Dynamic Arrays 809


Functions and Pointers 812
Pointers and Function Return Values 812
Dynamic Two-Dimensional Arrays 813

Shallow versus Deep Copy and Pointers 816

Classes and Pointers: Some Peculiarities 818


Destructor 818
Assignment Operator 820
Copy Constructor 821
Table of Contents | xix

Inheritance, Pointers, and Virtual Functions 828


Classes and Virtual Destructors 835

Abstract Classes and Pure Virtual Functions 835

Address of Operator and Classes 844

Quick Review 846

Exercises 849

Programming Exercises 857

OVERLOADING AND TEMPLATES 861


15 Why Operator Overloading Is Needed 862

Operator Overloading 863


Syntax for Operator Functions 864
Overloading an Operator: Some Restrictions 864
Pointer this 865
Friend Functions of Classes 870
Operator Functions as Member Functions and Nonmember
Functions 873
Overloading Binary Operators 876
Overloading the Stream Insertion (<<) and Extraction (>>)
Operators 882
Overloading the Assignment Operator (=) 887
Overloading Unary Operators 895
Operator Overloading: Member versus Nonmember 901
Classes and Pointer Member Variables (Revisited) 902
Operator Overloading: One Final Word 902

Programming Example: Clock Type 902

Programming Example: Complex Numbers 911

Overloading the Array Index (Subscript) Operator ([]) 916

Programming Example: Newstring 918

Function Overloading 924


xx | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Templates 925
Function Templates 925
Class Templates 927

Quick Review 935

Exercises 937

Programming Exercises 942

EXCEPTION HANDLING 951


16 Handling Exceptions within a Program 952
C++ Mechanisms of Exception Handling 956
try/catch Block 956
Using C++ Exception Classes 963

Creating Your Own Exception Classes 967


Rethrowing and Throwing an Exception 973

Exception-Handling Techniques 978


Terminate the Program 978
Fix the Error and Continue 978
Log the Error and Continue 980

Stack Unwinding 980

Quick Review 984

Exercises 986

Programming Exercises 989

RECURSION 991
17 Recursive Definitions 992
Direct and Indirect Recursion 995
Infinite Recursion 995

Problem Solving Using Recursion 996


Tower of Hanoi: Analysis 1005

Recursion or Iteration? 1006


Table of Contents | xxi

Programming Example: Converting a Number from


Binary to Decimal 1007
Programming Example: Converting a Number from
Decimal to Binary 1011
Quick Review 1014

Exercises 1015
Programming Exercises 1018
LINKED LISTS 1023
18 Linked Lists 1024
Linked Lists: Some Properties 1025
Deletion 1031
Building a Linked List 1032

Linked List as an ADT 1037


Structure of Linked List Nodes 1038
Member Variables of the class linkedListType 1038
Linked List Iterators 1039
Print the List 1045
Length of a List 1045
Retrieve the Data of the First Node 1046
Retrieve the Data of the Last Node 1046
Begin and End 1046
Copy the List 1047
Destructor 1048
Copy Constructor 1048
Overloading the Assignment Operator 1049

Unordered Linked Lists 1049


Search the List 1050
Insert the First Node 1051
Insert the Last Node 1052
Header File of the Unordered Linked List 1057

Ordered Linked Lists 1058


Search the List 1059
Insert a Node 1060
Insert First and Insert Last 1064
xxii | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Delete a Node 1065


Header File of the Ordered Linked List 1066

Print a Linked List in Reverse Order (Recursion Revisited) 1069


printList Reverse 1071

Doubly Linked Lists 1072


Default Constructor 1075
isEmptyList 1075
Destroy the List 1075
Initialize the List 1076
Length of the List 1076
Print the List 1076
Reverse Print the List 1076
Search the List 1077
First and Last Elements 1077

Circular Linked Lists 1083

Programming Example: Video Store 1084

Quick Review 1104

Exercises 1104

Programming Exercises 1109

STACKS AND QUEUES 1115


19 Stacks 1116
Stack Operations 1118

Implementation of Stacks as Arrays 1120


Initialize Stack 1123
Empty Stack 1124
Full Stack 1124
Push 1124
Return the Top Element 1126
Pop 1126
Copy Stack 1128
Constructor and Destructor 1128
Copy Constructor 1129
Table of Contents | xxiii

Overloading the Assignment Operator (=) 1129


Stack Header File 1130

Programming Example: Highest GPA 1134

Linked Implementation of Stacks 1138


Default Constructor 1141
Empty Stack and Full Stack 1141
Initialize Stack 1142
Push 1142
Return the Top Element 1144
Pop 1144
Copy Stack 1146
Constructors and Destructors 1147
Overloading the Assignment Operator (=) 1147
Stack as Derived from the
class unorderedLinkedList 1150

Application of Stacks: Postfix Expressions


Calculator 1151
Main Algorithm 1154
Function evaluateExpression 1154
Function evaluateOpr 1156
Function discardExp 1158
Function printResult 1158

Removing Recursion: Nonrecursive Algorithm


to Print a Linked List Backward 1161

Queues 1165
Queue Operations 1166
Implementation of Queues as Arrays 1168
Linked Implementation of Queues 1177
Queue Derived from the
class unorderedLinkedListType 1182

Application of Queues: Simulation 1183


Designing a Queuing System 1184
Customer 1185
Server 1188
xxiv | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Server List 1191


Waiting Customers Queue 1196
Main Program 1198

Quick Review 1203

Exercises 1204

Programming Exercises 1210

APPENDIX A: RESERVED WORDS 1215

APPENDIX B: OPERATOR PRECEDENCE 1217

APPENDIX C: CHARACTER SETS 1219


ASCII (American Standard Code for
Information Interchange) 1219

EBCDIC (Extended Binary Coded


Decimal Interchange Code) 1220

APPENDIX D: OPERATOR OVERLOADING 1223

APPENDIX E: ADDITIONAL C++ TOPICS 1225


Binary (Base 2) Representation of a
Nonnegative Integer 1225
Converting a Base 10 Number to a
Binary Number (Base 2) 1225
Converting a Binary Number (Base 2) to Base 10 1227
Converting a Binary Number (Base 2) to Octal (Base 8)
and Hexadecimal (Base 16) 1228

More on File Input/Output 1230


Binary Files 1230
Random File Access 1236

Naming Conventions of Header Files in


ANSI/ISO Standard C++ and Standard C++ 1244
Table of Contents | xxv

APPENDIX F: HEADER FILES 1247


Header File cassert (assert.h) 1247

Header File cctype (ctype.h) 1248

Header File cfloat (float.h) 1249

Header File climits (limits.h) 1250

Header File cmath (math.h) 1252


Header File cstddef (stddef.h) 1253
Header File cstring (string.h) 1253

APPENDIX G: MEMORY SIZE ON A SYSTEM


AND RANDOM NUMBER GENERATOR 1257
Random Number Generator 1258

APPENDIX H: STANDARD TEMPLATE


LIBRARY (STL) 1259
Components of the STL 1259

Container Types 1260


Sequence Containers 1260
Sequence Container: Vectors 1260
Member Functions Common to All Containers 1269
Member Functions Common to Sequence Containers 1271
copy Algorithm 1272
Sequence Container: deque 1276
Sequence Container: list 1279

Iterators 1284
IOStream Iterators 1285
Container Adapters 1285

Algorithms 1289
STL Algorithm Classification 1289
STL Algorithms 1292
Functions fill and fill_n 1292
Functions find and find_if 1294
xxvi | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Functions remove and replace 1295


Functions search, sort, and binary_search 1297

APPENDIX I: ANSWERS TO ODD-NUMBERED


EXERCISES 1301
Chapter 1 1301

Chapter 2 1304

Chapter 3 1306

Chapter 4 1307

Chapter 5 1309

Chapter 6 1311

Chapter 7 1312

Chapter 8 1313

Chapter 9 1314

Chapter 10 1316

Chapter 11 1317

Chapter 12 1318

Chapter 13 1321

Chapter 14 1322

Chapter 15 1323

Chapter 16 1324

Chapter 17 1325

Chapter 18 1326

Chapter 19 1327

INDEX 1331
P REFACE

WELCOME TO THE FIFTH EDITION OF C++ Programming: From Problem Analysis to Program
Design. Designed for a first Computer Science (CS1) C++ course, this text provides a
breath of fresh air to you and your students. The CS1 course serves as the cornerstone of
the Computer Science curriculum. My primary goal is to motivate and excite all CS1
students, regardless of their level. Motivation breeds excitement for learning. Motivation
and excitement are critical factors that lead to the success of the programming student. This
text is a culmination and development of my classroom notes throughout more than fifty
semesters of teaching successful programming to Computer Science students.

Warning: This text can be expected to create a serious reduction in the demand for
programming help during your office hours. Other side effects include significantly
diminished student dependency on others while learning to program.

C++ Programming: From Problem Analysis to Program Design started as a collection of brief
examples, exercises, and lengthy programming examples to supplement the books that were
in use at our university. It soon turned into a collection large enough to develop into a text.
The approach taken in this book is, in fact, driven by the students’ demand for clarity and readability.
The material was written and rewritten until the students felt comfortable with it. Most of the
examples in this book resulted from student interaction in the classroom.
As with any profession, practice is essential. Cooking students practice their recipes.
Budding violinists practice their scales. New programmers must practice solving
problems and writing code. This is not a C++ cookbook. We do not simply list the
C++ syntax followed by an example; we dissect the ‘‘why’’ behind all the concepts. The
crucial question of ‘‘why?’’ is answered for every topic when first introduced. This
technique offers a bridge to learning C++. Students must understand the ‘‘why?’’ in
order to be motivated to learn.
Traditionally, a C++ programming neophyte needed a working knowledge of another
programming language. This book assumes no prior programming experience. However,
some adequate mathematics background, such as college algebra, is required.
xxviii | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

Changes in the Fifth Edition


The fifth edition contains more than 50 new programming exercises, and more than 150 new
exercises. Each of the Chapters 2 to 7 include a programming exercise which contains a
solution of a problem, however, the statements are in the incorrect order. So the student is
asked to rewrite the program with statements in the correct order. This will allow the students
to learn how to read and debug programs written by someone else. Another major change in
this edition is the inclusion of debugging sections in the chapters 2 to 7. In these sections, a
program with errors is included. The program is compiled and syntax errors, if any are shown.
We then show how to interpret the syntax errors and correct them. Some sections also show
how to find and correct logical errors. This edition also includes various new examples, such
as Examples 5-8, 7-8, 12-6, and 12-8. Various sections of Chapters 4, 5, 6, and 7 have been
rewritten. Chapter 8 includes additional string functions and virtual functions section of
Chapter 14 is rewritten with new examples.

Approach
The programming language C++, which evolved from C, is no longer considered an
industry-only language. Numerous colleges and universities use C++ for their first program-
ming language course. C++ is a combination of structured programming and object-oriented
programming, and this book addresses both types.
This book can be easily divided into two parts: structured programming and object-oriented
programming. The first 11 chapters form the structured programming part; Chapters 12
through 19 form the object-oriented part. However, only the first seven chapters are essential
to move on to the object-oriented portion.
In July 1998, ANSI/ISO Standard C++ was officially approved. This book focuses on ANSI/
ISO Standard C++. Even though the syntax of Standard C++ and ANSI/ISO Standard C++
is very similar, Chapter 8 discusses some of the features of ANSI/ISO Standard C++ that are
not available in Standard C++.
Chapter 1 briefly reviews the history of computers and programming languages. The reader can
quickly skim through this chapter and become familiar with some of the hardware components
and the software parts of the computer. This chapter contains a section on processing a C++
program. This chapter also describes structured and object-oriented programming.
Chapter 2 discusses the basic elements of C++. After completing this chapter, students
become familiar with the basics of C++ and are ready to write programs that are complicated
enough to do some computations. Input/output is fundamental to any programming
language. It is introduced early, in Chapter 3, and is covered in detail.
Chapters 4 and 5 introduce control structures to alter the sequential flow of execution.
Chapters 6 and 7 study user-defined functions. It is recommended that readers with no prior
programming background spend extra time on Chapters 6 and 7. Several examples are provided
to help readers understand the concepts of parameter passing and the scope of an identifier.
Preface | xxix

Chapter 8 discusses the user-defined simple data type (enumeration type), the namespace
mechanism of ANSI/ISO Standard C++, and the string type. The earlier versions of C did
not include the enumeration type. Enumeration types have very limited use; their main
purpose is to make the program readable. This book is organized such that readers can skip
the section on enumeration types during the first reading without experiencing any disconti-
nuity, and then later go through this section.
Chapter 9 discusses arrays in detail. Chapter 10 describes various searching and sorting
algorithms as well as an introduction to the vector class. Chapter 11 introduces records
(structs). The introduction of structs in this book is similar to C structs. This chapter is
optional; it is not a prerequisite for any of the remaining chapters.
Chapter 12 begins the study of object-oriented programming (OOP) and introduces classes.
The first half of this chapter shows how classes are defined and used in a program. The second
half of the chapter introduces abstract data types (ADTs). This chapter shows how classes in
C++ are a natural way to implement ADTs. Chapter 13 continues with the fundamentals of
object-oriented design (OOD) and OOP and discusses inheritance and composition. It
explains how classes in C++ provide a natural mechanism for OOD and how C++ supports
OOP. Chapter 13 also discusses how to find the objects in a given problem.
Chapter 14 studies pointers in detail. After introducing pointers and how to use them in a
program, this chapter highlights the peculiarities of classes with pointer data members and
how to avoid them. Moreover, this chapter also discusses how to create and work with
dynamic two-dimensional arrays. Chapter 14 also discusses abstract classes and a type of
polymorphism accomplished via virtual functions.
Chapter 15 continues the study of OOD and OOP. In particular, it studies polymorphism in C++.
The chapter specifically discusses two types of polymorphism—overloading and templates.
Chapter 16 discusses exception handling in detail. Chapter 17 introduces and discusses recur-
sion. Moreover, this is a standalone chapter, so it can be studied anytime after Chapter 10.
Chapters 18 and 19 are devoted to the study of data structures. Discussed in detail are linked
lists in Chapter 18 and stacks and queues in Chapter 19. The programming code developed in
these chapters is generic. These chapters effectively use the fundamentals of OOD.
Appendix A lists the reserved words in C++. Appendix B shows the precedence and
associativity of the C++ operators. Appendix C lists the ASCII (American Standard Code
for Information Interchange) and EBCDIC (Extended Binary Coded Decimal Interchange
Code) character sets. Appendix D lists the C++ operators that can be overloaded.
Appendix E has three objectives. First, we discuss how to convert a number from decimal to
binary and binary to decimal. We then discuss binary and random access files in detail.
Finally, we describe the naming conventions of the header files in both ANSI/ISO Standard
C++ and Standard C++. Appendix F discusses some of the most widely used library
routines, and includes the names of the standard C++ header files. The programs in
Appendix G show how to print the memory size for the built-in data types on your system
as well as how to use a random number generator. Appendix H gives an introduction to
xxx | C++ Programming: From Problem Analysis to Program Design, Fifth Edition

the Standard Template Library, and Appendix I provides the answers to odd-numbered
exercises in the book.

How to Use the Book


This book can be used in various ways. Figure 1 shows the dependency of the chapters.

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6

Chapter 7

Chapter 8 Chapter 9*

Chapter 10 Chapter 11 Chapter 12

Chapter 13 Chapter 14 Chapter 16

Chapter 15

Chapter 17

Chapter 18

Chapter 19

FIGURE 1 Chapter dependency diagram


Preface | xxxi

In Figure 1, dotted lines mean the preceding chapter is used in one of the sections of the
chapter and is not necessarily a prerequisite for the next chapter. For example, Chapter 9
covers arrays in detail. In Chapters 11 and 12, we show the relationship between arrays and
structs and arrays and classes, respectively. However, if Chapter 12 is studied before
Chapter 9, then the section dealing with arrays in Chapter 12 can be skipped without any
discontinuation. This particular section can be studied after studying chapter 9.
It is recommended that the first seven chapters be covered sequentially. After covering the
first seven chapters, if the reader is interested in learning OOD and OOP early, then Chapter
12 can be studied right after Chapter 7. Chapter 8 can be studied any time after Chapter 7.
After studying the first seven chapters in sequence, some of the approaches are:
1. Study chapters in the sequence: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19.
2. Study chapters in the sequence: 9, 12, 14, 15, 13, 17, 18, 19, 10, 16.
3. Study chapters in the sequence: 12, 9, 10, 14, 15, 13, 17, 18, 19, 16.
4. Study chapters in the sequence: 12, 9, 14, 15, 13, 17, 18, 19, 10, 16.
FEATURES OF THE BOOK

Four-color
interior design
shows
accurate C++
code and
related
comments.
More than 300
visual diagrams,
both extensive
and exhaustive,
illustrate difficult
concepts.
Numbered examples
illustrate the key
concepts with their
relevant code. The
programming code
in these examples is
followed by a
Sample Run. An
explanation then
follows that
describes what each
line in the code
does.

Notes highlight important


facts about the concepts
introduced in the chapter.
Programming
Examples are
programs featured at
the end of each
chapter. Programming
Examples are where
everything in the
chapter comes
together. They are
highlighted with an
icon in the margin like
the one shown here.
These examples teach
problem solving skills
and include the
concrete stages of
input, output,
problem analysis and
algorithm design,
class design, and a
program listing All
programs are
designed to be
methodical,
consistent, and user-
friendly. Each
Programming
Example starts with a
problem analysis that
is followed by the
algorithm design and/
or class design. Every
step of the algorithm
is coded in C++. In
addition to helping
students learn
problem solving
techniques, these
detailed programs
show the student how
to implement concepts in an actual C++ program. We strongly recommend that students study the Programming
Examples carefully in order to learn C++ effectively. Students typically learn much from completely worked-out
programs. Further, programming examples reduce considerably the students’ need for help outside the classroom and
bolster the students’ self-confidence.
Exercises further
reinforce learning
and ensure that
students have, in
fact, mastered the
material.
Programming
Exercises challenge
students to write
C++ programs with
a specified
outcome.
S UPPLEMENTAL
R ESOURCES

The following supplemental materials are available when this book is used in a classroom
setting.
All instructor teaching tools are available with this book 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.
Supplemental Resources | xxxix

Content for Online Learning


Course Technology has partnered with today’s leading distance learning solution providers
and class-management platforms. To access this material, visit www.cengage.com/webtutor
and search for your title. Instructor resources include the following: additional case projects,
sample syllabi, PowerPoint presentations, and more. For students to access this material, they
must have purchased a WebTutor PIN-code specific to this title and your campus platform.
The resources for students might include (based on instructor preferences): topic reviews,
review questions, practice tests, and more. For additional information, please contact your
sales representative.

Source Code
The source code, in ANSI/ISO Standard C++, is available at www.course.com, and is also
available on the Instructor Resources CD-ROM. The input files needed to run some of the
programs are also included with the source code.

Solution Files
The solution files for all Programming Exercises, in ANSI/ISO C++, are available at www.course.
com, and are also available on the Instructor Resources CD-ROM. The input files needed to run
some of the Programming Exercises are also included with the solution files.
A CKNOWLEDGEMENTS

There are many people that I must thank who, one way or another, contributed to the success
of this book. First, I would like to thank all the students who, during the preparation, were
spontaneous in telling me if certain portions needed to be reworded for better understanding
and clearer reading. Next, I would like to thank those who e-mailed numerous comments to
improve upon the second edition. I am thankful to Professors S.C. Cheng, Randall Crist, and
Vasant Raval for constantly supporting this project. I am also very grateful to the reviewers
who reviewed earlier versions of this book and offered many critical suggestions on how to
improve it.
I owe a great deal to the following reviewers who patiently read each page of every chapter of
the current version and made critical comments to improve on the book: Stefano Basagni,
Northeastern University; Jeff Ringenberg, University of Michigan; Colleen van Lent, Uni-
versity of Michigan; Tuan Vo, Mt. San Antonio College; Kerstin Voigt, California State
University San Bernardino; Lan Yang, Cal Poly Pomona. The reviewers will recognize that
their criticisms have not been overlooked and, in fact, made this a better book.
Next, I express thanks to Amy Jollymore, acquisition editor, for recognizing the importance
and uniqueness of this project. All this would not have been possible without the careful
planning of Senior Product Manager Alyssa Pratt. I extend my sincere thanks to Alyssa, as well
as to Content Project Manager, Mathew Hutchinson. I also thank Tintu Thomas of Integra
Software Services for assisting us in keeping the project on schedule. I would like to thank
Chris Scriver and Serge Palladino of QA department of Course Technology for patiently and
carefully proof reading the text, testing the code, and discovering typos and errors.
I am thankful to my parents for their blessings.
Finally, I am thankful for the support of my wife Sadhana and especially my daughter Shelly,
to whom this book is dedicated. She cheered me up whenever I was overwhelmed during the
writing of this book, and also made sure that the corrections were in place. Shelly always
draws special joy whenever I undertake such projects.
I welcome any comments concerning the text. Comments may be forwarded to the following
e-mail address: malik@creighton.edu
D. S. Malik
1
CHAPTER

A N O VERVIEW OF
COMPUTERS AND
P ROGRAMMING
L ANGUAGES
I N T H I S C H A P T E R , YO U W I L L :
. Learn about different types of computers
. Explore the hardware and software components of a computer system
. Learn about the language of a computer
. Learn about the evolution of programming languages
. Examine high-level programming languages
. Discover what a compiler is and what it does
. Examine a C++ program
. Explore how a C++ program is processed
. Learn what an algorithm is and explore problem-solving techniques
. Become aware of structured design and object-oriented design programming methodologies
. Become aware of Standard C++ and ANSI/ISO Standard C++
2 | Chapter 1: An Overview of Computers and Programming Languages

Introduction
Terms such as ‘‘the Internet,’’ which were unfamiliar just 20 years ago are now common.
Students in elementary school regularly ‘‘surf ’’ the Internet and use computers to design their
classroom projects. Many people use the Internet to look for information and to commu-
nicate with others. This is all made possible by the availability of different software, also
known as computer programs. Without software, a computer is useless. Software is devel-
oped by using programming languages. The programming language C++ is especially well
suited for developing software to accomplish specific tasks. Our main objective is to help you
learn how to write programs in the C++ programming language. Before you begin
programming, it is useful to understand some of the basic terminology and different
components of a computer. We begin with an overview of the history of computers.

A Brief Overview of the History of Computers


The first device known to carry out calculations was the abacus. The abacus was invented in
Asia but was used in ancient Babylon, China, and throughout Europe until the late middle
ages. The abacus uses a system of sliding beads in a rack for addition and subtraction. In 1642,
the French philosopher and mathematician Blaise Pascal invented the calculating device
called the Pascaline. It had eight movable dials on wheels and could calculate sums up to
eight figures long. Both the abacus and Pascaline could perform only addition and subtrac-
tion operations. Later in the 17th century, Gottfried von Leibniz invented a device that was
able to add, subtract, multiply, and divide. In 1819, Joseph Jacquard, a French weaver,
discovered that the weaving instructions for his looms could be stored on cards with holes
punched in them. While the cards moved through the loom in sequence, needles passed
through the holes and picked up threads of the correct color and texture. A weaver could
rearrange the cards and change the pattern being woven. In essence, the cards programmed a
loom to produce patterns in cloth. The weaving industry may seem to have little in common
with the computer industry. However, the idea of storing information by punching holes on
a card proved to be of great importance in the later development of computers.
In the early and mid-1800s, Charles Babbage, an English mathematician and physical
scientist, designed two calculating machines—the difference engine and the analytical
engine. The difference engine could perform complex operations such as squaring
numbers automatically. Babbage built a prototype of the difference engine, but the actual
device was never produced. The analytical engine’s design included input device, data
storage, a control unit that allowed processing instructions in any sequence, and output
devices. However, the designs remained in blueprint stage. Most of Babbage’s work is
known through the writings of his colleague Ada Augusta, Countess of Lovelace. Augusta
is considered the first computer programmer.
At the end of the 19th century, U.S. Census officials needed help in accurately tabulating
the census data. Herman Hollerith invented a calculating machine that ran on electricity
and used punched cards to store data. Hollerith’s machine was immensely successful.
Hollerith founded the Tabulating Machine Company, which later became the computer
and technology corporation known as IBM.
Elements of a Computer System | 3

The first computer-like machine was the Mark I. It was built, in 1944, jointly by IBM and
Harvard University under the leadership of Howard Aiken. Punched cards were used to feed 1
data into the machine. The Mark I was 52 feet long, weighed 50 tons, and had 750,000 parts.
In 1946, the ENIAC (Electronic Numerical Integrator and Calculator) was built at the
University of Pennsylvania. It contained 18,000 vacuum tubes and weighed some 30 tons.
The computers that we know today use the design rules given by John von Neumann in
the late 1940s. His design included components such as an arithmetic logic unit, a control
unit, memory, and input/output devices. These components are described in the next
section. Von Neumann’s computer design makes it possible to store the programming
instructions and the data in the same memory space. In 1951, the UNIVAC (Universal
Automatic Computer) was built and sold to the U.S. Census Bureau.
In 1956, the invention of transistors resulted in smaller, faster, more reliable, and more
energy-efficient computers. This era also saw the emergence of the software development
industry, with the introduction of FORTRAN and COBOL, two early programming
languages. In the next major technological advancement, transistors were replaced by tiny
integrated circuits, or ‘‘chips.’’ Chips are smaller and cheaper than transistors and can contain
thousands of circuits on a single chip. They give computers tremendous processing speed.
In 1970, the microprocessor, an entire CPU on a single chip, was invented. In 1977,
Stephen Wozniak and Steven Jobs designed and built the first Apple computer in their
garage. In 1981, IBM introduced its personal computer (PC). In the 1980s, clones of the
IBM PC made the personal computer even more affordable. By the mid-1990s, people
from many walks of life were able to afford them. Computers continue to become faster
and less expensive as technology advances.
Modern-day computers are powerful, reliable, and easy to use. They can accept spoken-word
instructions and imitate human reasoning through artificial intelligence. Expert systems assist
doctors in making diagnoses. Mobile computing applications are growing significantly. Using
handheld devices, delivery drivers can access global positioning satellites (GPS) to verify
customer locations for pickups and deliveries. Cell phones permit you to check your e-mail,
make airline reservations, see how stocks are performing, and access your bank accounts.
Although there are several categories of computers, such as mainframe, midsize, and
micro, all computers share some basic elements, described in the next section.

Elements of a Computer System


A computer is an electronic device capable of performing commands. The basic commands
that a computer performs are input (get data), output (display result), storage, and perfor-
mance of arithmetic and logical operations.
In today’s market, personal computers are sold with descriptions such as a Pentium 4
Processor 2.80 GHz, 1 GB RAM, 250 GB HD, VX750 19" Silver Flat CRT Color
Monitor, preloaded with software such as an operating system, games, encyclopedias, and
application software such as word processors or money management programs. These
descriptions represent two categories: hardware and software. Items such as ‘‘Pentium 4
4 | Chapter 1: An Overview of Computers and Programming Languages

Processor 2.80 GHz, 1GB RAM, 250 GB HD, VX750 19" Silver Flat CRT Color Monitor’’
fall into the hardware category; items such as ‘‘operating system, games, encyclopedias, and
application software’’ fall into the software category. Let’s consider the hardware first.

Hardware
Major hardware components include the central processing unit (CPU); main memory
(MM), also called random access memory (RAM); input/output devices; and secondary
storage. Some examples of input devices are the keyboard, mouse, and secondary storage.
Examples of output devices are the screen, printer, and secondary storage. Let’s look at
each of these components in greater detail.

Central Processing Unit and Main Memory


The central processing unit is the ‘‘brain’’ of the computer and the single most expensive
piece of hardware in a computer. The more powerful the CPU, the faster the computer.
Arithmetic and logical operations are carried out inside the CPU. Figure 1-1(a) shows some
hardware components.

. .
Input . .
Central . .
Device
Processing 1000 54
Unit (CPU) 1001
Output A
. .
Device . .
. .
Main Memory 2000
2001
. .
. .
. .
Secondary Storage Main Memory

(a) (b)

FIGURE 1-1 Hardware components of a computer and main memory

Main memory, or random access memory, is connected directly to the CPU. All
programs must be loaded into main memory before they can be executed. Similarly, all
data must be brought into main memory before a program can manipulate it. When the
computer is turned off, everything in main memory is lost.
Main memory is an ordered sequence of cells, called memory cells. Each cell has a unique
location in main memory, called the address of the cell. These addresses help you access
the information stored in the cell. Figure 1-1(b) shows main memory with some data.
Random documents with unrelated
content Scribd suggests to you:
Triste comme un lion mangé par la vermine!
—Charles-Quint! dans ces temps d’opprobre et de
terreur,
Que fais-tu dans ta tombe, ô puissant empereur?
Oh! lève-toi! viens voir!—Les bons font place aux
pires.
Ce royaume effrayant, fait d’un amas d’empires,
Penche... Il nous faut ton bras! au secours, Charles-
Quint!
Car l’Espagne se meurt! car l’Espagne s’éteint!
Ton globe, qui brillait dans ta droite profonde,
Soleil éblouissant, qui faisait croire au monde
Que le jour désormais se levait à Madrid,
Maintenant, astre mort, dans l’ombre s’amoindrit,
Lune aux trois quarts rongée et qui décroît encore,
Et que d’un autre peuple effacera l’aurore!
Hélas! ton héritage est en proie aux vendeurs.
Tes rayons, ils en font des piastres! Tes splendeurs,
On les souille!—O géant! se peut-il que tu dormes?—
On vend ton sceptre au poids! un tas de nains
difformes
Se taillent des pourpoints dans ton manteau de roi;
Et l’aigle impérial qui, jadis, sous ta loi,
Couvrait le monde entier de tonnerre, et de flamme,
Cuit, pauvre oiseau plumé, dans leur marmite infâme!
Les conseillers se taisent consternés. Seuls, le marquis de Priego et le
comte de Camporeal redressent la tête et regardent Ruy Blas avec
colère. Puis Camporeal, après avoir parlé à Priego, va à la table, écrit
quelques mots sur un papier, les signe et les fait signer au marquis.

LE COMTE DE CAMPOREAL, désignant le marquis de Priego et


remettant le papier à Ruy Blas.

Monsieur le duc,—au nom de tous les deux,—voici


Notre démission de notre emploi.
RUY BLAS, prenant le papier, froidement.

Merci.
Vous vous retirerez, avec votre famille,
A Priego.

Vous, en Andalousie,—
A Camporeal.

Et vous, comte, en Castille.


Chacun dans vos États. Soyez partis demain.
Les deux seigneurs s’inclinent et sortent fièrement le chapeau sur la
tête. Ruy Blas se tourne vers les autres conseillers.

Quiconque ne veut pas marcher dans mon chemin


Peut suivre ces messieurs.
Silence dans les assistants. Ruy Blas s’assied à la table sur une chaise à
dossier placée à droite du fauteuil royal, et s’occupe à décacheter
une correspondance. Pendant qu’il parcourt les lettres l’une après
l’autre, Covadenga, Arias et Ubilla échangent quelques paroles à voix
basse.

UBILLA, à Covadenga, montrant Ruy Blas.

Fils, nous avons un maître.


Cet homme sera grand.

DON MANUEL ARIAS.

Oui, s’il a le temps d’être.

COVADENGA.

Et s’il ne se perd pas à tout voir de trop près.

UBILLA.

Il sera Richelieu!
DON MANUEL ARIAS.

S’il n’est Olivarès!

RUY BLAS, après avoir parcouru vivement une lettre qu’il vient d’ouvrir.

Un complot! qu’est ceci? messieurs, que vous disais-


je?
Lisant.

—... «Duc d’Olmedo, veillez. Il se prépare un piége


«Pour enlever quelqu’un de très-grand de Madrid.»
Examinant la lettre.

—On ne nomme pas qui. Je veillerai.—L’écrit


Est anonyme.—
Entre un huissier de cour qui s’approche de Ruy Blas avec une profonde
révérence.

Allons! qu’est-ce!

L’HUISSIER.

A Votre Excellence
J’annonce monseigneur l’ambassadeur de France.

RUY BLAS.

Ah! d’Harcourt! Je ne puis à présent.

L’HUISSIER, s’inclinant.

Monseigneur,
Le nonce impérial dans la chambre d’honneur
Attend Votre Excellence.

RUY BLAS.

A cette heure? impossible.


L’huissier s’incline et sort. Depuis quelques instants, un page est entré,
vêtu d’une livrée couleur de feu à galons d’argent, et s’est approché
de Ruy Blas.

RUY BLAS, l’apercevant.

Mon page! je ne suis pour personne visible.

LE PAGE, bas.

Le comte Guritan, qui revient de Neubourg...

RUY BLAS, avec un geste de surprise.

Ah!—Page, enseigne-lui ma maison du faubourg.


Qu’il m’y vienne trouver demain, si bon lui semble.
Va.
Le page sort. Aux conseillers.

Nous aurons tantôt à travailler ensemble.


Dans deux heures. Messieurs, revenez.
Tous sortent en saluant profondément Ruy Blas.

Ruy Blas, resté seul, fait quelques pas en proie à une rêverie profonde.
Tout à coup, à l’angle du salon, la tapisserie s’écarte et la reine
apparaît. Elle est vêtue de blanc avec la couronne en tête; elle paraît
rayonnante de joie et fixe sur Ruy Blas un regard d’admiration et de
respect. Elle soutient d’un bras la tapisserie derrière laquelle on
entrevoit une sorte de cabinet obscur où l’on distingue une petite
porte. Ruy Blas, en se retournant, aperçoit la reine et reste comme
pétrifié devant cette apparition.
SCÈNE TROISIÈME.
RUY BLAS, LA REINE.

LA REINE, du fond du théâtre.

Oh! merci!

RUY BLAS.

Ciel!

LA REINE.

Vous avez bien fait de leur parler ainsi.


Je n’y puis résister, duc, il faut que je serre
Cette loyale main si ferme et si sincère!
Elle marche vivement à lui et lui prend la main qu’elle presse avant qu’il
ait pu s’en défendre.

RUY BLAS.

A part.

La fuir depuis six mois et la voir tout à coup.


Haut.

Vous étiez là, madame?...

LA REINE.

Oui, duc, j’entendais tout.


J’étais là. J’écoutais avec toute mon âme!

RUY BLAS, montrant la cachette.

Je ne soupçonnais pas...—Ce cabinet, madame...


LA REINE.

Personne ne le sait. C’est un réduit obscur


Que don Philippe trois fit creuser dans ce mur,
D’où le maître invisible entend tout comme une
ombre.
Là j’ai vu bien souvent Charles deux, morne et
sombre,
Assister aux conseils où l’on pillait son bien,
Où l’on vendait l’État.

RUY BLAS.

Et que disait-il?

LA REINE.

Rien.

RUY BLAS.

Rien?—Et que faisait-il?

LA REINE.

Il allait à la chasse.
Mais vous! j’entends encor votre accent qui menace.
Comme vous les traitiez d’une haute façon,
Et comme vous aviez superbement raison!
Je soulevais le bord de la tapisserie,
Je vous voyais. Votre œil, irrité sans furie,
Les foudroyait d’éclairs, et vous leur disiez tout.
Vous me sembliez seul être resté debout!
Mais où donc avez-vous appris toutes ces choses?
D’où vient que vous savez les effets et les causes?
Vous n’ignorez donc rien? D’où vient que votre voix
Parlait comme devrait parler celle des rois?
Pourquoi donc étiez-vous, comme eût été Dieu même,
Si terrible et si grand?

RUY BLAS.

Parce que je vous aime!


Parce que je sens bien, moi qu’ils haïssent tous,
Que ce qu’ils font crouler s’écroulera sur vous!
Parce que rien n’effraye une ardeur si profonde,
Et que, pour vous sauver, je sauverais le monde!
Je suis un malheureux qui vous aime d’amour.
Hélas! je pense à vous comme l’aveugle au jour,
Madame, écoutez-moi. J’ai des rêves sans nombre.
Je vous aime de loin, d’en bas, du fond de l’ombre;
Je n’oserais toucher le bout de votre doigt,
Et vous m’éblouissez comme un ange qu’on voit!
—Vraiment, j’ai bien souffert. Si vous saviez,
madame!
Je vous parle à présent. Six mois, cachant ma flamme
J’ai fui. Je vous fuyais et je souffrais beaucoup.
Je ne m’occupe pas de ces hommes du tout,
Je vous aime.—O mon Dieu! j’ose le dire en face
A Votre Majesté. Que faut-il que je fasse?
Si vous disiez: Meurs! je mourrais. J’ai l’effroi
Dans le cœur. Pardonnez!

LA REINE.

Oh! parle! ravis-moi!


Jamais on ne m’a dit ces choses-là. J’écoute!
Ton âme, en me parlant, me bouleverse toute.
J’ai besoin de tes yeux, j’ai besoin de ta voix.
Oh! c’est moi qui souffrais! Si tu savais! cent fois,
Cent fois, depuis six mois que ton regard m’évite...
—Mais non, je ne dois pas dire cela si vite.
Je suis bien malheureuse. Oh! je me tais, j’ai peur!
RUY BLAS, qui l’écoute avec ravissement.

O madame! achevez! vous m’emplissez le cœur!

LA REINE.

Eh bien, écoute donc!


Levant les yeux au ciel.

—Oui, je vais tout lui dire.


Est-ce un crime? Tant pis. Quand le cœur se déchire,
Il faut bien laisser voir tout ce qu’on y cachait.—
Tu fuis la reine? Eh bien, la reine te cherchait!
Tous les jours je viens là,—là, dans cette retraite,—
T’écoutant, recueillant ce que tu dis, muette,
Contemplant ton esprit qui veut, juge et résout,
Et prise par ta voix qui m’intéresse à tout.
Va, tu me sembles bien le vrai roi, le vrai maître.
C’est moi, depuis six mois, tu t’en doutes peut-être,
Qui t’ai fait, par degrés, monter jusqu’au sommet.
Où Dieu t’aurait dû mettre une femme te met.
Oui, tout ce qui me touche a mes soins. Je t’admire.
Autrefois une fleur, à présent un empire!
D’abord je t’ai vu bon, et puis je te vois grand.
Mon Dieu! c’est à cela qu’une femme se prend!
Mon Dieu! si je fais mal, pourquoi, dans cette tombe,
M’enfermer, comme on met en cage une colombe,
Sans espoir, sans amour, sans un rayon doré?
—Un jour que nous aurons le temps, je te dirai
Tout ce que j’ai souffert.—Toujours seule, oubliée.
Et puis, à chaque instant, je suis humiliée.
Tiens, juge: hier encor...—Ma chambre me deplaît.
—Tu dois savoir cela, toi qui sais tout, il est
Des chambres où l’on est plus triste que dans
d’autres;—
J’en ai voulu changer. Vois quels fers sont les nôtres!
On ne l’a pas voulu. Je suis esclave ainsi!—
Duc, il faut,—dans ce but le ciel t’envoie ici,—
Sauver l’État qui tremble, et retirer du gouffre
Le peuple qui travaille, et m’aimer, moi qui souffre.
Je te dis tout cela sans suite, à ma façon,
Mais tu dois cependant voir que j’ai bien raison.

RUY BLAS, tombant à genoux.

Madame...

LA REINE, gravement.

Don César, je vous donne mon âme.


Reine pour tous, pour vous je ne suis qu’une femme.
Par l’amour, par le cœur, duc, je vous appartien.
J’ai foi dans votre honneur pour respecter le mien.
Quand vous m’appellerez, je viendrai. Je suis prête.
—O César! un esprit sublime est dans ta tête.
Sois fier, car le génie est ta couronne à toi!
Elle baise Ruy Blas au front.

Adieu.
Elle soulève la tapisserie et disparaît.
SCÈNE QUATRIÈME.
RUY BLAS, seul.

Il est comme absorbé dans une contemplation angélique.

Devant mes yeux c’est le ciel que je voi!


De ma vie, ô mon Dieu! cette heure est la première.
Devant moi tout un monde, un monde de lumière,
Comme ces paradis qu’en songe nous voyons,
S’entr’ouvre en m’inondant de vie et de rayons!
Partout, en moi, hors moi, joie, extase et mystère,
Et l’ivresse, et l’orgueil, et ce qui sur la terre
Se rapproche le plus de la Divinité,
L’amour dans la puissance et dans la majesté!
La reine m’aime! ô Dieu! c’est bien vrai, c’est moi-
même.
Je suis plus que le roi puisque la reine m’aime!
Oh! cela m’éblouit. Heureux, aimé, vainqueur!
Duc d’Olmedo,—l’Espagne à mes pieds,—j’ai son
cœur!
Cet ange qu’à genoux je contemple et je nomme,
D’un mot me transfigure et me fait plus qu’un
homme.
Donc je marche vivant dans mon rêve étoilé!
Oh! oui, j’en suis bien sûr, elle m’a bien parlé.
C’est bien elle. Elle avait un petit diadème
En dentelle d’argent. Et je regardais même,
Pendant qu’elle parlait,—je crois la voir encor,—
Un aigle ciselé sur son bracelet d’or.
Elle se fie à moi, m’a-t-elle dit.—Pauvre ange!
Oh! s’il est vrai que Dieu, par un prodige étrange,
En nous donnant l’amour, voulut mêler en nous
Ce qui fait l’homme grand à ce qui le fait doux,
Moi, qui ne crains plus rien maintenant qu’elle
m’aime,
Moi, qui suis tout-puissant, grâce à son choix
suprême,
Moi, dont le cœur gonflé ferait envie aux rois,
Devant Dieu qui m’entend, sans peur, à haute voix,
Je le dis, vous pouvez vous confier, madame,
A mon bras comme reine, à mon cœur comme
femme!
Le dévoûment se cache au fond de mon amour
Pur et loyal!—Allez, ne craignez rien!—
Depuis quelques instants, un homme est entré par la porte du fond,
enveloppé d’un grand manteau, coiffé d’un chapeau galonné
d’argent. Il s’est avancé lentement vers Ruy Blas sans être vu, et, au
moment où Ruy Blas, ivre d’extase et de bonheur, lève les yeux au
ciel, cet homme lui pose brusquement la main sur l’épaule. Ruy Blas
se retourne comme réveillé subitement; l’homme laisse tomber son
manteau, et Ruy Blas reconnaît don Salluste. Don Salluste est vêtu
d’une livrée couleur de feu à galons d’argent, pareille à celle du page
de Ruy Blas.
SCÈNE CINQUIÈME.
RUY BLAS, DON SALLUSTE.

DON SALLUSTE, posant sa main sur l’épaule de Ruy Blas.

Bonjour.

RUY BLAS, effaré.

A part.

Grand Dieu! je suis perdu! le marquis!

DON SALLUSTE, souriant.

Je parie
Que tous ne pensiez pas à moi.

RUY BLAS.

Sa seigneurie
En effet me surprend.
A part.

Oh! mon malheur renaît.


J’étais tourné vers l’ange et le démon venait.
Il court à la tapisserie qui cache le cabinet secret, et en ferme la petite
porte au verrou; puis il revient tout tremblant vers don Salluste.

DON SALLUSTE.

Eh bien! comment cela va-t-il?

RUY BLAS, l’œil fixé sur don Salluste impassible, pouvant à peine
rassembler ses idées.

Cette livrée?...
DON SALLUSTE, souriant toujours.

Il fallait du palais me procurer l’entrée.


Avec cet habit-là l’on arrive partout.
J’ai pris votre livrée et la trouve à mon goût.
(Il se couvre. Ruy Blas reste tête nue.)

RUY BLAS.

Mais j’ai peur pour vous...

DON SALLUSTE.

Peur! Quel est ce mot


risible?

RUY BLAS.

Vous êtes exilé?

DON SALLUSTE.

Croyez-vous? c’est possible.

RUY BLAS.

Si l’on vous reconnaît, au palais, en plein jour?

DON SALLUSTE.

Ah bah! des gens heureux, qui sont des gens de cour,


Iraient perdre leur temps, ce temps qui sitôt passe,
A se ressouvenir d’un visage en disgrâce!
D’ailleurs, regarde-t-on le profil d’un valet?
Il s’assied dans un fauteuil, et Ruy Blas reste debout.

A propos, que dit-on à Madrid, s’il vous plaît?


Est-il vrai que, brûlant d’un zèle hyperbolique,
Ici, pour les beaux yeux de la caisse publique,
Vous exilez ce cher Priego, l’un des grands?
Vous avez oublié que vous êtes parents.
Sa mère est Sandoval, la vôtre aussi. Que diable!
Sandoval porte d’or à la bande de sable.
Regardez vos blasons, don César. C’est fort clair.
Cela ne se fait pas entre parents, mon cher.
Les loups pour nuire aux loups font-ils les bons
apôtres?
Ouvrez les yeux pour vous, fermez-les pour les
autres.
Chacun pour soi.

RUY BLAS, se rassurant un peu.

Pourtant, monsieur, permettez-moi.


Monsieur de Priego, comme noble du roi,
A grand tort d’aggraver les charges de l’Espagne.
Or, il va falloir mettre une armée en campagne;
Nous n’avons pas d’argent, et pourtant il le faut.
L’héritier bavarois penche à mourir bientôt.
Hier, le comte d’Harrach, que vous devez connaître,
Me le disait au nom de l’empereur son maître.
Si monsieur l’archiduc veut soutenir son droit,
La guerre éclatera...

DON SALLUSTE.

L’air me semble un peu froid.


Faites-moi le plaisir de fermer la croisée.
Ruy Blas, pâle de honte et de désespoir, hésite un moment; puis il fait
un effort et se dirige lentement vers la fenêtre, et revient vers don
Salluste, qui, assis dans le fauteuil, le suit des yeux d’un air
indifférent.

RUY BLAS, reprenant et essayant de convaincre don Salluste.

Daignez voir à quel point la guerre est malaisée.


Que faire sans argent? Excellence, écoutez.
Le salut de l’Espagne est dans nos probités.
Pour moi, j’ai, comme si notre armée était prête,
Fait dire à l’empereur que je lui tiendrais tête...

DON SALLUSTE, interrompant Ruy Blas et lui montrant son mouchoir


qu’il a laissé tomber en entrant.

Pardon! ramassez-moi mon mouchoir.


Ruy Blas, comme à la torture, hésite encore, puis se baisse, ramasse le
mouchoir, et le présente à don Salluste.

DON SALLUSTE, mettant le mouchoir dans sa poche.

—Vous disiez?...

RUY BLAS, avec un effort.

Le salut de l’Espagne!—oui, l’Espagne à nos pieds,


Et l’intérêt public demandent qu’on s’oublie.
Ah! toute nation bénit qui la délie.
Sauvons ce peuple! Osons être grands, et frappons!
Otons l’ombre à l’intrigue et le masque aux fripons!

DON SALLUSTE, nonchalamment.

Et d’abord ce n’est pas de bonne compagnie.—


Cela sent son pédant et son petit génie
Que de faire sur tout un bruit démesuré.
Un méchant million, plus ou moins dévoré,
Voilà-t-il pas de quoi pousser des cris sinistres!
Mon cher, les grands seigneurs ne sont pas de vos
cuistres.
Ils vivent largement. Je parle sans phébus.
Le bel air que celui d’un redresseur d’abus
Toujours bouffi d’orgueil et rouge de colère!
Mais bah! vous voulez être un gaillard populaire,
Adoré des bourgeois et des marchands d’esteufs.
C’est fort drôle. Ayez donc des caprices plus neufs.
Les intérêts publics? Songez d’abord aux vôtres.
Le salut de l’Espagne est un mot creux que d’autres
Feront sonner, mon cher, tout aussi bien que vous.
La popularité? c’est la gloire en gros sous.
Rôder, dogue aboyant, tout autour des gabelles?
Charmant métier! je sais des postures plus belles.
Vertu? foi? probité? c’est du clinquant déteint.
C’était usé déjà du temps de Charles-Quint.
Vous n’êtes pas un sot; faut-il qu’on vous guérisse
Du pathos? Vous tétiez encore votre nourrice,
Que nous autres déjà, nous avions sans pitié,
Gaîment, à coups d’épingle ou bien à coups de pié,
Crevant votre ballon au milieu des risées,
Fait sortir tout le vent de ces billevesées!

RUY BLAS.

Mais pourtant, monseigneur...

DON SALLUSTE, avec un sourire glacé.

Vous êtes étonnant.


Occupons-nous d’objets sérieux, maintenant.
D’un ton bref et impérieux.

—Vous m’attendrez demain toute la matinée,


Chez vous, dans la maison que je vous ai donnée.
La chose que je fais touche à l’événement.
Gardez pour nous servir les muets seulement.
Ayez dans le jardin, caché sous le feuillage,
Un carrosse attelé, tout prêt pour un voyage.
J’aurai soin des relais. Faites tout à mon gré.
—Il vous faut de l’argent. Je vous en enverrai.—
RUY BLAS.

Monsieur, j’obéirai. Je consens à tout faire.


Mais jurez-moi d’abord qu’en toute cette affaire
La reine n’est pour rien.

DON SALLUSTE, qui jouait avec un couteau d’ivoire sur la table, se


retourne à demi.

De quoi vous mêlez-vous?

RUY BLAS, chancelant et le regardant avec épouvante.

Oh! vous êtes un homme effrayant. Mes genoux


Tremblent... Vous m’entraînez vers un gouffre
invisible.
Oh! je sens que je suis dans une main terrible!
Vous avez des projets monstrueux. J’entrevoi
Quelque chose d’horrible...—Ayez pitié de moi.
Il faut que je vous dise, hélas! jugez vous-même!—
Vous ne le saviez pas! cette femme, je l’aime!

DON SALLUSTE, froidement.

Mais si. Je le savais.

RUY BLAS.

Vous le saviez!

DON SALLUSTE.

Pardieu!
Qu’est-ce que cela fait?

RUY BLAS, s’appuyant au mur pour ne pas tomber, et comme se parlant


à lui-même.

Donc il s’est fait un jeu,


Le lâche, d’essayer sur moi cette torture!
Mais c’est que ce serait une affreuse aventure!
Il lève les yeux au ciel.

Seigneur Dieu tout-puissant, mon Dieu qui


m’éprouvez,
Épargnez-moi, Seigneur!

DON SALLUSTE.

Ah çà, mais—vous rêvez!


Vraiment! vous vous prenez au sérieux, mon maître.
C’est bouffon. Vers un but que seul je dois connaître,
But plus heureux pour vous que vous ne le pensez,
J’avance. Tenez-vous tranquille. Obéissez.
Je vous l’ai déjà dit et je vous le répète,
Je veux votre bonheur. Marchez, la chose est faite.
Puis, grand’chose après tout que des chagrins
d’amour!
Nous passons tous par là. C’est l’affaire d’un jour.
Savez-vous qu’il s’agit du destin d’un empire?
Qu’est le vôtre à côté? Je veux bien tout vous dire,
Mais ayez le bon sens de comprendre aussi, vous.
Soyez de votre état. Je suis très-bon, très-doux,
Mais que diable! un laquais, d’argile humble ou
choisie,
N’est qu’un vase où je veux verser ma fantaisie.
De vous autres, mon cher, on fait tout ce qu’on veut.
Votre maître, selon le dessein qui l’émeut,
A son gré vous déguise, à son gré vous démasque.
Je vous ai fait seigneur. C’est un rôle fantasque,
—Pour l’instant.—Vous avez l’habillement complet.
Mais, ne l’oubliez pas, vous êtes mon valet.
Vous courtisez la reine ici par aventure,
Comme vous monteriez derrière ma voiture.
Soyez donc raisonnable.
RUY BLAS, qui l’a écouté avec égarement et comme ne pouvant en
croire ses oreilles.

O mon Dieu!—Dieu clément!


Dieu juste! de quel crime est-ce le châtiment?
Qu’est-ce donc que j’ai fait? Vous êtes notre père,
Et vous ne voulez pas qu’un homme désespère!
Voilà donc où j’en suis!—et volontairement,
Et sans tort de ma part,—pour voir,—uniquement
Pour voir agoniser une pauvre victime,
Monseigneur, vous m’avez plongé dans cet abîme.
Tordre un malheureux cœur plein d’amour et de foi,
Afin d’en exprimer la vengeance pour soi!
Se parlant à lui-même.

Car c’est une vengeance! oui, la chose est certaine


Et je devine bien que c’est contre la reine!
Qu’est-ce que je vais faire? Aller lui dire tout?
Ciel! devenir pour elle un objet de dégoût
Et d’horreur! un Crispin! un fourbe à double face!
Un effronté coquin qu’on bâtonne et qu’on chasse!
Jamais!—Je deviens fou, ma raison se confond!
Une pause. Il rêve.

O mon Dieu! voilà donc les choses qui se font!


Bâtir une machine effroyable dans l’ombre,
L’armer hideusement de rouages sans nombre,
Puis, sous la meule, afin de voir comment elle est,
Jeter une livrée, une chose, un valet,
Puis la faire mouvoir, et soudain sous la roue
Voir sortir des lambeaux teints de sang et de boue,
Une tête brisée, un cœur tiède et fumant,
Et ne pas frissonner alors qu’en ce moment
On reconnaît, malgré le mot dont on le nomme,
Que ce laquais était l’enveloppe d’un homme!
Se tournant vers don Salluste.

Mais il est temps encore! oh! monseigneur, vraiment!


L’horrible roue encor n’est pas en mouvement!
Il se jette à ses pieds.

Ayez pitié de moi! grâce! ayez pitié d’elle!


Vous savez que je suis un serviteur fidèle!
Vous l’avez dit souvent! voyez! je me soumets!
Grâce!

DON SALLUSTE.

Cet homme-là ne comprendra jamais.


C’est impatientant.

RUY BLAS, se traînant à ses pieds.

Grâce!

DON SALLUSTE.

Abrégeons, mon maître.


Il se tourne vers la fenêtre.

Gageons que vous avez mal fermé la fenêtre.


Il vient un froid par là!
Il va à la croisée et la ferme.

RUY BLAS, se relevant.

Oh! c’est trop! à présent


Je suis duc d’Olmedo, ministre tout-puissant!
Je relève le front sous le pied qui m’écrase.

DON SALLUSTE.
Comment dit-il cela? Répétez-donc la phrase.
Ruy Blas, duc d’Olmedo? Vos yeux ont un bandeau.
Ce n’est que sur Bazan qu’on a mis Olmedo.

RUY BLAS.

Je vous fais arrêter.

DON SALLUSTE.

Je dirai qui vous êtes.

RUY BLAS, exaspéré.

Mais...

DON SALLUSTE.

Vous m’accuserez? J’ai risqué nos deux têtes.


C’est prévu. Vous prenez trop tôt l’air triomphant.

RUY BLAS.

Je nierai tout!

DON SALLUSTE.

Allons! vous êtes un enfant.

RUY BLAS.

Vous n’avez pas de preuve!

DON SALLUSTE.

Et vous pas de mémoire.


Je fais ce que je dis, et vous pouvez m’en croire.
Vous n’êtes que le gant, et moi je suis la main.
Bas et se rapprochant de Ruy Blas.

Si tu n’obéis pas, si tu n’es pas demain


Chez toi pour préparer ce qu’il faut que je fasse,
Si tu dis un seul mot de tout ce qui se passe,
Si tes yeux, si ton geste en laissent rien percer,
Celle pour qui tu crains, d’abord, pour commencer,
Par ta folle aventure, en cent lieux répandue,
Sera publiquement diffamée et perdue,
Puis, elle recevra, ceci n’a rien d’obscur,
Sous cachet, un papier, que je garde en lieu sûr,
Écrit, te souvient-il avec quelle écriture?
Signé, tu dois savoir de quelle signature?
Voici ce que ses yeux y liront; «—Moi Ruy Blas,
«Laquais de monseigneur le marquis de Finlas,
«En toute occasion, ou secrète, ou publique,
«M’engage à le servir comme un bon domestique.»

RUY BLAS, brisé et d’une voix éteinte.

Il suffit.—Je ferai, monsieur, ce qu’il vous plaît.


La porte du fond s’ouvre. On voit rentrer les conseillers du conseil privé.

Don Salluste s’enveloppe vivement de son manteau.

DON SALLUSTE, bas.

On vient.
Il salue profondément Ruy Blas. Haut.

Monsieur le duc, je suis votre valet.


Il sort.

FIN DU TROISIÈME ACTE.


ACTE QUATRIÈME.
DON CÉSAR.
PERSONNAGES.

RUY BLAS.
DON CÉSAR.
DON SALLUSTE.
DON GURITAN.
UN LAQUAIS.
UNE DUÈGNE.
UN PAGE.
UN ALCADE.
DES ALGUAZILS.
DEUX MUETS.
ACTE QUATRIÈME.
Une petite chambre somptueuse et sombre. Lambris et meubles
de vieille forme et de vieille dorure. Murs couverts d’anciennes
tentures de velours cramoisi, écrasé et miroitant par places et
derrière le dos des fauteuils, avec de larges galons d’or qui le
divisent en bandes verticales. Au fond, une porte à deux
battants. A gauche, sur un pan coupé, une grande cheminée
sculptée du temps de Philippe II, avec écusson de fer battu
dans l’intérieur. Du côté opposé, sur un pan coupé, une petite
porte basse donnant dans un cabinet obscur. Une seule
fenêtre à gauche, placée très-haut et garnie de barreaux et
d’un auvent inférieur comme les croisées des prisons. Sur le
mur, quelques vieux portraits enfumés et à demi effacés.
Coffre de garde-robe avec miroir de Venise. Grands fauteuils
du temps de Philippe III. Une armoire très-ornée adossée au
mur. Une table carrée avec ce qu’il faut pour écrire. Un petit
guéridon de forme ronde à pieds dorés dans un coin. C’est le
matin.

Au lever du rideau, Ruy Blas, vêtu de noir, sans manteau et sans


la toison, vivement agité, se promène à grands pas dans la
chambre. Au fond se tient son page, immobile et comme
attendant ses ordres.

SCÈNE PREMIÈRE.
RUY BLAS, LE PAGE.

RUY BLAS, à part, et se parlant à lui-même.

Que faire?—Elle d’abord! elle avant tout!—rien qu’elle!


Dût-on voir sur un mur rejaillir ma cervelle,
Dût le gibet me prendre ou l’enfer me saisir
Il faut que je la sauve!—oui! mais y réussir,
Comment faire? donner mon sang, mon cœur, mon
âme,
Ce n’est rien, c’est aisé. Mais rompre cette trame!
Deviner...—deviner! car il faut deviner!—
Ce que cet homme a pu construire et combiner!
Il sort soudain de l’ombre et puis il s’y replonge,
Et là, seul dans sa nuit, que fait-il?—Quand j’y songe,
Dans le premier moment je l’ai prié pour moi!
Je suis un lâche, et puis c’est stupide!—eh bien quoi!
C’est un homme méchant.—Mais que je m’imagine
—La chose a sans nul doute une ancienne origine,—
Que lorsqu’il tient sa proie et la mâche à moitié,
Ce démon va lâcher la reine, par pitié
Pour son valet! Peut-on fléchir les bêtes fauves?
—Mais, misérable, il faut pourtant que tu la sauves!
C’est toi qui l’as perdue! à tout prix! il le faut!
—C’est fini. Me voilà retombé! De si haut!
Si bas! j’ai donc rêvé!—Ho! je veux qu’elle échappe!
Mais lui! par quelle porte, ô Dieu, par quelle trappe,
Par où va-t-il venir, l’homme de trahison?
Dans ma vie et dans moi, comme en cette maison,
Il est maître. Il en peut arracher les dorures.
Il a toutes les clefs de toutes les serrures.
Il peut entrer, sortir, dans l’ombre s’approcher,
Et marcher sur mon cœur comme sur ce plancher.
—Oui, c’est que je rêvais! le sort trouble nos têtes
Dans la rapidité des choses sitôt faites.—
Je suis fou. Je n’ai plus une idée en son lieu.
Ma raison dont j’étais si vain, mon Dieu! mon Dieu!
Prise en un tourbillon d’épouvante et de rage,
N’est plus qu’un pauvre jonc tordu par un orage!
Que faire? Pensons bien. D’abord empêchons-la
De sortir du palais.—Oh oui, le piége est là.
Sans doute. Autour de moi tout est nuit, tout est
gouffre.
Je sens le piége, mais je ne vois pas.—Je souffre!
C’est dit. Empêchons-la de sortir du palais.
Faisons-la prévenir sûrement, sans délais.—
Par qui?—je n’ai personne!
Il rêve avec accablement. Puis, tout à coup, comme frappé d’une idée
subite et d’une lueur d’espoir, il relève la tête.

—Oui, don Guritan l’aime!


C’est un homme loyal! oui!
Faisant un signe au page de s’approcher. Bas.

—Page, à l’instant même,


Va chez don Guritan, et fais-lui de ma part
Mes excuses, et puis dis-lui que sans retard
Il aille chez la reine et qu’il la prie en grâce,
En mon nom comme au sien, quoi qu’on dise ou
qu’on fasse,
De ne point s’absenter du palais de trois jours.
Quoi qu’il puisse arriver. De ne point sortir. Cours!
Rappelant le page.

Ah!
Il tire de son garde-notes une feuille et un crayon.

Qu’il donne ce mot à la reine, et qu’il veille!


Il écrit rapidement sur son genou.

—«Croyez don Guritan, faites ce qu’il conseille!»


Il ploie le papier et le remet au page.

Quant à ce duel, dis-lui que j’ai tort, que je suis


A ses pieds, qu’il me plaigne et que j’ai des ennuis,
Qu’il porte chez la reine à l’instant mes suppliques,
Et que je lui ferai des excuses publiques.
Qu’elle est en grand péril. Qu’elle ne sorte point.
Quoi qu’il arrive. Au moins trois jours.—De point en
point
Fais tout. Va, sois discret, ne laisse rien paraître.

LE PAGE.

Je vous suis dévoué. Vous êtes un bon maître.

RUY BLAS.

Cours, mon bon petit page. As-tu bien tout compris!

LE PAGE.

Oui, monseigneur, soyez tranquille.


Il sort.

RUY BLAS, resté seul, tombant sur un fauteuil.

Mes esprits
Se calment. Cependant, comme dans la folie,
Je sens confusément des choses que j’oublie.
Oui, le moyen est sûr. Don Guritan...!—mais moi?
Faut-il attendre ici don Salluste? Pourquoi?
Non. Ne l’attendons pas. Cela le paralyse
Tout un grand jour. Allons prier dans quelque église.
Sortons. J’ai besoin d’aide, et Dieu m’inspirera!
Il prend son chapeau sur une crédence, et secoue une sonnette posée
sur la table. Deux nègres, vêtus de velours vert-clair et de brocard
d’or, jaquettes plissées à grandes basques, paraissent à la porte du
fond.
Je sors. Dans un instant un homme ici viendra.
—Par une entrée à lui.—Dans la maison, peut-être,
Vous le verrez agir comme s’il était maître.
Laissez-le faire. Et si d’autres viennent...
Après avoir hésité un moment.

Ma foi,
Vous laisserez entrer!—
Il congédie du geste les noirs, qui s’inclinent en signe d’obéissance et
qui sortent.

Allons?
Il sort.

Au moment où la porte se referme sur Ruy Blas, on entend un grand


bruit dans la cheminée, par laquelle on voit tomber tout à coup un
homme, enveloppé d’un manteau déguenillé, qui se précipite dans la
chambre. C’est don César.
SCÈNE DEUXIÈME.
DON CÉSAR.

Effaré, essoufflé, décoiffé, étourdi, avec une expression joyeuse et


inquiète en même temps.

Tant pis! c’est moi!


Il se relève en se frottant la jambe sur laquelle il est tombé, et s’avance
dans la chambre avec force révérences et chapeau bas.

Pardon! ne faites pas attention, je passe.


Vous parliez entre vous. Continuez, de grâce.
J’entre un peu brusquement, messieurs, j’en suis
fâché!
Il s’arrête au milieu de la chambre et s’aperçoit qu’il est seul.

—Personne!—sur le toit tout à l’heure perché,


J’ai cru pourtant ouïr un bruit de voix.—Personne!
S’asseyant dans un fauteuil.

Fort bien. Recueillons-nous. La solitude est bonne.


—Ouf! que d’événements!—J’en suis émerveillé
Comme l’eau qu’il secoue aveugle un chien mouillé.
Primo, ces alguazils qui m’ont pris dans leurs serres;
Puis cet embarquement absurde; ces corsaires;
Et cette grosse ville où l’on m’a tant battu;
Et les tentations faites sur ma vertu
Par cette femme jaune; et mon départ du bagne:
Mes voyages; enfin, mon retour en Espagne!
Puis, quel roman! le jour où j’arrive, c’est fort,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like