Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Learn to Program with C
Nội dung xem thử
Mô tả chi tiết
www.apress.com
Kalicharan Learn to Program with
C
Learn to
Program with C
Learn to Program using the Popular
C Programming Language
—
Noel Kalicharan
Learn to Program with C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS® THE EXPERT’S VOICE® IN PROGRAMMING
Learn to Program with C teaches computer programming to the complete beginner using the
native C language. As such, it assumes you have no knowledge whatsoever about programming.
The main goal of this book is to teach fundamental programming principles using C, one of the
most widely used programming languages in the world today.
We discuss only those features and statements in C that are necessary to achieve our goal.
Once you learn the principles well, they can be applied to any language. If you are worried that
you are not good at high-school mathematics, don’t be. It is a myth that you must be good at
mathematics to learn programming.
C is considered a ‘modern’ language even though its roots date back to the 1970s. Originally,
C was designed for writing ‘systems’ programs—things like operating systems, editors,
compilers, assemblers and input/output utility programs. But, today, C is used for writing all
kinds of applications as well—word processing programs, spreadsheet programs, database
management programs, accounting programs, games, robots, embedded systems/electronics
(i.e., Arduino), educational so ware—the list is endless.
• How to get started with programming using the C language
• How to use the basics of C
• How to program with sequence, selection and repetition logic
• How to work with characters
• How to work with functions
• How to use arrays
Shelve in:
Programming Languages/ANSI C
User level:
Beginning
9 781484 213728 SOURCE CODE ONLINE
ISBN 978-1-4842-1372-8
www.it-ebooks.info
Learn to Program
with C
Noel Kalicharan
www.it-ebooks.info
Learn to Program with C
Copyright © 2015 by Noel Kalicharan
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with
reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed
on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or
parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its
current version, and permission for use must always be obtained from Springer. Permissions for use may be
obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under
the respective Copyright Law.
ISBN-13 (pbk): 978-1-4842-1372-8
ISBN-13 (electronic): 978-1-4842-1371-1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Steve Anglin
Technical Reviewer: Rohan Walia
Editorial Board: Steve Anglin, Louise Corrigan, Jonathan Gennick, Robert Hutchinson,
Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper,
Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing
Coordinating Editor: Mark Powers
Copy Editor: Karen Jameson
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text is available to
readers at www.apress.com/9781484213728. For detailed information about how to locate your book’s source
code, go to www.apress.com/source-code/. Readers can also access source code at SpringerLink in the
Supplementary Material section for each chapter.
www.it-ebooks.info
To my daughters
Anushka Nikita
and
Saskia Anyara
www.it-ebooks.info
v
Contents at a Glance
About the Author �����������������������������������������������������������������������������������������������������xv
About the Technical Reviewer �������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix
Preface �������������������������������������������������������������������������������������������������������������������xxi
■Chapter 1: Elementary Programming Concepts ���������������������������������������������������� 1
■Chapter 2: C – The Basics������������������������������������������������������������������������������������ 23
■Chapter 3: Programs with Sequence Logic ��������������������������������������������������������� 47
■Chapter 4: Programs with Selection Logic ���������������������������������������������������������� 65
■Chapter 5: Programs with Repetition Logic��������������������������������������������������������� 91
■Chapter 6: Characters���������������������������������������������������������������������������������������� 141
■Chapter 7: Functions ����������������������������������������������������������������������������������������� 165
■Chapter 8: Arrays ���������������������������������������������������������������������������������������������� 197
■Chapter 9: Searching, Sorting, and Merging ����������������������������������������������������� 243
■Chapter 10: Structures �������������������������������������������������������������������������������������� 279
Index��������������������������������������������������������������������������������������������������������������������� 307
www.it-ebooks.info
vii
Contents
About the Author �����������������������������������������������������������������������������������������������������xv
About the Technical Reviewer �������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix
Preface �������������������������������������������������������������������������������������������������������������������xxi
■Chapter 1: Elementary Programming Concepts ���������������������������������������������������� 1
1.1 Programs, Languages, and Compilers ........................................................................ 1
1.2 How a Computer Solves a Problem ............................................................................ 3
1.2.1 Define the Problem ........................................................................................................................ 3
1.2.2 Analyze the Problem ...................................................................................................................... 4
1.2.3 Develop an Algorithm to Solve the Problem .................................................................................. 4
1.2.4 Write the Program for the Algorithm .............................................................................................. 6
1.2.5 Test and Debug the Program ......................................................................................................... 8
1.2.6 Document the Program.................................................................................................................. 9
1.2.7 Maintain the Program .................................................................................................................... 9
1.3 How a Computer Executes a Program ........................................................................ 9
1.4 Data Types ................................................................................................................ 10
1.5 Characters ................................................................................................................ 11
1.6 Welcome to C Programming ..................................................................................... 12
1.6.1 Run the Program .......................................................................................................................... 13
1.6.2 A Word on Program Layout .......................................................................................................... 14
www.it-ebooks.info
viii
■ Contents
1.7 Write Output with printf ........................................................................................ 14
1.7.1 The Newline Character, \n (backslash n) .................................................................................... 15
1.7.2 Escape Sequences ...................................................................................................................... 16
1.7.3 Print the Value of a Variable ......................................................................................................... 16
1.8 Comments ................................................................................................................ 17
1.9 Programming with Variables .................................................................................... 18
■Chapter 2: C – The Basics������������������������������������������������������������������������������������ 23
2.1 Introduction .............................................................................................................. 23
2.2 The C Alphabet ......................................................................................................... 24
2.3 C Tokens ................................................................................................................... 24
2.3.1 Spacing Within a Program ........................................................................................................... 25
2.3.2 Reserved Words ........................................................................................................................... 27
2.3.3 Identifiers .................................................................................................................................... 27
2.3.4 Some Naming Conventions.......................................................................................................... 28
2.4 Basic Data Types ...................................................................................................... 28
2.5 Integer Numbers - int ............................................................................................. 29
2.5.1 Declaring Variables ...................................................................................................................... 29
2.5.2 Integer Expressions ..................................................................................................................... 29
2.5.3 Precedence of Operators ............................................................................................................. 30
2.5.4 Print an Integer Using a “Field Width” ......................................................................................... 31
2.6 Floating-Point Numbers – float and double ........................................................ 33
2.6.1 Print double and float Variables ................................................................................................ 34
2.6.2 Assignment Between double and float ..................................................................................... 36
2.6.3 Floating-Point Expressions .......................................................................................................... 36
2.6.4 Expressions with Integer and Floating-Point Values.................................................................... 37
2.6.5 Assigning double/float to int .................................................................................................. 38
2.7 Strings ...................................................................................................................... 38
2.8 The Assignment Statement ...................................................................................... 41
2.9 printf ..................................................................................................................... 42
www.it-ebooks.info
ix
■ Contents
■Chapter 3: Programs with Sequence Logic ��������������������������������������������������������� 47
3.1 Introduction .............................................................................................................. 47
3.2 Read Data Supplied by a User .................................................................................. 47
3.3 scanf ....................................................................................................................... 50
3.3.1 Read Data Into a float Variable ................................................................................................. 52
3.3.2 Read Data Into a double Variable ............................................................................................... 52
3.4 Read Strings ............................................................................................................. 54
3.5 Examples .................................................................................................................. 55
3.5.1 Problem 1 - Average .................................................................................................................... 55
3.5.2 Problem 2 - Square ..................................................................................................................... 56
3.5.3 Problem 3 - Banking .................................................................................................................... 57
3.5.4 Problem 4 – Tickets ..................................................................................................................... 60
■Chapter 4: Programs with Selection Logic ���������������������������������������������������������� 65
4.1 Introduction .............................................................................................................. 65
4.2 Boolean Expressions ................................................................................................ 65
4.2.1 AND, &&........................................................................................................................................ 66
4.2.2 OR, || ............................................................................................................................................ 67
4.2.3 NOT, ! ........................................................................................................................................... 68
4.3 The if Construct ...................................................................................................... 69
4.3.1 Find the Sum of Two Lengths ...................................................................................................... 72
4.4 The if...else Construct ....................................................................................... 75
4.4.1 Calculate Pay............................................................................................................................... 77
4.5 On Program Testing .................................................................................................. 80
4.6 Symbolic Constants .................................................................................................. 80
4.6.1 The #define Directive .................................................................................................................. 81
4.6.2 Example – Symbolic Constants ................................................................................................... 82
4.7 More Examples ......................................................................................................... 83
4.7.1 Print a Letter Grade ..................................................................................................................... 83
4.7.2 Classify a Triangle ........................................................................................................................ 85
www.it-ebooks.info
x
■ Contents
■Chapter 5: Programs with Repetition Logic��������������������������������������������������������� 91
5.1 Introduction .............................................................................................................. 91
5.2 The while Construct ................................................................................................ 91
5.2.1 Highest Common Factor .............................................................................................................. 96
5.3 Keep a Count ............................................................................................................ 97
5.3.1 Find Average................................................................................................................................ 99
5.4 Increment and Decrement Operators ..................................................................... 100
5.5 Assignment Operators ............................................................................................ 101
5.6 Find Largest ........................................................................................................... 102
5.7 Find Smallest ......................................................................................................... 105
5.8 Read Data from a File ............................................................................................. 106
5.8.1 fscanf...................................................................................................................................... 108
5.8.2 Find Average of Numbers in a File ............................................................................................. 108
5.9 Send Output to a File .............................................................................................. 110
5.9.1 fprintf......................................................................................................................................... 111
5.10 Payroll .................................................................................................................. 112
5.11 The for Construct ................................................................................................ 118
5.11.1 The for Statement in C ........................................................................................................... 120
5.11.2 A Bit of Aesthetics ................................................................................................................... 125
5.12 Multiplication Tables ............................................................................................. 125
5.13 Temperature Conversion Table ............................................................................. 129
5.14 Expressive Power of for ...................................................................................... 131
5.15 The do...while Statement ................................................................................ 132
5.15.1 Highest Common Factor .......................................................................................................... 133
5.15.2 Interest at the Bank ................................................................................................................. 134
■Chapter 6: Characters���������������������������������������������������������������������������������������� 141
6.1 Character Sets ........................................................................................................ 141
6.2 Character Constants and Values............................................................................. 142
6.3 The Type char ........................................................................................................ 143
www.it-ebooks.info
xi
■ Contents
6.4 Characters in Arithmetic Expressions .................................................................... 143
6.4.1 Uppercase To/From Lowercase ................................................................................................. 144
6.5 Read and Print Characters ..................................................................................... 145
6.6 Count Characters .................................................................................................... 152
6.6.1 Count Characters in a Line ........................................................................................................ 153
6.7 Count Blanks in a Line of Data ............................................................................... 153
6.8 Compare Characters ............................................................................................... 155
6.9 Read Characters from a File ................................................................................... 156
6.10 Write Characters to a File ..................................................................................... 157
6.10.1 Echo Input, Number Lines ........................................................................................................ 157
6.11 Convert Digit Characters to Integer ...................................................................... 161
■Chapter 7: Functions ����������������������������������������������������������������������������������������� 165
7.1 About Functions ...................................................................................................... 165
7.2 skipLines ............................................................................................................ 166
7.3 A Program with a Function ..................................................................................... 167
7.3.1 The Function Header .................................................................................................................. 168
7.3.2 How a Function Gets Its Data .................................................................................................... 169
7.4 max ......................................................................................................................... 170
7.5 Print the Day ........................................................................................................... 173
7.6 Highest Common Factor ......................................................................................... 175
7.6.1 Using HCF to Find LCM .............................................................................................................. 177
7.7 factorial .................................................................................................................. 178
7.7.1 Using Factorial ........................................................................................................................... 181
7.7.2 Combinations ............................................................................................................................. 182
7.8 Job Charge ............................................................................................................. 184
7.9 Calculate Pay .......................................................................................................... 185
7.10 Sum of Exact Divisors .......................................................................................... 186
7.10.1 Classify Numbers ..................................................................................................................... 186
www.it-ebooks.info
xii
■ Contents
7.11 Some Character Functions ................................................................................... 188
7.11.1 Position of a Letter in the Alphabet ......................................................................................... 189
7.12 Fetch the Next Integer .......................................................................................... 191
■Chapter 8: Arrays ���������������������������������������������������������������������������������������������� 197
8.1 Simple vs Array Variable ......................................................................................... 197
8.2 Array Declaration .................................................................................................... 198
8.3 Store Values in an Array ......................................................................................... 199
8.3.1 About Not Using Element 0 ........................................................................................................ 203
8.4 Average and Differences from Average .................................................................. 203
8.5 Letter Frequency Count .......................................................................................... 206
8.6 Making Better Use of fopen .................................................................................. 209
8.7 Array as Argument to a Function ............................................................................ 211
8.8 String – Array of Characters ................................................................................... 213
8.8.1 Reverse the Characters in a String ........................................................................................... 217
8.9 Palindrome ............................................................................................................. 220
8.9.1 A Better Palindrome Function .................................................................................................... 223
8.10 Array of Strings – Name of Day Revisited ............................................................ 225
8.11 A Flexible getString Function ............................................................................... 228
8.12 A Geography Quiz Program................................................................................... 230
8.13 Find the Largest Number ...................................................................................... 233
8.14 Find the Smallest Number .................................................................................... 235
8.15 A Voting Problem .................................................................................................. 235
■Chapter 9: Searching, Sorting, and Merging ����������������������������������������������������� 243
9.1 Sequential Search .................................................................................................. 243
9.2 Selection Sort ......................................................................................................... 246
9.2.1 Analysis of Selection Sort .......................................................................................................... 252
9.3 Insertion Sort .......................................................................................................... 252
9.3.1 Analysis of Insertion Sort ........................................................................................................... 258
9.3.2 Insert an Element in Place ......................................................................................................... 259
www.it-ebooks.info
xiii
■ Contents
9.4 Sort an Array of Strings .......................................................................................... 260
9.4.1 Variable-Length Arrays .............................................................................................................. 260
9.5 Sort Parallel Arrays ................................................................................................. 262
9.6 Binary Search ......................................................................................................... 264
9.7 Word Frequency Count ........................................................................................... 266
9.8 Merge Sorted Lists ................................................................................................. 271
9.8.1 Implement the Merge ................................................................................................................ 273
■Chapter 10: Structures �������������������������������������������������������������������������������������� 279
10.1 The Need for Structures ....................................................................................... 279
10.2 How to Declare a Structure .................................................................................. 280
10.2.1 typedef.................................................................................................................................. 283
10.3 Array of Structure ................................................................................................. 285
10.4 Search an Array of Structure ................................................................................ 286
10.5 Sort an Array of Structure .................................................................................... 287
10.6 Read, Search, and Sort a Structure ...................................................................... 288
10.7 Nested Structures ................................................................................................ 292
10.8 Work with Fractions ............................................................................................. 293
10.8.1 Manipulate Fractions ............................................................................................................... 294
10.9 A Voting Problem .................................................................................................. 295
10.10 Pass Structures to Functions ............................................................................. 304
Index��������������������������������������������������������������������������������������������������������������������� 307
www.it-ebooks.info
xv
About the Author
Dr. Noel Kalicharan is a Senior Lecturer in Computer Science
at the University of the West Indies, St. Augustine, Trinidad.
For 40 years, he has taught programming courses to people at all
levels. He has been teaching computer science at the University
since 1976. In 1988, he developed and hosted a 26-programme
television series entitled Computers - Bit by Bit. Among other
things, this series taught programming to the general public.
He is always looking for innovative ways to teach logical thinking
skills which go hand in hand with programming skills. His efforts
resulted in two games - BrainStorm! and Not Just Luck - which
won him the Prime Minister’s Award for Invention and Innovation
in 2000 and 2002, respectively. He is a Computer Science author
for Cambridge University Press which published his international
successes, Introduction to Computer Studies and C By Example.
The C book is ranked among the best in the world for learning the
C programming language. It has received glowing reviews from readers as far away as Australia,
Canada, India and Scotland. This book is written in a more leisurely style. Born in Lengua Village,
Princes Town, Trinidad, he received his primary education at the Lengua Presbyterian School
and his secondary education at Naparima College. He is a graduate of The University of the
West Indies, Jamaica, the University of British Columbia, Canada and The University of the
West Indies, Trinidad.
www.it-ebooks.info
xvii
About the Technical Reviewer
Rohan Walia is a Senior Software Consultant with extensive
experience in client-server, web-based, and enterprise application
development. He is an Oracle Certified ADF Implementation
Specialist and a Sun Certified Java Programmer. Rohan is
responsible for designing and developing end-to-end applications
consisting of various cutting-edge frameworks and utilities.
His areas of expertise are Oracle ADF, Oracle WebCenter, Fusion,
Spring, Hibernate, and Java/J2EE. When not working, Rohan loves
to play tennis, hike, and travel. Rohan would like to thank his wife,
Deepika Walia, for using all her experience and expertise to review
this book.
www.it-ebooks.info
xix
Acknowledgements
I would like to express my deepest appreciation to Shellyann Sooklal for the time and care she
took in reading the manuscript, oftentimes finding subtle errors that a less critical eye would have
overlooked.
www.it-ebooks.info