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

C Programming Building Blocks Of Modern Code Edet Theophilus pdf download

The document is a comprehensive guide titled 'C Programming: Building Blocks of Modern Code' by Theophilus Edet, aimed at both novice and experienced programmers. It covers a wide range of topics including the history of C, programming concepts, data structures, memory management, and modern coding practices, emphasizing hands-on learning and practical applications. The book serves as a roadmap for mastering C programming and its relevance in contemporary software development.

Uploaded by

johnspatte8t
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)
15 views

C Programming Building Blocks Of Modern Code Edet Theophilus pdf download

The document is a comprehensive guide titled 'C Programming: Building Blocks of Modern Code' by Theophilus Edet, aimed at both novice and experienced programmers. It covers a wide range of topics including the history of C, programming concepts, data structures, memory management, and modern coding practices, emphasizing hands-on learning and practical applications. The book serves as a roadmap for mastering C programming and its relevance in contemporary software development.

Uploaded by

johnspatte8t
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/ 88

C Programming Building Blocks Of Modern Code

Edet Theophilus download

https://ebookbell.com/product/c-programming-building-blocks-of-
modern-code-edet-theophilus-54936130

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Pro Tbb C Parallel Programming With Threading Building Blocks 1st


Edition Michael Voss

https://ebookbell.com/product/pro-tbb-c-parallel-programming-with-
threading-building-blocks-1st-edition-michael-voss-50195056

Learning C 7 By Developing Games With Unity 2017 Learn C Programming


By Building Fun And Interactive Games With Unity Third Edition 3rd
Edition Micael Dagraca Greg Lukosek

https://ebookbell.com/product/learning-c-7-by-developing-games-with-
unity-2017-learn-c-programming-by-building-fun-and-interactive-games-
with-unity-third-edition-3rd-edition-micael-dagraca-greg-
lukosek-7250930

Handson Game Development With Webassembly Learn Webassembly C


Programming By Building A Retro Space Game 1st Edition Rick Battagline

https://ebookbell.com/product/handson-game-development-with-
webassembly-learn-webassembly-c-programming-by-building-a-retro-space-
game-1st-edition-rick-battagline-36528724

Programming C Building Net Applicationscover Updated For Vsnet 10cover


Includes Index 2nd Ed Jesse Liberty

https://ebookbell.com/product/programming-c-building-net-
applicationscover-updated-for-vsnet-10cover-includes-index-2nd-ed-
jesse-liberty-4106468
Programming C Building Net Applications With C 4th Edition Jesse
Liberty

https://ebookbell.com/product/programming-c-building-net-applications-
with-c-4th-edition-jesse-liberty-925808

C Programming Handbook For Beginners On Gui Development With Qt A


Stepbystep Guide To Building Crossplatform Gui Applications Using C
And Qt Framework 1st Edition Tech Greeny

https://ebookbell.com/product/c-programming-handbook-for-beginners-on-
gui-development-with-qt-a-stepbystep-guide-to-building-crossplatform-
gui-applications-using-c-and-qt-framework-1st-edition-tech-
greeny-220579132

Learning C By Developing Games With Unity 2021 Kickstart Your C


Programming And Unity Journey By Building 3d Games From Scrat Sixth
Edition Harrison Ferrone

https://ebookbell.com/product/learning-c-by-developing-games-with-
unity-2021-kickstart-your-c-programming-and-unity-journey-by-
building-3d-games-from-scrat-sixth-edition-harrison-ferrone-47965372

Diy Microcontroller Projects For Hobbyists The Ultimate Projectbased


Guide To Building Realworld Embedded Applications In C And C
Programming 1st Edition Miguel Angel Garciaruiz

https://ebookbell.com/product/diy-microcontroller-projects-for-
hobbyists-the-ultimate-projectbased-guide-to-building-realworld-
embedded-applications-in-c-and-c-programming-1st-edition-miguel-angel-
garciaruiz-33789590

Programming Firefox Building Applications In The Browser 1st Edition


Kenneth C Feldt

https://ebookbell.com/product/programming-firefox-building-
applications-in-the-browser-1st-edition-kenneth-c-feldt-36702404
C Programming: Building Blocks of Modern Code
By Theophilus Edet
Theophilus Edet
theoedet@yahoo.com

facebook.com/theoedet

twitter.com/TheophilusEdet

Instagram.com/edettheophilus
Copyright © 2023 Theophilus Edet All rights reserved.
No part of this publication may be reproduced, distributed, or transmitted in any form or by any
means, including photocopying, recording, or other electronic or mechanical methods, without the
prior written permission of the publisher, except in the case of brief quotations embodied in reviews
and certain other non-commercial uses permitted by copyright law.
Table of Contents
Preface
C Programming: Building Blocks of Modern Code

Module 1: Introduction to C Programming


Historical Overview
Importance in Modern Computing
Setting up C Development Environment
Basic Structure of a C Program

Module 2: Variables in C
Data Types and Declarations
Memory Allocation
Constants and Literals
Dynamic Memory Allocation

Module 3: Functions in C
Function Declaration and Definition
Parameters and Return Values
Function Prototypes
Recursion in C

Module 4: Conditions and Decision Making


if, else if, else Statements
Switch-Case Statements
Ternary Operator
Best Practices for Decision Making in C

Module 5: Collections in C
Arrays and Pointers
Strings in C
Multi-dimensional Arrays
Dynamic Arrays

Module 6: Loops in C
while Loop
for Loop
do-while Loop
Loop Control Statements

Module 7: Comments and Documentation


Importance of Comments
Commenting Best Practices
Generating Documentation
Doxygen and its Usage in C

Module 8: Enumerations in C
Introduction to Enums
Creating Enums
Enum Applications in C
Best Practices for Enum Usage
Module 9: Classes in C
Overview of Object-Oriented Programming in C
Defining and Using Classes
Constructors and Destructors
Encapsulation in C

Module 10: Accessors and Mutators


Getters and Setters
Access Specifiers in C
Designing Accessor Methods
Ensuring Data Integrity with Mutators

Module 11: Scope in C


Block Scope
Function Scope
File Scope
Global Scope and Lifetime

Module 12: Advanced Functions


Function Pointers
Callback Functions
Variadic Functions
Anonymous Functions (Lambda Functions)

Module 13: Memory Management in C


Understanding Pointers
Memory Leak Detection
Garbage Collection in C
Best Practices for Memory Allocation

Module 14: File Handling in C


Working with Text Files
Binary File Operations
Error Handling in File Operations
File I/O Best Practices

Module 15: Error Handling and Debugging


Common Errors in C Programming
Debugging Techniques
Error Handling Strategies
Unit Testing in C

Module 16: Preprocessor Directives


Macros in C
Conditional Compilation
File Inclusion
Best Practices for Preprocessor Usage

Module 17: Advanced Data Structures


Linked Lists
Stacks and Queues
Trees and Graphs
Hash Tables in C

Module 18: Interfacing with Hardware


Using C for Hardware Control
Embedded Systems Programming
Device Drivers in C
Accessing I/O Ports

Module 19: Network Programming in C


Socket Programming
Client-Server Communication
Protocol Implementation
Security Considerations

Module 20: Multithreading and Concurrency


Basics of Multithreading
Thread Synchronization
Mutexes and Semaphores
Parallel Programming in C

Module 21: Optimization Techniques


Code Profiling
Performance Analysis Tools
Compiler Optimizations
Writing Efficient Code in C

Module 22: Secure Coding Practices


Common Security Vulnerabilities
Input Validation
Buffer Overflows
Encryption and Decryption in C

Module 23: GUI Programming in C


Introduction to GUI
Using GUI Libraries in C
Designing User Interfaces
Event Handling in GUI Applications

Module 24: C in the Modern Software Ecosystem


Integration with Other Languages
C in Web Development
C in Mobile App Development
C in Cloud Computing

Module 25: C Standard Library


Overview of Standard Library Functions
Input/Output Functions
String Manipulation Functions
Math and Time Functions in C

Module 26: C and Data Science


Using C for Data Analysis
Integration with Data Science Libraries
C in Machine Learning
Data Visualization in C

Module 27: C and Artificial Intelligence


Overview of AI
Integrating C with AI Frameworks
C in Neural Network Development
AI Applications in C
Module 28: C in Game Development
Basics of Game Development
Graphics Programming in C
Input Handling in Games
Game Design Patterns in C

Module 29: Future Trends in C Programming


C and Quantum Computing
C in Edge Computing
Role of C in Emerging Technologies
Continuous Learning and Adaptation

Module 30: Conclusion and Beyond


Recap of Key Concepts
Building a Strong Foundation in C
Paths for Further Learning
Embracing the Evolution of C Programming

Review Request
Embark on a Journey of ICT Mastery with CompreQuest Books
Welcome to the fascinating journey into the world of C
Preface programming, where the essence of modern code creation
unfolds through the pages of this comprehensive guide. In the
rapidly evolving landscape of technology, C remains an unparalleled
language, and this book aims to be your trusted companion in mastering its
intricacies.
Exploring the Essence of the Book:
"C Programming: Building Blocks of Modern Code" is not just another
programming manual; it is a roadmap for harnessing the power of C to
build robust and efficient modern code. This book is meticulously crafted to
provide a thorough understanding of C programming concepts, with a focus
on their relevance in contemporary software development.
Pedagogical Style of Presentation:
Learning programming is a transformative journey, and we understand that
effective teaching requires clarity, engagement, and practical relevance. The
pedagogical style adopted in this book is designed to make complex
concepts accessible to learners of all levels. We believe in the power of
hands-on learning, and each module is enriched with examples, exercises,
and real-world applications to reinforce theoretical knowledge.
What Readers Stand to Benefit:
Whether you are a novice programmer or an experienced developer, this
book offers valuable insights and practical skills. Novices will find a
structured and approachable introduction to C, while experienced
programmers can delve into advanced topics and modern coding practices.
The book caters to diverse learning styles, providing a solid foundation for
everyone.
Readers can expect to gain proficiency in:

1. Fundamentals of C Programming: The book starts with a


solid grounding in the basics, ensuring that readers comprehend
the foundational elements of C programming.
2. Modern Coding Practices: We emphasize modern coding
practices, exploring C's relevance in contemporary software
development. Concepts like dynamic memory allocation, data
structures, and file handling are presented with a focus on best
practices.
3. Application Development: Practical examples and projects
guide readers in applying their knowledge to real-world
scenarios, fostering a hands-on approach and reinforcing their
programming skills.
4. Problem-Solving Techniques: The book emphasizes problem-
solving strategies, honing the reader's ability to approach
coding challenges systematically. From algorithmic thinking to
debugging, the skills acquired are transferable to any
programming language.
5. Efficient Code Optimization: Understanding the nuances of
compiler optimizations, memory management, and code
efficiency becomes second nature, enabling readers to write
high-performance code.
Call to Action:
Embark on this journey with us, and you'll discover the fabulous and
glamorous world of C programming. Beyond the syntax and semantics, C
offers a canvas for creative expression and problem-solving. It's a language
that empowers you to build the foundation of modern software, from
operating systems to embedded systems, and everything in between.
As you navigate through the chapters, embrace the challenges and triumphs
that come with learning to code in C. Engage with the examples,
experiment with the code, and, most importantly, apply your newfound
knowledge to real-world projects. The true essence of programming is
revealed in the act of creation, and C is your gateway to crafting the future
of technology.
This book is more than a learning resource; it's an invitation to become a
part of the vibrant community of C programmers who shape the digital
world. Welcome to the journey of mastering C programming, where the
building blocks you acquire will lay the groundwork for your endeavors in
the vast and ever-evolving landscape of modern coding.

Theophilus Edet
C Programming: Building Blocks of
Modern Code
Introduction to C Programming: Building Blocks of Modern Code
C Programming stands as a cornerstone in the realm of computer
programming, and the book "C Programming: Building Blocks of Modern
Code" delves into its intricacies, providing a comprehensive guide to both
novice and experienced programmers. This timeless language, created by
Dennis Ritchie in the early 1970s, has left an indelible mark on the software
development landscape. Its influence extends far beyond its inception,
shaping the foundations of modern computing.
C as a Versatile Programming Language
At its core, C is celebrated for its versatility. It serves as the progenitor of
numerous programming languages, owing to its simplicity, efficiency, and
expressiveness. The book begins by elucidating the fundamental principles
that make C an ideal choice for myriad applications. Whether crafting
system-level software, embedded systems, or high-performance
applications, C's flexibility empowers programmers to wield it as a
powerful tool in their arsenal.
Programming Models and Paradigms
The strength of C lies not only in its syntax but also in its support for
various programming models and paradigms. The book navigates through
these, unraveling the layers of procedural programming where C excels.
With a focus on procedural abstraction, the book elucidates how C allows
developers to structure code in a modular fashion, fostering code reusability
and maintainability.
Moving beyond procedural programming, the book explores C's support for
imperative programming. Its ability to handle sequential execution with
clear control flow structures makes it an adept language for writing clear
and concise algorithms. Readers will gain insights into how C
accommodates imperative programming principles, providing a solid
foundation for algorithmic development.
Furthermore, the book ventures into the world of structured programming.
Here, C shines with its support for modular design, emphasizing the
creation of functions and structures to enhance code organization. The
paradigm of structured programming aligns seamlessly with C, promoting
code clarity and ease of maintenance.
As the journey through the book progresses, readers will encounter the
elegance of C in supporting low-level programming. From direct memory
manipulation to bit-level operations, C provides unparalleled control,
making it an indispensable language for system programming and
embedded systems development.
"C Programming: Building Blocks of Modern Code" is more than a guide;
it's a companion for those navigating the expansive landscape of C
programming. With a focus on applications, programming models, and
paradigms, this book aims to equip readers with the knowledge and skills
needed to harness the full potential of C and lay the foundation for robust,
efficient, and modern code.
Module 1:
Introduction to C Programming

Unveiling the Foundations


The module "Introduction to C Programming" serves as the gateway to the
expansive world of one of the most influential programming languages —
C. As the foundational chapter of the book "C Programming: Building
Blocks of Modern Code," this module takes readers on a journey through
the origins, key characteristics, and the enduring legacy of C.
The Genesis of C: A Historical Perspective
At the heart of this module lies the exploration of C's genesis. Dennis
Ritchie's creation of C in the early 1970s at Bell Labs marked a paradigm
shift in programming languages. Rooted in the need for a versatile and
powerful language to develop the UNIX operating system, C quickly
outgrew its initial purpose, becoming a linchpin in software development.
Key Characteristics of C: Simplicity and Power in Harmony
The module illuminates the intrinsic qualities that make C both accessible
and powerful. Its syntax, inspired by earlier languages like B and BCPL,
strikes a delicate balance between simplicity and expressiveness. Readers
will delve into the elegance of C, a language that favors clarity and
conciseness without sacrificing the ability to tackle complex programming
tasks.
Enduring Legacy: C's Impact on Modern Programming
Beyond mere syntax, the module sheds light on C's enduring legacy. With
its influence evident in languages like C++, Java, and even modern
scripting languages, C stands as a testament to the robustness of its design.
The module articulates how C's influence transcends time, permeating
diverse domains from system-level programming to embedded systems and
beyond.
Navigating the Module: An Overview of What's to Come
To guide readers through this exploration, the module provides a roadmap
for what lies ahead in the book. It offers a glimpse into the topics that will
be covered, from fundamental concepts like variables and functions to
advanced discussions on memory management and programming
paradigms. This roadmap ensures that readers embark on their C
programming journey with a clear understanding of the terrain they are
about to traverse.
In essence, "Introduction to C Programming" sets the stage for a holistic
understanding of C. It invites readers to appreciate the language not just as
a tool for writing code but as a profound and enduring presence in the
evolution of modern computing.

Historical Overview
The Historical Overview of the Introduction to C Programming
module in the book "C Programming: Building Blocks of Modern
Code" provides a comprehensive journey through the evolution of the
C programming language. C, conceived by Dennis Ritchie at Bell
Labs in the early 1970s, emerged as a successor to the B
programming language. This section delves into the motivations
behind creating C and its early applications.
Birth of C Programming Language
In the late 1960s and early 1970s, computing faced challenges with
the proliferation of diverse hardware architectures. Developers
needed a versatile language that could adapt to different systems
without sacrificing performance. Dennis Ritchie, along with Ken
Thompson, began working on what would become the C language.
They aimed to create a portable and efficient tool for systems
programming, initially implementing it on the PDP-11.
Impact on Unix and Systems Programming
The section explores the symbiotic relationship between C and the
Unix operating system. C became the language of choice for
developing Unix, enabling the creation of a robust and portable
operating system. The Unix philosophy, favoring simplicity and
composability, aligns seamlessly with the design principles of C.
Together, they laid the foundation for modern systems programming,
influencing subsequent generations of operating systems.
Standardization and ANSI C
As C gained popularity, the need for standardization arose to ensure
compatibility across different implementations. The American
National Standards Institute (ANSI) played a pivotal role in
formalizing the language specifications. The book navigates through
the evolution of C standards, highlighting key features introduced in
each version. The significance of ANSI C lies in providing a common
ground for developers, fostering consistency and interoperability.
C in Embedded Systems and Real-Time Applications
Beyond its role in systems programming, C found a niche in
embedded systems and real-time applications. The Historical
Overview explores how C's efficiency and low-level control make it
well-suited for programming microcontrollers and other resource-
constrained environments. The section delves into practical examples
of C code for embedded systems, elucidating its relevance in modern
technological landscapes.
Legacy and Continued Relevance
The section concludes by emphasizing the enduring legacy of C.
Despite the emergence of newer languages, C continues to be a
fundamental building block of modern code. Its influence extends
beyond systems programming to various domains, including game
development, firmware, and high-performance computing. The
Historical Overview serves as a bridge between C's origins and its
enduring impact on contemporary software development.

Importance in Modern Computing


The module "Introduction to C Programming" within the book "C
Programming: Building Blocks of Modern Code" meticulously
explores the enduring importance of C in contemporary computing.
This section illuminates how C's efficiency, versatility, and low-level
control make it a linchpin in the modern software development
landscape.
Foundational Role in Software Development
C programming serves as the bedrock for many modern
programming languages. Understanding C provides a solid
foundation for grasping the principles of memory management,
pointers, and low-level operations. For instance, the syntactical
structure of C has heavily influenced languages like C++, C#, and
Objective-C, making it an invaluable precursor for developers
venturing into diverse programming paradigms.
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}

The simplicity of the "Hello, World!" program above highlights C's


elegance and straightforward syntax, offering a gentle entry point for
beginners while establishing fundamental programming concepts.
Efficiency and Performance Optimization
In the realm of performance-critical applications, C's efficiency
shines. This section delves into the intricacies of writing optimized
code, emphasizing C's role in achieving maximum performance.
Through examples like loop unrolling and manual memory
management, the module elucidates how C empowers developers to
fine-tune code for speed, a crucial aspect in domains such as game
development and scientific computing.
#include <stdio.h>

void multiplyMatrix(int a[3][3], int b[3][3], int result[3][3]) {


// Matrix multiplication logic
}
int main() {
int matrixA[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrixB[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3];

multiplyMatrix(matrixA, matrixB, result);

// Display the result matrix


// ...

return 0;
}

The above code snippet showcases a matrix multiplication function,


demonstrating the precision and control that C offers in optimizing
computational tasks.
Low-Level System Interaction
C's ability to interact directly with hardware and low-level system
components is crucial in modern computing. From operating systems
to device drivers, C remains the language of choice for tasks
requiring intimate access to hardware resources. The section
illustrates how system calls and kernel interactions in C facilitate the
development of robust and efficient software that interfaces
seamlessly with the underlying infrastructure.
The "Importance in Modern Computing" section underscores C's
foundational role, performance optimization capabilities, and low-
level system interaction as key contributors to its enduring
significance in the ever-evolving landscape of software development.

Setting up C Development Environment


The "Setting up C Development Environment" section in the
"Introduction to C Programming" module of the book "C
Programming: Building Blocks of Modern Code" serves as a
practical guide for readers to establish a conducive environment for C
programming. A well-configured development environment is crucial
for efficient coding and testing. This section not only outlines the
fundamental components required but also provides detailed steps for
setting up a C development environment.
Installing a C Compiler
The first step in setting up a C development environment is installing
a C compiler. The section details the process of installing a compiler
like GCC (GNU Compiler Collection) on different operating systems,
ensuring readers have a working compiler to translate their C code
into executable programs.
# Installing GCC on Linux
sudo apt-get update
sudo apt-get install build-essential

Choosing an Integrated Development Environment (IDE)


While a basic text editor can suffice for C programming, using a
feature-rich IDE enhances the development experience. The module
explores the benefits of using an IDE and guides readers in setting up
Visual Studio Code (VS Code) for C development.
# Installing VS Code on Ubuntu
sudo snap install --classic code

Configuring VS Code for C Programming


Once VS Code is installed, the section provides step-by-step
instructions for configuring the IDE to support C programming. This
includes installing the C/C++ extension, setting up build tasks, and
configuring debugging options.
// .vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "gcc",
"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"]
}
]
}

The above code snippet illustrates a simple build task in VS Code's


tasks.json file, allowing users to compile their C code with the GCC
compiler directly from the IDE.
Adding Compiler Path to System Environment
To ensure seamless compilation from the command line, the section
guides users in adding the compiler's path to the system environment
variables. This step is crucial for enabling the execution of compiler
commands from any directory in the terminal.
# Adding GCC to the PATH on Linux
export PATH=$PATH:/path/to/gcc

The "Setting up C Development Environment" section not only


emphasizes the importance of a well-configured environment but also
provides hands-on guidance, making it accessible for readers to set
up their C development environment using a powerful and popular
IDE like Visual Studio Code.
Basic Structure of a C Program
The module "Introduction to C Programming" in the book "C
Programming: Building Blocks of Modern Code" dives into the
essential foundation of C programming by dissecting the basic
structure of a C program. Understanding this structure is crucial for
novices as it lays the groundwork for writing efficient and organized
code.
Include Directives
A C program typically begins with include directives to bring in
libraries and header files, essential for accessing predefined functions
and features. For instance, the #include <stdio.h> directive includes
the standard input/output library, allowing the use of functions like
printf and scanf.
#include <stdio.h>

Main Function
The heart of every C program is the main function. Execution starts
from the main function, making it a mandatory component. The main
function encapsulates the code that will be executed when the
program runs.
int main() {
// Code inside the main function
return 0;
}

The int before main indicates that the function returns an integer
value, conventionally used to convey the program's exit status.
Variables and Data Types
Following the main function, C programs often declare variables to
store and manipulate data. C supports various data types such as int,
float, and char. Declaring variables with specific data types helps in
efficient memory allocation.
int main() {
int age = 25;
float height = 5.9;
char grade = 'A';
// Additional variable declarations and code
return 0;
}

Statements and Control Flow


C programs execute a series of statements within the main function.
These statements can include assignments, mathematical operations,
and conditional structures like if and else for control flow.
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
// Additional statements and code
return 0;
}

Functions
Beyond the main function, C programs can define additional
functions to modularize code. Functions promote code reuse and
maintainability. They consist of a return type, a function name,
parameters, and the function body.
int add(int a, int b) {
return a + b;
}

int main() {
int result = add(3, 7);
printf("Sum: %d\n", result);
return 0;
}

The "Basic Structure of a C Program" section thus guides learners


through the key components, enabling them to comprehend the
anatomy of a C program and fostering a solid foundation for
subsequent learning in the realm of C programming.
Module 2:
Variables in C

The Pillars of Data Storage and Manipulation


In the module "Variables in C," readers embark on a pivotal exploration of
one of the foundational elements that make C a powerhouse in
programming. This chapter of "C Programming: Building Blocks of
Modern Code" delves into the essence of variables, elucidating their role as
the bedrock of data storage and manipulation within the C programming
paradigm.
Fundamentals of Variables: Storage Units for Data
At its core, this module demystifies the concept of variables. Variables, in
the C language, serve as dynamic containers capable of holding various
data types. Readers will grasp the fundamental idea that, in C, variables act
as storage units, allowing programmers to manipulate and work with
different types of data efficiently.
Data Types: Shaping the Character of Variables
The module extends its focus to the diverse data types that variables can
encapsulate. From integers and floating-point numbers to characters and
pointers, the versatility of C becomes apparent. Each data type carries
unique properties, influencing how data is stored, processed, and interpreted
by the program. This nuanced understanding is critical for crafting efficient
and precise C code.
Variable Declaration and Initialization: Crafting the Blueprint
An integral aspect of mastering variables in C involves the intricacies of
declaration and initialization. This module delves into the syntax and
semantics of declaring variables, emphasizing the importance of adhering to
C's strict typing rules. Readers will grasp how the process of initialization
sets the initial values of variables, laying the groundwork for a program's
execution.
Scope and Lifetime: Navigating the Temporal Landscape
Beyond the basic concepts, the module ventures into the notions of scope
and lifetime. These characteristics govern when and where variables exist
within a program. From local variables confined to specific blocks of code
to global variables with broader visibility, understanding the temporal
landscape of variables is essential for writing robust and maintainable C
programs.
As readers progress through "Variables in C," they not only gain a profound
understanding of the mechanics behind variables but also develop a
foundational knowledge that will prove invaluable as they delve into more
advanced programming concepts. This module serves as a cornerstone in
building a solid comprehension of C programming, setting the stage for the
mastery of subsequent building blocks in the world of modern code.
Data Types and Declarations
The "Variables in C" module within the book "C Programming:
Building Blocks of Modern Code" delves into the critical aspect of
data types and declarations, elucidating how they form the backbone
of variable handling in C programming. Understanding data types is
paramount for efficient memory utilization and ensuring accurate
representation of information.
Fundamental Data Types
C provides several fundamental data types, each serving a specific
purpose. The int data type, for instance, is commonly used for storing
integer values.
int age = 25;

Here, the variable age is declared as an integer and assigned the value
25. Similarly, the float data type is employed for decimal or floating-
point values.
float height = 5.9;

The char data type is reserved for single characters, while double is
used for double-precision floating-point numbers.
char grade = 'A';
double pi = 3.14159;

Derived Data Types


In addition to fundamental types, C supports derived data types like
arrays, structures, and pointers. Arrays allow the grouping of
elements under a single variable name, facilitating the storage of
collections of data.
int scores[5] = {85, 90, 78, 92, 88};

Here, an integer array scores is declared to hold five elements. The


indices allow accessing individual values within the array.
User-Defined Data Types
C also enables the creation of user-defined data types through
structures. Structures group multiple variables under a single name,
enhancing code organization and readability.
struct Point {
int x;
int y;
};

struct Point p1 = {3, 7};

The code snippet defines a structure named Point with two members
x and y. An instance p1 is then declared, representing a point in a
Cartesian coordinate system.
Pointers for Memory Management
Pointers are a powerful feature in C, allowing direct manipulation of
memory addresses. They enhance efficiency and flexibility but
require careful handling to avoid memory-related issues.
int num = 42;
int *ptr = &num;
In this example, a pointer ptr is declared to store the address of the
variable num. This provides a means to indirectly access and modify
the value of num through the pointer.

Type Modifiers
C includes type modifiers to adjust the range and nature of data types.
For instance, unsigned can be used to declare variables that only store
positive values, effectively doubling the positive range of int.
unsigned int positiveNumber = 100;

The "Data Types and Declarations" section serves as a


comprehensive guide within the "Variables in C" module, laying the
groundwork for effective variable usage by exploring fundamental
and derived data types, user-defined structures, pointers, and type
modifiers. Understanding these concepts is pivotal for writing robust
and efficient C programs.

Memory Allocation
The "Variables in C" module within the book "C Programming:
Building Blocks of Modern Code" delves into the crucial concept of
memory allocation. Understanding how memory is allocated and
managed is essential for writing efficient and reliable C programs.
This section illuminates the different aspects of memory allocation,
from static allocation to dynamic allocation.
Static Memory Allocation
In C, memory can be statically allocated during compile-time.
Variables declared with a fixed size are assigned memory when the
program is compiled, and this memory remains constant throughout
the program's execution.
int count = 10; // Static memory allocation

In this example, the variable count is statically allocated memory to


store an integer value. The size of the memory is determined at
compile-time and remains unchanged during program execution.
Dynamic Memory Allocation
Dynamic memory allocation, on the other hand, allows the program
to request memory during runtime, providing flexibility for varying
data requirements. The malloc function is commonly used for
dynamic memory allocation.
int *dynamicArray = (int *)malloc(5 * sizeof(int));

Here, malloc allocates memory for an array of five integers. The


sizeof(int) ensures that the correct amount of memory is allocated
based on the system's integer size. It's important to note that
dynamically allocated memory needs to be explicitly deallocated
using the free function to avoid memory leaks.
free(dynamicArray); // Deallocating dynamically allocated memory

Pointers and Memory Allocation


Pointers play a pivotal role in memory allocation. They can be used
to access dynamically allocated memory, providing a mechanism to
manipulate memory locations directly.
int *dynamicVariable = (int *)malloc(sizeof(int));
*dynamicVariable = 42; // Storing a value in dynamically allocated memory

This example demonstrates dynamic memory allocation for a single


integer. The pointer dynamicVariable holds the memory address, and
the value 42 is stored at that location.
Memory Allocation for Arrays and Structures
Memory allocation extends to arrays and structures. When creating
dynamic arrays or structures, careful memory management is
essential to prevent memory leaks or undefined behavior.
struct Point {
int x;
int y;
};

struct Point *pointArray = (struct Point *)malloc(3 * sizeof(struct Point));


Here, dynamic memory is allocated for an array of three Point
structures. It's crucial to release this memory using free when it is no
longer needed.
Understanding memory allocation is fundamental to writing efficient
and reliable C programs. The "Memory Allocation" section of the
"Variables in C" module provides a comprehensive exploration of
both static and dynamic memory allocation, empowering
programmers to make informed decisions regarding memory usage in
their C code.

Constants and Literals


The module on "Variables in C" within the book "C Programming:
Building Blocks of Modern Code" explores the significant role of
constants and literals in programming. Constants are fixed values that
do not change during the execution of a program, while literals
represent these constant values in a program's source code.
Understanding how to use and declare constants and literals is
essential for writing code that is both readable and maintainable.
Numeric Constants
Numeric constants represent fixed numerical values in a program.
They can be integers, floating-point numbers, or even in scientific
notation. For instance, an integer constant is declared as follows:
const int MAX_COUNT = 100;

In this example, MAX_COUNT is a constant holding the value 100,


and the const keyword ensures that the value cannot be modified
throughout the program's execution.
Character and String Literals
Character literals represent individual characters, enclosed within
single quotes, and are used to assign values to char variables or
constants.
const char GRADE = 'A';
String literals, on the other hand, are sequences of characters
enclosed within double quotes.
const char *welcomeMessage = "Hello, World!";

Here, welcomeMessage is a constant pointer to a string literal. The


use of pointers in string literals allows for efficient manipulation and
storage of character sequences.
Symbolic Constants
Symbolic constants are identifiers that represent constant values in a
program. They are often defined using the #define preprocessor
directive.
#define PI 3.14159

This example declares a symbolic constant PI with the value 3.14159.


Symbolic constants enhance code readability and maintainability by
providing meaningful names for fixed values.
Enumerations
Enumerations, or enums, allow programmers to create named integer
constants. They provide a way to represent a set of named integer
values with more meaningful names.
enum Days { MON, TUE, WED, THU, FRI, SAT, SUN };

Here, an enum named Days is declared, representing the days of the


week with corresponding integer values. Enums enhance code clarity
by replacing "magic numbers" with meaningful identifiers.
Hexadecimal and Octal Literals
C supports hexadecimal and octal literals for expressing values in
base-16 and base-8, respectively. Hexadecimal literals are prefixed
with '0x,' and octal literals are prefixed with '0.'
int hexValue = 0x1A; // Hexadecimal literal
int octalValue = 034; // Octal literal
Understanding how to utilize these numeric systems provides
flexibility in representing values in different bases.
The "Constants and Literals" section within the "Variables in C"
module serves as a comprehensive guide, illustrating the various
ways constants and literals are employed in C programming. A solid
grasp of these concepts is pivotal for creating code that is not only
robust but also easy to understand and maintain.

Dynamic Memory Allocation


The "Variables in C" module within the book "C Programming:
Building Blocks of Modern Code" delves into the intricacies of
dynamic memory allocation, a crucial aspect of C programming that
allows for flexible memory management during runtime. Unlike
static memory allocation, dynamic memory allocation enables
programs to allocate and deallocate memory as needed, facilitating
efficient memory usage and enhancing program flexibility.
Using malloc() for Memory Allocation
The primary function for dynamic memory allocation in C is
malloc(). It stands for "memory allocation" and is used to request a
specified number of bytes from the heap, returning a pointer to the
beginning of the allocated memory.
int *dynamicArray = (int *)malloc(5 * sizeof(int));

In this example, dynamicArray is a pointer to an integer that is


dynamically allocated to store an array of five integers. The
sizeof(int) ensures that the correct amount of memory is allocated
based on the system's integer size.
calloc() for Allocating and Initializing
The calloc() function is another dynamic memory allocation function
that not only allocates memory but also initializes all the allocated
memory to zero.
int *zeroedArray = (int *)calloc(8, sizeof(int));
Here, zeroedArray is a pointer to an array of eight integers, and all
the elements are initialized to zero. This is particularly useful when a
program requires a block of memory with specific initial values.
realloc() for Resizing Memory
Dynamic memory can be resized during runtime using the realloc()
function. This function takes a pointer to a previously allocated
memory block and adjusts its size.
int *resizedArray = (int *)realloc(dynamicArray, 10 * sizeof(int));

In this example, dynamicArray is resized to accommodate ten


integers. It's important to note that realloc() may return a different
pointer if it needs to move the memory block, so it's essential to
assign the result back to the original pointer.
Deallocating Memory with free()
To prevent memory leaks, it is crucial to deallocate dynamically
allocated memory once it is no longer needed. The free() function is
used for this purpose.
free(dynamicArray);
free(zeroedArray);
free(resizedArray);

This snippet demonstrates the proper use of free() to release the


memory allocated for dynamicArray, zeroedArray, and resizedArray.
Failing to free dynamically allocated memory can lead to memory
leaks, impacting the program's performance.
Error Handling and NULL Checks
Dynamic memory allocation is susceptible to failure, especially when
the system runs out of memory. It is good practice to check the return
value of allocation functions for NULL to handle such situations
gracefully.
int *newArray = (int *)malloc(size * sizeof(int));
if (newArray == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}

Here, the program checks if the allocation was successful, and if not,
it prints an error message and exits the program.
The "Dynamic Memory Allocation" section provides a
comprehensive guide within the "Variables in C" module, offering
insights into the functions and practices related to allocating and
managing memory dynamically in C programs. Understanding these
concepts is fundamental for writing robust and memory-efficient C
code.
Module 3:
Functions in C

Crafting Modular and Reusable Code


The module "Functions in C" stands as a pivotal chapter in the narrative of
"C Programming: Building Blocks of Modern Code." In the vast landscape
of C programming, functions emerge as indispensable tools for structuring
code, promoting reusability, and fostering modular design. This exploration
unveils the intricacies of functions in C, elucidating their role as dynamic
building blocks in the construction of robust and scalable programs.
The Essence of Functions: Decomposing Complexity
At its core, the module immerses readers in the essence of functions — self-
contained units of code designed to perform specific tasks. This concept
aligns seamlessly with C's commitment to procedural programming,
allowing developers to decompose complex problems into manageable and
comprehensible parts. Readers will delve into the syntax of function
definition, understanding how to declare, implement, and invoke functions
to streamline their code.
Function Parameters: Bridging Data into the Function Realm
A significant portion of the module unravels the concept of function
parameters. Parameters act as bridges, enabling the passage of data into
functions. The discussion spans the diverse types of parameters, including
those that allow the function to receive input and others that facilitate the
return of values. Readers gain insight into the nuances of parameter passing,
appreciating how it contributes to the flexibility and adaptability of C
functions.
Return Values: Harvesting Results from Function Orchestrations
The narrative extends to the crucial role of return values. Functions in C are
not merely isolated operations; they are orchestrators that produce
outcomes. The module elucidates the mechanisms of returning values from
functions, emphasizing the importance of conveying results to the broader
context of a program. This dynamic aspect of functions empowers
developers to create efficient and purposeful code.
Scope and Lifetime of Variables: Navigating the Function Landscape
A deep dive into functions necessitates an understanding of the scope and
lifetime of variables within their domain. This module unfurls the temporal
landscape of variables, illuminating how local and global variables operate
within the context of functions. Such comprehension is pivotal for crafting
modular and maintainable code, ensuring that functions encapsulate their
logic while interacting seamlessly with the broader program.
As readers navigate the realms of "Functions in C," they not only grasp the
syntax and mechanics of function implementation but also cultivate a
mindset geared towards modular design and code reusability. This module
serves as a catalyst for embracing the power of functions, setting the stage
for the development of intricate and scalable C programs.

Function Declaration and Definition


The "Functions in C" module within the book "C Programming:
Building Blocks of Modern Code" delves into the importance of
function declaration and definition, a fundamental concept that
enhances code modularity and reusability. In C, functions play a
pivotal role in organizing code into manageable units, and
understanding how to declare and define them is essential for creating
structured and maintainable programs.
Function Declaration
A function declaration informs the compiler about the function's
name, return type, and the types of its parameters. It serves as a
prototype that allows the compiler to understand how to call the
function and what values to expect.
// Function declaration
int add(int a, int b);
Here, the function add is declared with a return type of int and two
integer parameters. The declaration enables other parts of the
program to call the function without having the entire function
definition available.
Function Definition
The function definition provides the actual implementation of the
function, detailing the logic executed when the function is called.
// Function definition
int add(int a, int b) {
return a + b;
}

In this example, the add function adds two integers and returns the
result. The function definition includes the return type, function
name, parameter types, and the actual code within curly braces.
Function Prototypes
Function prototypes are a form of forward declaration, allowing the
compiler to recognize functions before their definitions appear in the
code. They are particularly useful when functions are defined after
they are called in the program.
// Function prototype
int multiply(int x, int y);

int main() {
int result = multiply(3, 4);
return 0;
}

// Function definition
int multiply(int x, int y) {
return x * y;
}

Here, the prototype for the multiply function is declared at the


beginning, enabling its use in the main function before its definition.
Function Parameters and Return Values
Functions can take parameters, which are values passed to them, and
return values, which are the results they produce. Understanding how
to define and utilize these aspects is vital for creating versatile and
effective functions.
// Function with parameters and return value
float calculateAverage(int array[], int size) {
float sum = 0;
for (int i = 0; i < size; ++i) {
sum += array[i];
}
return sum / size;
}

In this example, the calculateAverage function takes an array and its


size as parameters, calculates the sum of its elements, and returns the
average. Functions with parameters and return values enhance code
reusability and flexibility.
Recursive Functions
C supports recursive functions, allowing a function to call itself.
Recursive functions are often employed for solving problems that can
be broken down into smaller, similar sub-problems.
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

In this instance, the factorial function calculates the factorial of a


number using recursion. Recursive functions provide an elegant way
to express complex algorithms.
Variable Scope and Lifetime
Understanding the scope and lifetime of variables within functions is
crucial. Variables declared within a function are local to that function
and have limited visibility outside of it.
int globalVariable = 10; // Global variable
void modifyGlobalVariable() {
globalVariable = 20; // Modifying the global variable
}

int main() {
modifyGlobalVariable();
// globalVariable is now 20
return 0;
}

In this example, the modifyGlobalVariable function can access and


modify the global variable, but local variables within functions are
confined to their respective scopes.
The "Function Declaration and Definition" section of the "Functions
in C" module provides a comprehensive exploration of the
foundational concepts related to creating and utilizing functions in C
programming. Mastery of these concepts is essential for writing
modular, readable, and maintainable code in the C language.

Parameters and Return Values


The "Functions in C" module within the book "C Programming:
Building Blocks of Modern Code" extensively covers the crucial
aspects of parameters and return values, essential components for
creating versatile and reusable functions in C. Understanding how to
define, pass, and utilize parameters, as well as how to manage return
values, is fundamental for effective function implementation.
Function Parameters
Function parameters enable the passing of values to a function,
allowing it to operate on specific data. Parameters are specified
within the function declaration and definition, defining the type and
name of each parameter.
// Function declaration with parameters
int add(int a, int b);

// Function definition with parameters


int add(int a, int b) {
return a + b;
}
In this example, the add function takes two parameters, a and b, and
returns their sum. Parameters enhance the flexibility and reusability
of functions, as they allow the function to work with different input
values.
Passing Parameters by Value
By default, C uses a "pass-by-value" mechanism when passing
parameters to functions. This means that the actual values of the
arguments are copied into the function parameters, preserving the
original values outside the function.
void square(int x) {
x = x * x; // Changes only the local copy of x
}

int main() {
int number = 5;
square(number);
// 'number' remains 5 after the function call
return 0;
}

In this case, the square function attempts to modify the parameter x,


but the original value of number in the main function remains
unchanged.
Passing Parameters by Reference
While C primarily uses pass-by-value, it is possible to achieve pass-
by-reference-like behavior by passing the address of a variable (a
pointer) to a function. This allows the function to directly manipulate
the value stored at that memory address.
void squareByReference(int *x) {
*x = (*x) * (*x); // Modifies the value at the memory address pointed to by x
}

int main() {
int number = 5;
squareByReference(&number);
// 'number' is now 25 after the function call
return 0;
}
Here, the squareByReference function takes a pointer to an integer
and modifies the value at that memory address, affecting the original
variable number in the main function.
Return Values
Functions in C can return values to the calling code, allowing them to
communicate results or perform computations. The return type is
specified in the function declaration and definition.
// Function declaration with return type
float calculateAverage(int array[], int size);

// Function definition with return type


float calculateAverage(int array[], int size) {
float sum = 0;
for (int i = 0; i < size; ++i) {
sum += array[i];
}
return sum / size;
}

In this example, the calculateAverage function returns the average of


an array of numbers. The return type (float in this case) indicates the
type of value the function will provide.
Multiple Return Values
C functions can only directly return a single value. However, multiple
values can be effectively returned by using pointers or structures.
// Function with multiple return values using pointers
void getMinMax(int array[], int size, int *min, int *max) {
// Logic to find min and max
// Assign results to *min and *max
}

int main() {
int numbers[] = {3, 7, 1, 9, 4};
int minValue, maxValue;

getMinMax(numbers, 5, &minValue, &maxValue);

// minValue and maxValue now contain the minimum and maximum values,
respectively
return 0;
}
Here, the getMinMax function takes an array, its size, and two
pointers (min and max) to store the minimum and maximum values.
The function modifies the values indirectly through the pointers.
Understanding parameters and return values is fundamental for
harnessing the full potential of functions in C. The ability to pass data
into functions and receive results back enhances the modularity and
clarity of code, facilitating the creation of robust and reusable
software.

Function Prototypes
The module on "Functions in C" within the book "C Programming:
Building Blocks of Modern Code" introduces the concept of function
prototypes, a vital aspect of C programming that enhances code
organization and allows for better modularity. Function prototypes
serve as declarations that inform the compiler about the existence and
signature of a function before its actual implementation, enabling
smooth integration and avoiding potential issues related to function
calls.
Introduction to Function Prototypes
In C, a function prototype provides the compiler with information
about a function's name, return type, and parameters. This enables the
compiler to validate function calls and ensure their correctness before
the actual function definitions are encountered.
// Function prototype
int calculateSum(int a, int b);

Here, the function prototype for calculateSum declares that the


function takes two integers as parameters (a and b) and returns an
integer. This declaration allows the compiler to understand how the
function should be used even before its definition.
Benefits of Function Prototypes
The primary advantage of function prototypes is evident when
functions are defined after they are called in the program. Without
prototypes, the compiler might encounter function calls without prior
knowledge of the function signatures, potentially leading to errors or
unexpected behavior.
// Function prototype
int calculateProduct(int x, int y);

int main() {
int result = calculateProduct(3, 4);
return 0;
}

// Function definition
int calculateProduct(int x, int y) {
return x * y;
}
In this example, the prototype informs the compiler about the
calculateProduct function, allowing the main function to call it before
its actual definition.
Avoiding Implicit Int Function Declarations
In older C standards, when a function was called without a prototype,
the compiler implicitly assumed it returned an int. This could lead to
subtle bugs if the function returned a different type.
// No prototype
double calculateAverage(int array[], int size);

int main() {
double result = calculateAverage(numbers, 5);
return 0;
}

// Function definition
double calculateAverage(int array[], int size) {
// Logic to calculate average
return sum / size;
}

Here, the absence of a prototype in the main function could lead to a


mismatch if the compiler assumes calculateAverage returns an int.
Utilizing function prototypes ensures proper type checking and
eliminates this ambiguity.
Default Arguments in Prototypes
C does not support default function arguments like some other
languages. However, function prototypes allow for a certain degree of
flexibility by declaring functions with parameters that are not strictly
enforced during the definition.
// Function prototype with additional parameters
int multiply(int a, int b, int c);

In this case, the prototype introduces an additional parameter c that


may not be present in the actual function definition. While this is not
a true default argument, it provides a level of flexibility in function
declarations.
Header Files and Function Prototypes
Function prototypes are commonly placed in header files (.h) in
larger C projects. This practice centralizes declarations, making them
accessible to multiple source files.
// Example header file (calculate.h)
#ifndef CALCULATE_H
#define CALCULATE_H

int calculateSum(int a, int b);


double calculateAverage(int array[], int size);

#endif

By including this header file in source files that require these


functions, the compiler gains knowledge of the function prototypes,
promoting modular code design and ease of maintenance.
Function prototypes are an integral part of C programming, providing
a mechanism to declare functions before their actual implementation.
This practice enhances code organization, improves readability, and
prevents potential errors arising from implicit assumptions about
function signatures. Understanding the significance of function
prototypes is essential for writing clear, error-free, and maintainable
C code.

Recursion in C
The module on "Functions in C" within the book "C Programming:
Building Blocks of Modern Code" explores the powerful concept of
recursion. Recursion is a programming technique where a function
calls itself, allowing for the repetition of a particular set of
operations. This section delves into the principles of recursion in C,
its applications, and considerations for effective implementation.
Understanding Recursion
Recursion simplifies complex problems by breaking them down into
smaller, more manageable sub-problems. The base case, a condition
where the function does not call itself, is crucial for preventing an
infinite loop. Each recursive call tackles a smaller part of the
problem, gradually converging towards the base case.
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}

In this example, the factorial function calculates the factorial of a


number using recursion. The base case ensures the recursion stops
when n reaches 0 or 1.
Recursive vs. Iterative Approaches
Recursion is often an elegant and intuitive solution, but it may not
always be the most efficient. Some problems are better suited for
iterative approaches using loops. The choice between recursion and
iteration depends on the nature of the problem and performance
considerations.
// Iterative approach to calculate factorial
int factorialIterative(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
This iterative version of calculating factorial achieves the same result
as the recursive approach. While recursion can lead to more readable
code in certain scenarios, iterative solutions may offer better
performance.
Memory Usage in Recursion
Recursive functions utilize the call stack to manage multiple function
calls. Each recursive call adds a new frame to the stack, consuming
memory. Excessive recursion without proper termination conditions
can lead to a stack overflow, causing program termination.
// Recursive function to calculate Fibonacci sequence
int fibonacci(int n) {
if (n <= 1) {
return n; // Base case
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}
}

In the fibonacci function, each recursive call contributes to the call


stack. While recursion is elegant for expressing Fibonacci
calculations, it becomes inefficient for large values of n due to
redundant computations.
Tail Recursion and Optimization
Tail recursion is a special case where the recursive call is the last
operation in the function. Some compilers can optimize tail-recursive
functions to use constant stack space, avoiding stack overflow issues.
// Tail-recursive function
int factorialTailRecursive(int n, int accumulator) {
if (n == 0) {
return accumulator; // Base case
} else {
return factorialTailRecursive(n - 1, n * accumulator); // Tail-recursive call
}
}

The factorialTailRecursive function is tail-recursive, allowing for


potential optimization by certain compilers.
Proper Handling of Recursive Cases
When designing recursive functions, it's crucial to ensure that the
recursive calls lead towards the base case. Failing to do so may result
in infinite recursion, consuming excessive stack space and leading to
program termination.
// Incorrect recursive function without reaching base case
void infiniteRecursion(int n) {
printf("%d\n", n);
infiniteRecursion(n + 1); // Recursive call without approaching a base case
}

This example demonstrates an incorrect recursive function that lacks


a proper termination condition, leading to an infinite loop.
Recursion is a powerful and versatile technique in C programming
that simplifies complex problems by breaking them down into more
manageable sub-problems. Properly designed recursive functions
enhance code readability and maintainability, but careful
consideration must be given to base cases, termination conditions,
and potential performance implications. Understanding the principles
of recursion empowers programmers to approach problem-solving
with a fresh and elegant perspective.
Module 4:
Conditions and Decision Making

Navigating Program Flow


The module "Conditions and Decision Making" within the book "C
Programming: Building Blocks of Modern Code" is a pivotal exploration
into the realm of program control. In the intricate tapestry of C
programming, the ability to make decisions dynamically based on certain
conditions is a cornerstone skill. This module unveils the syntax, concepts,
and nuances of decision-making structures in C, empowering programmers
to sculpt code that adapts intelligently to diverse scenarios.
Foundations of Decision Making: The 'if' and 'else' Constructs
At its core, the module immerses readers in the foundational constructs of
decision making — the 'if' and 'else' statements. These building blocks
enable programmers to introduce conditional logic into their code, allowing
the execution of different branches based on the evaluation of specified
conditions. Readers will gain a comprehensive understanding of the syntax
and applications of these constructs, laying the groundwork for more
intricate decision-making scenarios.
Extended Decision-Making: The 'switch' Statement
The exploration extends to the versatile 'switch' statement, providing an
alternative approach to decision making. Unlike the 'if' and 'else' constructs,
the 'switch' statement allows for multi-branch decision making based on the
value of an expression. This section of the module delves into the syntax
and applications of the 'switch' statement, offering insights into when to
leverage its capabilities for cleaner and more concise code.
Logical Operators: Crafting Complex Conditions
A significant portion of the module delves into the world of logical
operators. These operators — '&&' (logical AND), '||' (logical OR), and '!'
(logical NOT) — serve as tools for crafting intricate conditions that respond
to multiple criteria. Readers will grasp the art of combining conditions,
creating decision-making structures that reflect the complexity of real-
world scenarios.
Nested Decision Making: Crafting Hierarchical Logic
The narrative expands to the concept of nested decision making, where
conditions are layered within one another. This advanced technique enables
programmers to create hierarchical logic, where the fulfillment of one
condition triggers the evaluation of another. Readers will master the art of
crafting nested 'if' statements, unlocking the potential to address intricate
decision-making scenarios with precision and clarity.
As readers progress through "Conditions and Decision Making," they not
only acquire the technical proficiency to implement decision-making
structures but also cultivate a strategic approach to crafting code that
responds intelligently to varying conditions. This module serves as a
gateway to the dynamic world of program control in C, paving the way for
the development of resilient and adaptive programs.
if, else if, else Statements
The "Conditions and Decision Making" module within the book "C
Programming: Building Blocks of Modern Code" introduces the
fundamental concept of decision-making in C through the if, else if,
and else statements. These control structures allow programmers to
execute specific blocks of code based on the evaluation of conditions,
enabling the creation of flexible and responsive programs.
The if Statement
The if statement is the cornerstone of decision-making in C. It allows
the execution of a block of code only if a specified condition is true.
int num = 10;

if (num > 0) {
printf("The number is positive.\n");
}
In this example, the printf statement will only be executed if the
condition num > 0 is true. If the condition is false, the code block will
be skipped.
The else if Statement
The else if statement provides a way to test multiple conditions
sequentially. If the preceding if condition is false, the else if
statement allows the evaluation of an additional condition.
int num = 0;

if (num > 0) {
printf("The number is positive.\n");
} else if (num < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

In this scenario, the program checks multiple conditions using else if.
If none of the conditions is true, the else block is executed, providing
a default case.
The else Statement
The else statement provides a fallback option when none of the
preceding conditions are true. It allows the execution of a default
block of code.
int num = -5;

if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}

Here, if the condition num > 0 is false, the else block will be
executed, printing that the number is non-positive.
Nested if Statements
Conditional statements can be nested, allowing for more complex
decision-making scenarios. Nested if statements are useful when
multiple conditions need to be evaluated based on the outcome of
outer conditions.
int num = 10;

if (num > 0) {
if (num % 2 == 0) {
printf("The number is positive and even.\n");
} else {
printf("The number is positive and odd.\n");
}
} else {
printf("The number is non-positive.\n");
}

In this example, the inner if statement checks whether the positive


number is even or odd, depending on the outcome of the outer if
condition.
Common Mistakes and Best Practices
When working with if, else if, and else statements, it's crucial to
avoid common mistakes, such as missing braces for code blocks or
failing to account for all possible scenarios. Additionally, maintaining
code readability by properly indenting nested statements enhances
code comprehension.
int num = 42;

// Incorrect indentation
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}

This snippet highlights the importance of consistent indentation for


clear code presentation.
Ternary Operator as a Compact Alternative
The ternary operator (? :) provides a concise alternative for simple
conditional expressions, especially when assigning values based on a
condition.
int num = 7;
printf("The number is %s.\n", (num % 2 == 0) ? "even" : "odd");

In this example, the ternary operator is used to determine whether the


number is even or odd within a single line, showcasing a more
compact syntax.
The "if, else if, else Statements" section within the "Conditions and
Decision Making" module serves as a foundation for understanding
how C programs make decisions based on different conditions.
Proper usage of these statements enables programmers to create
dynamic and responsive code that can adapt to various scenarios.

Switch-Case Statements
The "Conditions and Decision Making" module in the book "C
Programming: Building Blocks of Modern Code" introduces the
switch-case statements, a powerful control structure designed to
simplify decision-making processes involving multiple possible
conditions. The switch-case construct provides an organized and
efficient way to handle various cases, offering an alternative to
cascading if-else if statements.
Introduction to Switch-Case
The switch-case structure is particularly useful when a program needs
to compare a variable or expression against multiple constant values
and execute different blocks of code based on the match. It improves
code readability and maintainability by avoiding the need for
extensive nested if-else constructs.
int dayOfWeek = 3;

switch (dayOfWeek) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
// Additional cases for other days
default:
Random documents with unrelated
content Scribd suggests to you:
For the Southern Literary Messenger.

LETTERS ON THE UNITED STATES OF AMERICA,

By a young Scotchman, now no more.

Boston, 1832.

DEAR HENRY,—Mr. Paulding and Miss Sedgewick, are, in my opinion,


inferior in genius to the American writers I mentioned in my last.
They may be classed as the secondary novelists of this country,
though in general literature, Paulding is equal if not superior to
Cooper. His tales are usually short and want interest; but his
characters are well sketched, his incidents natural, and his opinions
and observations characterized by good sense. There is, however, an
affectation of humor in what he writes, that does not please me. It
seems to consist more in the employment of quaint terms and odd
phrases, than in the incident or character itself, and would appear to
be the result of an early and frequent perusal of the works of Swift
and Rabelais. His productions are neat and sensible, but not very
imaginative or striking. The interest or curiosity of the reader is
never powerfully excited, but he never fails to please by the manner
in which he conducts his plots; the easy and perspicuous style he
employs, the clear and happy illustration of the vice or folly he holds
up to indignation or scorn, and the successful though sometimes
exaggerated developement of the character he wishes to portray. In
both Paulding and Cooper there is an overwhelming American
feeling, which bursts forth on all occasions, and which, to a
foreigner, seems to partake of the nature of deep rooted prejudice.
It results, however, I have no doubt, from an ardent love of country,
increased perhaps by the silly contumelies and sarcasms of the
reviewers and travellers of our country. Mr. Paulding has not
displayed any great depth or expansion of mind in anything he has
yet written, though he has tried his wing in both prose and verse.
His forte is satire, which, like that of Horace, is more playful than
mordant and bitter. The productions of Miss Sedgewick which I have
seen, are remarkable for good sense, but without much vigor of
imagination. She succeeds best in quiet life. The delineation of the
workings of passion, and of stormy and powerful emotions, are
beyond the reach of her powers; but what she attempts she always
does well. Her plots are generally without complication, and display
no great fertility of invention; the incidents are not very striking and
the characters are sometimes tame, and occasionally extravagant.
They are not like the delineations of Miss Edgeworth, or Miss
Mitford. You cannot form an idea of the nationality of the individual
she sketches, and would as soon take him for a native of any other
country as of her own. There is a manifest defect in this particular, in
all the novelists I have mentioned. With the exception of the Indians
who are occasionally introduced, there is scarcely any difference
between their Americans, and the inhabitants of other lands. Cooper
has indeed presented a finer gallery of American characters than any
other writer, especially in his sketches of the early settlers or
pioneers; but his characters, except in a few instances, are not
usually distinguished by striking national peculiarities. This may
possibly originate from the singular fact that in this country where
men are free to rove where inclination leads, and to be under no
other restraint than that which religion, law, or decency imposes,
there is less peculiarity of character or individuality, than in any other
portion of the globe with which I am acquainted. They have not yet
attempted to give as in England, sketches of American society as it
now exists, or may have existed since the organization of their
government. Whether such pictures would indeed be interesting I
am not prepared to say; but from the society in which I have
mingled, I do not think it has variety enough, or differs sufficiently
from that of other civilized nations to render such pictures striking or
amusing. Genius, however, can accomplish every thing, and might
give to what appears to be vapid and ennuyant, some novelty and
interest.

There are some other novelists in the United States, whose


productions, as they have sunk, or are rapidly sinking into oblivion, it
is scarcely necessary to name. One of these is a man of talent, who,
you will recollect, was an occasional contributor to the literary
periodicals of our country, while a resident there. I mean J. Neale.
His romances, from their wildness and extravagance, have been but
little read, and are now nearly forgotten. He still, however, employs
his pen, I understand, in doing what he can to edify and amuse his
countrymen. Novel reading has been legitimatized by Sir Walter
Scott, and though his productions furnish an admirable standard,
nothing in the nature of romance now goes amiss, and the demand
for works of fancy seems to increase in proportion to the number
issued from the press, and the food that is furnished. Although the
Americans are great novel readers, there is not much of romance in
their character. There is too much matter-of-fact about them; they
are too calculating and money-making to serve the purposes of the
novelist. They form but indifferent heroes and heroines of romance,
and hence Cooper is obliged to resort to the sea to rake up pirates
and smugglers, or to go back to the revolution or the early
settlement of his country to find characters and incidents calculated
to give verisimilitude and interest to his tales.

In dramatic literature, but little has yet been done in the United
States. Few appear to have devoted much of their attention to
dramatic composition. I have seen but ten or twelve American plays
in the course of my researches; and these, though they possessed a
good deal of merit, have been suffered to sink into neglect, and are
rarely performed. A much larger number, however, would appear to
have been written and prepared for the stage. According to a
catalogue I have lately seen, no less than 270 dramatic pieces have
either been prepared for the theatre of this country, or written by
Americans. Of these many were of course got up for temporary
purposes, and when these purposes were answered were no longer
remembered; but you will be surprised to learn that of this number,
commencing in 1775, there are no less than thirty-three tragedies,
the best of which are those which have been recently brought out,
Metamora, Ouralasqui, a prize tragedy by a lady of Kentucky, and a
combination of tragedies, by Paine, called Brutus, which has been on
the stage for several years. The rest are scarcely remembered. The
writer who seems to have devoted the largest portion of his time to
dramatic literature in this country and who may be called the father
of the American drama, is Mr. Dunlap, who has figured for many
years in the various characters of dramatist, manager, and painter.
His dramatic pieces amount to about 50, and he has already outlived
their fame. Some of his translations from the German are still
exhibited; but his original compositions are now never performed,
and are almost forgotten. Mr. J. N. Barker of Philadelphia, stands
next in point of fecundity, having given birth to ten dramatic
bantlings in the course of his life, some of which are very creditable
to their parent, but none are, I believe, stock plays. The prejudice
against native writers was at one time so strong that the managers
deemed it prudent to announce Mr. Barker's Marmion, Sir Walter's
poem dramatized, as the production of Thomas Morton the author of
Columbus. Mr. Dunlap was also I understand obliged to resort to the
same expedient in relation to two or three of his plays; but as moon
as it was known, their popularity, which had at first been
considerable, immediately ceased, and they were laid upon the shelf.
Such are some of the difficulties with which the American writer has
to struggle; but these I am happy to learn are now giving way, and a
more liberal spirit is beginning to prevail. It is to be hoped that the
dramatic muse of America will soon be enabled to triumph over all
the impediments which she has had to encounter, and repose in the
same bower and be crowned with the same chaplet as her more
fortunate sister of romance. Among the American plays which
accident brought under my notice, was a comedy in five acts,
entitled the "Child of Feeling," published in 1809, and written by a
citizen of Washington. It seems to have been a juvenile production,
written without much knowledge of the world, but with a due regard
to the unities. The dialogue wants sprightliness and the plot interest,
and I merely mention it now because its contains among its dramatis
personæ a character which is to me entirely original, and which if he
really existed, the author must I think have caricatured in his copy.
He is called Etymology, and does not belie his name, for he is
constantly occupied in tracing every word that is spoken by himself
or others to its root, and makes as may easily be supposed, some
comic and ludicrous blunders. Till very recently, the author of even a
successful play received scarcely any compensation for his labor, and
the fame he acquired was but of short duration. Now however, it is
otherwise, and both reputation and emolument attend the successful
dramatist. The comedies, by American writers that I have seen, are
not remarkable for their wit or humor, and therefore do not long
retain their hold upon the stage. Dramatic exhibitions are not
however held by the Americans in very high estimation, and this
may be one of the causes of the low state of dramatic literature
here. But the principal causes would appear to be the want of
leisure, the devotion of the people to higher and more lucrative
avocations, and the facility with which dramatic productions of
established merit and popularity can be obtained from England.
These causes operate in like manner I conceive, to prevent the
attainment of that high poetical excellence which has yet to be
reached by the worshippers of the muse in this country. The
following remarks on this subject by an American writer are so
pertinent, that I will transcribe them for your information. "We regret
to say," says he, speaking of American poetry, "that much less has
been done than might reasonably have been expected, even during
our short political existence. We have indeed as yet scarcely done
anything at which an American can look with conscious pride, as a
trophy of native poetic genius. The ponderous and vapid Epic of
Barlow, and the still more leaden and senseless heroics of Emmons,
are far from giving reputation to the poetry of our country; and the
fugitive and occasional pieces of Percival, Bryant, Halleck, &c. are
not exactly such as we should select as a proof that we have done
much in poetry. We have been in existence as a nation for upwards
of half a century, and yet we have produced nothing that is certain
to reach posterity, or that can be classed higher than the minor
productions of Moore, Campbell, or Byron, of the present day. There
is an apparent want of originality, and too great an appearance of
imitation in the poetical efforts of our native bards to carry them far
down the stream of time, though it must be conceded that they
have discovered in these efforts no ordinary portion of genius. There
would seem to be something either in the nature of our political
institutions, or in the general character of our pursuits, which is
inimical to the developement of high poetical power. We are not a
very imaginative people; we prefer the reality to the ideal; we
pursue the substance rather than the shadow. Our ambition is early
fired by political distinction, or our exertions are directed to the
attainment of competency or wealth. The public mind has been led
into a train of thinking somewhat adverse to the indulgence of
poetical enthusiasm, and not calculated to render it susceptible of
deep and intense delight from the contemplation of poetical beauty.
It has been led to consider that the highest efforts of genius are
those which are displayed at the bar or in the senate, and to regard
the power of forensic and parliamentary eloquence as the loftiest
exhibition of intellectual excellence. To that which the mind is early
taught to respect and admire its greatest exertions will be directed,
and hence the number of those who resort to the profession of law,
the career of legislation, or the pursuits of commerce," &c.

It is unquestionably true, that no great original poetical work of


distinguished merit has yet made its appearance in the United
States, but it cannot at the same time be denied, that the individuals
this writer has named, with Bryant, Sigourney, Willis, and several
others, possess a fine poetical vein, the mens divinior of Horace.
Some of their effusions contain passages of great beauty and
splendor, and may be fairly classed with those of the first poets of
our country. Most of them however, have merely what Mad. De
Genlis calls the "art of making verses;" and either from the want of
encouragement, the stimulus of praise, or continued enthusiasm,
wing their flight briefly into the regions of poetic fancy, and seldom
afterwards attempt any more lofty or daring excursions. But I must
pause. I will endeavor in my next to bring my remarks on the
science and literature of the United States to a close.

FINE PASSAGE IN HOOKER.

Hooker in his Ecclesiastical Polity says, "The time will come when
three words, uttered with charity and meekness, shall receive a far
more blessed reward, than three thousand volumes written with
disdainful sharpness of wit."

For the Southern Literary Messenger.

TO ——.

The dial marks the sunny hour,


Every brilliant moment noting,
But it loses all its power
When a cloud is o'er it floating,
As if gloom should be forgot!

Thus on Time has Mem'ry dwelt,


Tracing every fleeting minute,
When thy radiant smiles were felt
Courting each, if they were in it,
Noting none if they were not!

For the Southern Literary Messenger.

PARAPHRASE

Of a figure in the first volume of Eugene Aram.

Tho' the Moon o'er yonder river


Seems a partial glance to throw,
Kissing waves that brightly quiver
Whilst the rest in darkness flow,
There's not a ripple of that stream
Unsilvered by some hallowed beam.

Thus in life the bliss that mellows


Ills, that else the soul would blight,
Seems to fall upon our fellows
Like that glance of partial light;
Yet each spirit sunk in sadness,
Feels in turn its ray of gladness!

For the Southern Literary Messenger.


TO MY SISTERS.

Tho' I have sworn in other ears,


And kissing, sealed the oath in tears,
Have owned a little world divine,
Between my Sarah's lips and mine,
And more than mortal blessed have felt,
While there in Heav'nly bliss we dwelt,
Yet I loved not.
But when I look, dear girls on ye,
E'en in the look my worlds I see;
No vow has passed—our years have proved
That we have ever truly loved—
And in your every prayer I hear,
My name so kindly whispered there,
Oh! then I love.
ROSICRUCIUS.

For the Southern Literary Messenger.

LINES.

Sleep on, thou dear maiden, I'll guard thee from harm,
No foe shall come nigh thee while strength's in this arm;
As thy sweet breath comes o'er me wild wishes may rise,
But honor still whispers—Remember the ties
Which bind her to one to whom she is dear
As his hopes of a heaven, she's all he has here.
Yes, far be it from me my friend to betray—
To gain thy affections, whilst he, far away,
But little suspects me, or dreams I would dare
To deceive his heart's treasure—so lovely, so fair:
Then sleep on, thou dear maiden, I'll guard thee from harm,
No foe shall come nigh thee while strength's in this arm.
J. M. C. D.

For the Southern Literary Messenger.

GRAYSON GRIFFITH.

There is in a pleasant part of the Old Dominion, a thrifty village


named Goodcheer. The inhabitants, from the first settlement of the
place, were kind, and bland, and social. Indeed many of them went
further. They jested, they fiddled, they danced, they sang songs,
they played at cards, they drank wine, they frolicked. Yet was there
among them a strong and steady current of public opinion against
acts of very low and gross meanness or depravity. They were not
liars, or thieves, or swindlers, or rakes.

In this village lived Gregory Griffith, the tanner, whose industry and
probity earned for him a respectability and an independence rivalled
by none except the old patriarch of the village, more generally
known by the name of the Major. Gregory had married the eldest
daughter of old farmer Ryefield, a woman well suited to make him
happy. Her disposition was easy, and her habits industrious and
economical. They were a bonny couple.

"The day moved swiftly o'er their heads,


Made up of innocence and love."
Fourteen months after their marriage, their first born son, a lovely
child, smiled in the face of his parents. Him they called Grayson. Nor
was he the only pledge of their love. They alternately rejoiced over a
daughter and a son, until their quiver was full, having four sons and
three lovely daughters. The death of their second child, who bore
her mother's name, had in the fourth year of their marriage, wrung
the bleeding hearts of these parents, and chastened their feelings to
sober thinking. Between their first born and their third child lay an
interval of nearly five years—a period which Mr. and Mrs. Griffith
always spoke of with deep emotion.

Grayson, in his childhood, had but feeble health—a circumstance


which secured to him very indulgent treatment. This indulgence rose
to excess after the death of the lovely Martha, his little sister. So
soon after the death of the daughter, as the gay villagers could with
propriety, they planned a general meeting at Mr. Griffith's. They
came, and after some time spent in sober enjoyment, a game of
whist was proposed. The proposal sensibly affected Mrs. Griffith. She
seemed to feel that it was too soon after her babe's death. The tears
started in her eyes, and she sought a place to weep. She went to
her toilet and bathed her face, and returned with an air of
constrained cheerfulness. Meanwhile Mr. Griffith had taken his seat
with a second company who were playing loo. Before Martha's
death, Grayson had been regularly carried to the nursery, as the sun
threw his lowest and latest beams on the summit of a hill in sight
from the portico. But after the death of his sister, he was
encouraged to spend the evening with his parents; and when
overcome by sleep, his cradle and his pillow were the bosom and the
lap of parental fondness. And when company was present, he was
often awake until a late hour. On this evening every one had
something to say to Master Grayson. All the ladies kissed him, and
more than one promised him a daughter for a little sweetheart.
When whist and loo became the amusement, Grayson was much
interested, especially when he saw his father dealing out. The very
beaminess of his eye seemed to throw a charm around the figures
on every card. At first he said nothing. At last he went to his mother
and said: "Mamma, won't you teach me to do like papa? O, I wish
sister Martha was not dead, that she might see the pretties papa has
got. Mamma, what are the papers with the hearts on?" The mention
of Martha's name overcame Mrs. Griffith. She led Grayson to her
bed-room, and wept and kissed him until, overcome by sleep, he
forgot his joys and his sorrows until the next day. The nurse having
lodged the sweet boy in the long crib at the side of his parent's bed,
Mrs. Griffith returned to her company. Either her appearance, or a
sense of propriety in her guests, operated a speedy dissolution of
the party. The company being gone, Mr. Griffith said he wished he
had not consented to play that evening—that Martha had been dead
but a year, and that he really thought that as his child had been
taken to heaven when not two years old, it was time for him to
begin to think of preparing to meet her. Mrs. Griffith wept at the
mention of Martha's name, repeated what Grayson had said,
observed that she had felt badly, but that they must not be
melancholy. She also said it was very kind in the neighbors to
endeavor to cheer them up. It was after midnight, in the month of
June, before these parents slept at all. At the very dawn of day
Grayson awoke his parents by kissing them often, and calling their
names aloud. So soon as he could get his father's attention, he said:
"O father, what were those pretty things you had in your hand last
night? Father, were they yours? May I have some? Can't I do as you
did with them? Father, what was you doing? Please, sir, give me
some to carry to school to-day." Mr. Griffith was not displeased that
Grayson did not wait for an answer to his interrogatories. To his
request for some to carry to school, he replied that Mr. Birch, the
teacher, was a religious man, and would not let the boys carry such
things to school. Grayson said: "And an't you religious too, papa?"
and kissed him. Mr. Griffith looked at his wife. They both smiled
confusedly.

After breakfast, some of the neighbors called and inquired for the
welfare of the family. Some of the ladies kissed Grayson, as did his
mother, and he went to school. At play-time he told the children
what he had seen, and one of the older boys explained the matter to
the rest of the company. He said the old people loved fun, and also
played for money—and yet they would not let their boys play. "Never
mind," continued he, "I can make fun, if you will all beg some pins
and bring here to-morrow. Now, fellows, don't forget—bring a good
many." The next morning every mother and sister were faithfully
plied for pins, and every boy's sleeve was brightened with them.
Before the teacher had arrived, the elder boy, before named, had
taught all his juniors two ways of playing pins—one on a hat, and
the other called "heads or points." In a few days one boy had
secured all the pins, and kept them safely in a little case made of a
section of reed. The spirit of gambling, however, did not expire with
the loss of the pins. Indeed the loss of the many was the gain of
one, and that one was the object of profound admiration.

In a day or two, one of the boys came to school with an ear of white
and another of red corn, and a piece of chalk in his pocket, and
whispered to all his play fellows that now they would have fine fun.
Every urchin was restless for play-time. Grayson Griffith was sure the
master's watch must have stopped or must be too slow, and said so.
At length the hour of recreation came, and as soon as all were fairly
out of the teacher's hearing, the aforesaid boy prepared to teach his
fellows the game of fox and geese. With his chalk he chequered a
board, and arranged his white and red grains in proper order—
calling the white grains of corn geese, and the red foxes. Soon he
initiated every boy, and Grayson Griffith among the number, in the
mysteries of the game.

Ere long it was proposed that every boy should ask for a cent at
home, and bring it to school. It was done. Grayson Griffith asked for
one cent, and his father gave him two, and his mother one. They
said he was old enough to have pocket money. He was now nearly
eight years old. In the playtime, all the boys agreed to throw heads
or tails, until they had won or lost the money that could be had. At
the end of the sport, Grayson had seven cents—but on his way
home, he dropped one in the grass, and by throwing heads or tails
with another boy, he lost three more—so that at night he had no
more and no less than in the morning.

That evening he asked if his father would go to the race next day.
His father replied he did not know. "Well," said Grayson, "I bet you
three cents and my barlow knife against ninepence, that Colonel
Riley's Firefly will beat General Hobson's young Medley." "You will
bet?" said Mr. Griffith. "Why, yes," said Grayson, "did not you bet at
loo, father?" Grayson and his father, as by mutual consent, waived
the conversation.

Next day Grayson told at school what had occurred. Mr. Griffith did
not go to the races; but in the evening some of the gentlemen came
to see him, and induced him to bet as high as twenty dollars on a
game at loo. Grayson seemed hardly to notice the occurrence, yet
he was in reality closely observing, and caught several of the
expressions of the gentlemen visiters. The next day, at a game of
fox and geese, he cried "Damme soul." And as he went to school he
kept saying, "Clubs are trumps—high, low, jack and the game." He
thought it sounded pretty.

In the meantime Mr. Griffith's family increased. He had now three


sons and a daughter; and Grayson would often promise to show his
little brother how to play fox and geese when he should grow a little
larger. Mrs. Griffith had also played at cards when any very special
company was present, or she was much urged.

Mr. Griffith about this time gave a hundred dollars towards building a
church in the village, and subscribed twenty dollars a year towards
the minister's salary; and many of the people had become very
serious, and even religious. The good minister, like his master Jesus
Christ, was very fond of children. All the children knew him in six
weeks after he went to live in Goodcheer, and they all loved him.
They would speak to him all the way across the street. One day Mr.
Goodnews (for that was the minister's name) called at Mr. Griffith's,
and asked Grayson if he knew how many commandments there
were. His answer was, "I bet you I do." "But," said Mr. Goodnews, "I
never bet, my dear little boy. Did not you know it was wrong to
bet?" "No," said Grayson, "it is'nt—Father and mother bet." Mrs.
Griffith's face colored, and she stammered out, "My son, you ought
not to tell stories, even in fun. You will make dear Mr. Goodnews
think very badly of your parents." "Any how, mother, it is true," said
the boy.

When Grayson was eleven years old, he was allowed to go to the


races. Here his fondness for sport and gaming was much increased.
He also saw many things that he did not understand, and some that
made him shudder. His parents had given him at different times
money, which he had saved, and adding to which, what he received
that morning, the sum total amounted to one dollar and a quarter.
The race that day was chiefly between two noted animals, Major
Clark's Rabbit, and Colonel Nelson's Yellow Gray. Betting ran high. At
first Grayson bet twenty-five cents in favor of Rabbit; then he bet
fifty cents against twenty-five on the Yellow Gray; then he bet his
remaining fifty cents against another fifty cents in favor of Yellow
Gray. In the meantime he bought some beer and some cakes, and
paid away twenty-five cents of his money. When he first
remembered that he might lose, he thought he would not be able to
meet all his engagements; but on reflection he discovered, that let
who would win, he could not lose all. The race was run. Rabbit was
beaten, and Grayson got his seventy-five cents, and paid what he
had lost, and had now left one dollar and a half. At first he thought
he would go home, and started—but a boy stepped forward and
said, he could show him some tricks—that he had a rattle-come-
snap, &c. Grayson went with him into the bushes, and there Grayson
lost one dollar at some sort of game, became vexed, and went
home. At night he would have determined never to bet any more,
had it not been that some gentlemen came to his father's, and
talked earnestly about their gains. Then the thought entered his
mind that it was entirely owing to good luck that some succeeded,
and that he would have better luck another day.
A few days after the races, Mr. Griffith was called to see his mother
die. She had been a very worldly-minded, proud woman—but her
last sickness had humbled her. With her last breath she spoke of
herself as a great sinner, and of her salvation as doubtful, and most
solemnly warned all her children not to follow her example. The
minister at Goodcheer went over to preach the funeral sermon, and
returning in company with Mr. Griffith, he thought he perceived
some seriousness in his manner, and introduced a very friendly and
solemn conversation on the importance of preparing for death. From
that time Mr. Griffith began to change, and in twelve months he and
his wife both joined Mr. Goodnews's church. They also presented
their five children to the Lord. This was a great change, and was
much spoken of by the villagers. It is thought the father and mother
were both truly converted. The day the children were baptized,
Grayson did not behave well in church, yet he dared not to do
anything very wrong. The next day, when one of the boys laughed at
him for being baptized, he at first thought he would say nothing, and
had he done so, all would have been well. But the laugh tormented
him. So in going home from school he made fun of it, and said the
old people had got mighty religious. When he got home he felt
dreadfully at seeing Mr. Goodnews at his father's; but he soon left
the house, and took the old cat in his arms, and called the dogs, and
went to chase cats in the old field.

His parents with difficulty prevailed on him to attend Sabbath school.


He said five days and a half in a week were enough to go to school.
He also disliked to come to prayers. He was frequently out until a
late hour at night, and once was found with some very bad boys in
an old house on a Sabbath night, doing what he called "projecting."
His parents had all along opposed the cold water men, and had
allowed Grayson to have some sweetened dram in the morning out
of their cups. And even after Mr. and Mrs. Griffith joined the church,
it did not seem easy to conquer in a day all their prejudices against
the temperance society. These things led Master Grayson to drink
julaps, and punch, and even grog. But he did not drink much. He
had also learned to use profane language to an extent that was very
distressing to some pious people who had heard him; but his
parents supposed he never swore.

When Grayson was sixteen years old, he read Hoyle on Games; and
though he understood very little of what he read, he conceived that
gaming must be a very profound science. Especially was this
impression deepened by hearing a member of congress say, that
Hoyle was as profound as Sir Isaac Newton. He read Hoyle again,
and even on the Sabbath. His parents began to suffer much
uneasiness about him; they sometimes wept over his case; they took
great pains to make religion appear amiable—but he was eager in
his pursuit of vanity.

When Grayson was eighteen or nineteen years old, he became


acquainted with Archibald Anderson, a most unworthy young man,
of low breeding and much cunning. Archie persuaded Grayson to go
a pleasuring the next Sunday—told him he had found a bee-tree,
and that they would get some girls and go and take the bee-tree
next Sunday. They went, and although Grayson tried to think it fine
fun, it was a very gloomy day. A thousand times did he wish himself
in church. At night he came in late, and went immediately to bed.
Next day his father inquired where he had been. But Grayson let him
understand that young people must not be watched too closely. In a
day or two Mrs. Griffith became alarmed at finding in Grayson's
apparel evident preparations to elope; but gentle and kind treatment
soon seemed to regain his confidence.

Mr. Griffith had, in the course of business, previously borrowed a


thousand dollars from one of his neighbors, who had since removed
to the city of Allvice—and wishing to raise his bond, he gave Grayson
$1060, being the principal and interest for one year, and money to
buy himself a suit of clothes, and started him to town. Grayson had
never been to the city before, and his hopes were very high. On the
evening of the third day's ride, he arrived in the city of Allvice, and
put up in Blockley Row, at Spendthrift Hotel, next door to the sign of
the Conscience-seared-with-a-hot-iron. After supper he went to the
bar-room, and asked a young man "how far it was to any place
where he could see some fun." "What, the theatre," said the young
man. "Any place where I can see a little fun," said he. The young
man said, "follow me." Ere long they were at the door of the theatre,
where Grayson saw in large letters over a door—"The way to the
pit." He knew not what it meant, but said to the young man, "Don't
let us go that way." "No," said his companion, "we will go to the
gallery. You know they are in the gallery." Grayson knew not who
was meant by the emphatic they; but following his guide, was soon
in a crowd of black and white women, and young and old men.
Taking the first lesson in the species of crime there taught, he
stepped down a little lower, and asked to what place a certain door
led. He was told, "to the boxes." Entering that door, he found many
a vacant seat, and listened—but when others laughed, he saw
nothing to laugh at, until the clown came on the stage. At him he
laughed—he roared. Yet he felt as if he had lost something, but
could not tell what it was. "In the midst of laughter the heart is sad,"
were words he often repeated, as he sat in a box alone. The play
being ended, he endeavored to find his way to the hotel, but was
greatly discomposed at remembering that his money had been left in
his saddle-bags, and they not locked, and that he had not seen them
since he came to town. At length he reached his lodgings, and found
all safe. He went to bed, but could not sleep. Most of the night was
spent in reflection, or rather in wild and vain imaginations. A little
before day a well dressed gentleman was shown into the room
where our young hero lay, there being two beds in the room. The
new inmate took a seat, and sighed; he paced the floor; he took out
his port-folio, and wrote a few words; he dropped his pen and said,
"What a fool." At length Griffith (for he is now too old to be called by
his given name,) ventured to inquire whether he could in any way
assist his room-mate to a greater composure. "O sir," said the man,
and sighed. At length the stranger said: "Eight days ago I left home
with $3,600 to go to the north to buy goods. I came here day before
yesterday, and to-night they have got the last cent from me at the
faro bank. And now, O what a fool!—I had rather take five hundred
lashes than do what I must,—write to my partner or my wife to send
me money to carry me home." Griffith expressed regret, but of
course could offer no consolation. He resolved, however, to pay the
$1,060 as soon as he could find the man to whom it was due. This
he accordingly did before nine o'clock next morning. The rest of the
day he walked the streets. Every little while $3,600 kept ringing in
his ears. At night, not having bought his suit of clothes, he went to
the bar, and there found the same young gentleman who the night
before had accompanied him to the theatre. Griffith took a seat by a
window, and the well dressed young man came to him and said:
"Young gentleman, I see you are fond of real genteel pleasure; let
us go down into hell, and win those fellows' money." Perhaps more
mingled emotions never agitated a bosom. In the first place he had
been called a young gentleman—an honor which, though he had
deserved it before, had seldom been given him. Then the idea of
"real and genteel pleasure." But the very sound of "going down to
hell!" He would not go in "the way to the pit" the night previous—
and now could he go to hell? At length he concluded that it was a
mere nickname, and that the place was really no worse than if it
were called heaven, and he replied, "I don't care if I do." They both
left the room and went to the stable. "Stop a minute," said Griffith,
"let me see if Decatur has a good bed and a plenty to eat." In half a
minute he satisfied himself that his horse fared well, and he followed
his young acquaintance into one of the stalls, through which they
passed by a blind door into a long, narrow and dark entry. "Follow
me," said the young man. Presently they entered a large room.
Griffith was struck with the abundance of good things to eat and
drink, which too were all free for visiters. At a table on one side, sat
an old man with a playful countenance. He rose and said: "Last night
a man won $3,600 at this table." Three thousand six hundred dollars
thought Griffith—and "how much had he to begin with?" said he to
the old gentleman. "Only a ten dollar note," was the reply. In
another part of the room, Griffith saw a young man sitting behind a
table, and leaning against the wall, with his hat drawn down over his
forehead, and wearing a heavy set of features. Before him on the
table lay three heaps of money—one of silver—another of gold—a
third of paper. Griffith eat some very fine blanc mange on the table,
and drank a little brandy, after which he concluded he would risk ten
dollars on a card. He did so, and put a ten dollar bill into his pocket.
His next risk was five dollars, which he lost. With various success he
spent an hour, at the end of which he had tripled his money. He then
retired to his room, and slept until a late hour in the morning. Then
he went to a merchant tailor, and ordered his new suit, and spent
the day in musing—visiting factories—attending auctions, and laying
plans for the night. "If I had held on I might have broke them," said
he; "I should have gotten $3,600!" Night came, and with it a self-
confident feeling peculiar to the young gambler. He returned alone
through the stall into "hell," and there lost all he had but five dollars.
The next night he won $150. The next night, which was to be his
last in the city, he went, and for a time succeeded. Once he had
$700 in pocket, but before day-light he had lost every cent he had,
and making known his situation, two men who had won his money,
gave him each five dollars, and advised him to leave town at day-
light. That was a wretched night to Griffith. His couch was a "bed of
unrest." His very dreams were startling. At daylight he paid his bill,
and had remaining three dollars and a quarter. He mounted Decatur,
and with a heavy heart journeyed towards the village of Goodcheer.
When he found himself in sight of home, he felt in his pocket and
found he had seventy-five cents. He also felt for the cancelled bond,
but could not find it. Riding into the woods, he examined his saddle-
bags, and found the bond in a waistcoat pocket. Seizing it with great
joy, he shed a tear, and mounted again. All the way home he had
thought much of the manner in which he should account for not
having the new clothes. At length seeing no way of escape, from
confusion at least, in case his father should inquire respecting the
matter, he cherished the hope that his father would say nothing. So
he paced along, and got home just in time for dinner. There was an
air of affected cheerfulness in young Griffith's gait and manner, that
was unusual. He did the best he could—took care early to deliver the
cancelled bond—said he was not much pleased with the city, and
told something of what he had seen. Next day his father asked if he
had gotten the new suit. He replied that he had concluded not to get
it then, and reddened very much. Mr. Griffith told his wife that he
had fears about Grayson. They both wept, and agreed to pray for
him more than usual.

In the course of time, young Griffith being twenty-one years old, left
his father's, with $700 and Decatur, to seek his fortune in the West.
He soon obtained employment, and in the course of two years was
able to commence business as partner in a new firm. But,
unfortunately, he was not satisfied in the village where he was, but
broke up and went to the town of Badblood, where he opened a
store. He was not long here until a quarrel commenced betwixt him
and one of his neighbors. The occasion of the quarrel was a
disagreement as to the beauty of a piece of music. One declared the
other to have a bad taste, and this was regarded as insulting. Of
course a challenge was given, and accepted. The day of combat
arrived. At the first fire no blood was spilt. This was owing to the
great agitation of both the combatants. At the second fire Griffith
wounded his antagonist slightly, but himself received no wound. At
the third fire Griffith's right arm was broken, and his antagonist was
wounded in the thigh. Here the seconds and friends interfered, and
declared they had fought enough. Had it not been for public opinion,
they would have thought that it was enough to be shot at once a
piece. But they were both content to quit, and even to drink each
other's health, before they left the ground. In the course of eight or
nine weeks, they were both in their usual health, and attending to
their accustomed duties.

The effect on Mr. Griffith's family on learning that Grayson was


expected to fight, was very distressing. The day the challenge was
given, Griffith wrote to his father thus:

My very dear Father:—On the morning of the day on which this


shall reach you in due course of mail, I shall have settled an
affair of honor. I do not love to fight, because I neither like the
idea of killing or being killed. If I go on the ground, I shall
certainly take life or lose it. I can't help it. I should be posted as
a coward, if I did not. Mr. B. will write you as soon as it is
decided. Love to mother and the children. God bless you. I can't
bear an insult. Your's ever,

G. GRIFFITH.

An entire week was this family in suspense, when at last, by request


of the father, dear Mr. Goodnews, the minister, was at the office, and
got the letter and opened it, and read the account as before given.
He immediately went to Mr. Griffith's, and found both the parents in
bed with a high fever, and their countenances covered with wan
despair. As he entered the door he tried to look cheerfully. "Grayson
is dead," said the almost frantic mother. "No, he is'nt," said the
minister. "Then he is mortally wounded," said she. "No, he is not,"
said he. "Then he is a murderer; he has killed a man! O, my first-
born Grayson!" "My dear Mrs. Griffith," said the good minister, "the
Lord is better than all your fears. Grayson and his antagonist are
both wounded indeed, but neither mortally." "O bless the Lord, bless
the Lord," said Mrs. Griffith, and swooned away. On using proper
means she was restored, and became calm and quiet; but it was an
hour before Mr. Goodnews could read the whole letter to her. Mr.
Griffith suffered greatly, but was much occupied with the care of his
wife. He really feared that things would have terminated fatally. In a
few days the parents rallied, and wrote Grayson a most affectionate
and solemn letter, which he never answered.

The next news of importance which these parents received


respecting their son was, that he was married to an amiable, though
a thoughtless and giddy girl. In a year they heard that he was the
father of a sweet boy. In eighteen months more they heard that he
had a sweet daughter. Not long after, they heard that he made
frequent and unaccountable excursions from home, and presently
they heard, that on a steam boat that ran between the town of
Badblood and the Bay of Dissipation, he had by gambling, lost all his
money. What they had heard was true. Losing his money, he
hastened home—made some arrangements for his family—disposed
of as much property as was left—received five hundred dollars in
hand—left two hundred with his wife—and with the other three
hundred set out professedly to visit his parents at the village of
Goodcheer. But the demon of gambling had possessed him—and
Griffith in a few weeks found himself with but one hundred dollars,
remaining at Spendthrift Hotel, in Blockley Row, in the city of Allvice
in the Old Dominion. Here Griffith resolved to retrieve his fortunes.
He sought the faro bank, and in an hour was pennyless. Poor Griffith
was not far from perfect ruin. He spent the night in dreadful
tossings, and in the very room where he had lodged years before.
He fancied that he saw "$3,600" in flaming figures before him. In
the morning he walked the streets. He watched to see whether he
could recognize any old friend among the hundreds he met. He read
the names on the sign-boards; he searched the morning papers; yet
no bright prospect opened before him. In the afternoon he
wandered into Purity Lane, and had hardly entered that street, when
he saw on the knocker at the door, "Amos Kindheart." He asked a
servant who was washing down the white marble steps, whether the
"Reverend" Mr. Kindheart lived there, and was answered in the
affirmative. Asking to be introduced into his presence, he was soon
shown into the study. "Is this the Rev. Mr. Kindheart?" said he. "It
is," replied the good man, "please to be seated." "Are you not
acquainted with Rev. Mr. Goodnews?" "Yes sir." "Do you not also
know Gregory Griffith?" "Yes sir; I stayed at his house more than a
week some years ago; and if I am not deceived, this is his son
Grayson, who used to exercise my horse night and morning when I
was there." Mr. Kindheart expressed much pleasure at seeing him,
and learned that he had a wife and two children in the town of
Badblood, in the State of Misery; he also learned that he had been a
merchant. Mr. Kindheart treated him very affectionately, gave him a
handsome little present, invited him to dinner next day, and excused
himself for that evening, as he had in a remote part of the city an
engagement that could not be broken. Early next morning a little
ragged servant handed Mr. Kindheart a sealed note from Griffith,
stating that he had been imprudent, and requesting him to send by
the bearer a sum sufficient to meet the expenses of a passage to the
pleasant village of Goodcheer, from which place the amount should
be returned at an early date. Mr. Kindheart replied in a note that he
had not the money then, but would get it before the next evening,
when the first stage would leave, and renewed the invitation to
dinner that day. Dinner came, but no Griffith was there. Several
hours before it was time for the stage to start, Mr. Kindheart called
with the money at Griffith's lodgings, but he was not to be seen. In
a short time he called again, and then again. Still he could not be
seen. The truth was, Griffith's conscience would not let him face a
man from whom he knew he desired money only that he might have
the means of gambling. He had no serious purpose of visiting
Goodcheer.

For many days Griffith loitered about the city in perfect


wretchedness, and without one cent of money. At length he went to
the proper city police officer, and told him that there were several
gambling establishments in town, that many persons visited them,
and that he could give important testimony in the case. Then going
to Hardface and Takeall, two gamblers, he told them that unless
they would give him $600, so that he might fairly and speedily
escape, he would be retained as a witness against them at the next
sessions. The gamblers agreed to give him $500, hastened his
departure in a private conveyance, but started after him a man, who
overtaking him in the next post town, horsewhipped him very
severely. Griffith bore this rough treatment like a dog. He squealed,
he cried, he howled, he danced—but he did not resist.

From this time Griffith wandered about, until, in the course of a few
months, he found himself again with his family. At first he seemed
pleased to kiss his babes and embrace his wife; but the next day
went to a faro bank in Badblood, and lost all he had—even his wife's
wardrobe and toilet. At this time he resolved on destroying his own
life. He went to three different shops, and procured laudanum in a
quantity sufficient to take life. He went home, and as he ascended
the first flight of stairs, he emptied the contents of each vial into his
stomach. O woman, what an angel of mercy thou art! His wife met
him at the door, with unwonted demonstrations of love. His little boy
prattled most sweetly; his little girl breathed in her crib as gently as
a May zephyr. His wife told him of several pleasant and smart things
which the children had said and done that day. He began to weep—
then to tremble—then to dislodge the contents of his stomach. "My
dear Nancy," said Griffith, "I shall be dead in a few hours, but never
mind." His wife perceiving that laudanum was in his stomach,
instantly prepared a potent emetic, and mixing it with a large
tumbler of hot water, offered it to her husband, and he consented to
drink it, supposing it could not be improper. In a few minutes,
through the influence of nausea, from the effects of brandy, and
from the dose just given, the stomach was emptied. Poor Griffith
suffered much, but gradually recovered. None save his wife knew of
the attempted violence on his own life.

At length a few benevolent people proposed to him to leave


Badblood, and go into the interior. He consented, and they gave him
the necessary money, as he and his family entered the stage. Griffith
was much affected by their kindness, especially that of one old
Baptist gentleman, who said very tenderly, "God bless you all." They
travelled day and night, until they were two hundred miles from the
place of their recent miseries, when a violent fever and painful
dysentery in their little boy compelled them to stop. The house
where they stopped, though not promising much in outward
appearance, was yet neat and clean. Mr. Felix, the landlord, and his
wife, were intelligent, industrious and pious. They were strict
temperance people, and no liquor could be had for drink within
fifteen miles. Griffith of course became very cool. The first day he
was very wretched; he had no employment—he had no heart to
assist in nursing the sick boy. Towards evening he took a gun and
walked into the field, and shot a partridge. At first he seemed
pleased that he might thus promote the comfort of his little son, but
then he remembered that animal food of any kind would injure him.
The next day he was more miserable than ever, until about noon he
saw fishing rods, and on inquiry found that there was a fish-pond
not very distant. He went and angled for hours, but the hot sun had
driven every fish under the banks and tussocks. He sat four long
hours, and had not even a nibble. He returned with a heavy heart;
yet it was pleasant to more than his wife, to observe a growing
earnestness and frequency of inquiry into the health of his child. The
next day, being Friday, a meeting commenced at a church not three
hundred yards distant from the house of their kind landlord, and by
a little persuasion, Griffith was prevailed on to attend. The first
sermon was very animated, and was on that text: Isaiah lii. 3: "Thus
saith the Lord; ye have sold yourselves for naught, and ye shall be
redeemed without money." Griffith sat on the back seat, and paid
more attention than one would have supposed from his appearance.
The second sermon was preached by an old gentleman, on the text,
1 Timothy, i. 15: "This is a faithful saying and worthy of all
acceptation, that Christ Jesus came into the world to save sinners, of
whom I am chief." Returning home, Griffith thought the preachers
both affectionate and able; but he really thought some things must
be personal. Indeed, the young man who had preached first, had a
very dark and piercing eye, which when animated in preaching,
made almost every one think he was looking all the while at him
alone. When Griffith came home, he sat by his sick child, and told
his wife what he had seen and heard. That night he was restless and
wakeful. In the morning he took a long walk before breakfast, and at
the usual hour repaired to the church. A sermon was then preached
on the Cities of Refuge, and the preacher earnestly exhorted his
hearers to flee for refuge to the hope set before them in the gospel.
The exercises of Saturday afternoon, were prayer and singing,
accompanied by short and solemn exhortations. In all these services
Griffith manifested deep interest, though he said nothing, except
that he detailed to his wife what he had seen and heard. He also
said, that as their boy was now much improved in health, and as Mr.
Felix's oldest daughter would stay at home next day, his wife must
accompany him to church. Sabbath morning came, and although
there seemed to be many difficulties, yet they were all surmounted,
and Mrs. Griffith and her husband, for the first time in several years,
went in company to the house of God. The text was, Isaiah liii. 5:
"He was wounded for our transgressions, he was bruised for our
iniquities; the chastisement of our peace was upon him; and with his
stripes we are healed." During the delivery of this sermon, Griffith
was seen to weep. His wife, however, had two reasons for not
feeling easy. Her apparel was really poor; but she was soon relieved,
by seeing that all the people were plainly attired. She also suffered
much uneasiness about her son. But good Mrs. Felix had directed
her eldest son to return home in an hour after the service should
begin, and bring word whether all was right. Her son came with a
message, which she soon, in a whisper, communicated to Mrs.
Griffith. The message was, that the boy had fallen asleep—that his
room had been made dark—that he seemed to sleep very sweetly,
and would perhaps not wake for an hour or two. Mrs. Griffith got the
message just in time to be entirely composed during the
administration of the Lord's Supper, which service immediately
succeeded the first sermon. It was a solemn scene. There were few
dry eyes in the house. At the close of the communion service, the
company of believers rose and sang that favorite spiritual song—

"How happy are they


Who the Savior obey," &c.

Griffith and his wife both thought "how happy are they." They both
hastened home, as did Mrs. Felix also. Finding their boy much better,
and their kind hostess herself determining to remain at home in the
afternoon, both Mr. and Mrs. Griffith returned to the church. When
they came near the church they heard singing, and just as they
entered the door, the congregation sung, and repeated the closing
lines of a hymn as follows:

"Here, Lord, I give myself away,


'Tis all that I can do."

Griffith sighed, and said to himself—"O that I could give myself


away, and the gift be accepted." They had just taken their seats,
when the preacher announced his text in Revelation xxii. 17: "And
the spirit and the bride say, come: and let him that heareth say,
come: and let him that is athirst, come: and whosoever will, let him
take the water of life freely." The sermon did not exceed forty
minutes in length, yet it was a faithful, tender and solemn entreaty
to all sinners, the least and the most vile, to come to Christ and live.
After service, one of the ministers went home with Mr. Felix, and
having observed Griffith's behavior at church, he said many good
things in his presence and for his benefit. Griffith and his wife spent
most of that night in solemn reflection and silent prayer. On Monday
morning a neighbor called to complete some arrangements with Mr.
Felix, in reference to supplying the place of their teacher, who had
recently died. In an unexpected train of conversation, they were led
to speak of Griffith as perhaps a suitable man. In a few days it was
mutually agreed that Griffith should teach the school for the rest of
that session, which was but three months. His family being provided
for, he commenced his school. Yet for days and weeks, both he and
his wife suffered much pain and darkness of mind. At length they
both, about the same time, hoped that they had found him, of
whom Moses in the law and the prophets did write. After trial of
some weeks, they were admitted to the communion. The day after
this event, Griffith wrote an affecting letter to his venerable parents.
This letter was evidently blessed, not only to the comfort of their
hearts, but also many of the pious people in Goodcheer were much
affected by it.

"Great is the grace, the neighbors cried,


And owned the power Divine."

Griffith immediately established the worship of God in his family, and


rejoiced in God with all his heart. Nor was his wife a whit behind in
holy delight at the change. Griffith's conversion led him to inquire
into the lawfulness of gambling. He had three questions to decide.
The first was, whether he should pay a debt of $60 incurred in
gambling? He soon resolved to pay it, as it was the manner of
contracting, and not the payment of the debt, that was the sin. The
next question was, what should he do respecting the $9,000, which
he found by estimate he had lost at different times? To this he could
only say, that most of it was won by strangers, and by men who had
long since died in wretchedness and poverty. He could not get it. By
a careful estimate of what he had won from men whose names and
residence he knew, over and above what they had won from him,
and including the $500 extorted from the gamblers, by threatening
to volunteer as witness against them, he found that he owed in all,
rather more than $1,500. Resolving to pay the whole sum, if spared
and prospered, he engaged to teach school another session of ten
months; and although he could not save much of his earnings, he
resolved to save what he could.

How astonished was he, when a few days after he formed this
purpose, as he was going to school in the morning, a gentleman
hailed him as Mr. Griffith, and said: "Sir, I won from you several
years ago nearly $700; there is the money, with some interest. I am
a christian. I cannot keep it; there it is." With these few words, the
traveller proceeded. Griffith was so amazed, that he even forgot to
ask his name, or residence, or the course of his journey. Of the
$700, Griffith sent $200 to the widow of a poor silly drunken man,
from whom he had, not long before his complete downfall, won that
amount. He sent $200 more to a young clerk, whom he had well
nigh ruined as to morals and character, and from whom he had won
$180 two years before. He sent $300 to the father of a little blind
girl, from whose deceased brother he had won that amount, saving
the interest, and requesting that it might be employed to send the
blind child to the Asylum for the blind. By the kindness of
Providence, other sums were restored to him, amounting in all to a
few hundreds. His economy and industry, and good capacity as a
teacher, also secured to him a growing income from his school—so
that in a few years he had paid every debt, and restored all money
obtained by gambling. He has since bought a small tract of land, and
built a very neat cabin, with two apartments, upon it. He calls it the
Retreat. He is now forty-three years old—still keeps a school—has a
good income from his own industry—enjoys tolerable health, and
has around him many of the comforts of life. His wife and children
still live, and help to make him happy. His penitence and humility are
deep; yet is thankfulness the reigning exercise of his heart. The
goodness and grace of God, through Jesus Christ, are themes on
which he never tires.

Dryden's genius was of that sort which catches fire by its own
motion; his chariot wheels got hot by driving fast.—Coleridge.

For the Southern Literary Messenger.

LINES

Written in Mrs. ——'s Album.

Give me a subject! O! propitious fate!


That by collision with my frigid brain
Shall strike out fire!1 Love? Honor? Friendship? Hate?
The jaded ear doth loathe the hackneyed train!

Give me a subject! thus a Byron sang—


And from the Poet's mind in perfect form
Like brain-born PALLAS, forth Don Juan sprang,
A captivating Demon—fresh and warm.

Give me a subject! Alexander raved,


A world to conquer!—and the red sword swept—
No truant Planet sought to be enslaved,
And bully Ellick disappointed wept!

A theme, ye stars! that with yon clouds bo-peep—


They wink, sweet Madam!—but, alas! are dumb:
"I could call spirits from the vasty deep"
To freeze thy gentle blood! But would they come?

There are no themes in this dull changeless world!


Spinning for aye on its own icy poles—
Forever in the self-same orbit whirled,
A huge TEE-TOTUM with concentric holes!

Ev'n Heaven itself had not poetic been


Though filled with seraph hosts in guiltless revel,
Had not one bright Archangel changed the scene—
Unlucky wight! to play himself the Devil!

Then came the tug of Gods! for rule and life—


The unmasked thunders shook the stable sky—
But MILTON sings of the immortal strife,
And lived much nearer to the times than I.

Prythee! go seek him, if thou would'st be told


A graphic story, pictured to the ear
With matchless art, by one who did behold,
So thou wouldst think—the war storm raging near.

Hast read the Poem, Ma'am? So have not I,


But I have heard that what I say is true—
And by my faith I'm much disposed to try
And give the Devil's bard and Devil his due!

But I am modest—and do not intend


To outsoar Milton in his lofty flight—
Nor would my Muse poor Byron's ghost offend,
He hated rivalry—and so—good night!
1 A familiar suggests that an "oaken towel" might produce the desired effect. No
doubt; and hence the expression "cudgel thy brains."

For the Southern Literary Messenger.

THE DIAMOND CHAIN.

While Rosa near me sweetly sung,


And I beheld her blue eyes' light,
A chain around my heart was flung,
Its every link a diamond bright.

But now that we are forced to part,


And her loved voice no more I hear,
The chain is withering up my heart—
Its diamonds each a burning tear.
QUESTUS.

For the Southern Literary Messenger.

WHERE SHALL THE STUDENT REST?


Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like