learn to program with c - home - springer978-1-4842-1371-1/1.pdf · learn to program with c noel...

22
Learn to Program with C Noel Kalicharan

Upload: trantuyen

Post on 01-May-2018

224 views

Category:

Documents


1 download

TRANSCRIPT

Learn to Program with C

Noel Kalicharan

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 SpahrLead Editor: Steve AnglinTechnical Reviewer: Rohan WaliaEditorial 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 PowersCopy Editor: Karen JamesonCompositor: SPi GlobalIndexer: SPi GlobalArtist: 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.

To my daughters

Anushka Nikita

and

Saskia Anyara

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

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

viii

■ Contents

1.7 Write Output with printf ........................................................................................ 141.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

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 f loat 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

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

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

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

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

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.

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.

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.

xxi

Preface

This book attempts to teach computer programming to the complete beginner using the C language. As such, it assumes you have no knowledge whatsoever about programming. And 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. In this book, knowledge of primary school mathematics is all that is required—basic addition, subtraction, multiplication, division, finding the percentage of some quantity, finding an average or the larger of two quantities.

Some of our most outstanding students over the last thirty years have been people with little mathematics background from all walks of life—politicians, civil servants, sports people, housewives, secretaries, clerical assistants, artists, musicians and teachers. On the other hand, we’ve had mathematical folks who didn’t do as well as might be expected.

What will be an asset is the ability to think logically or to follow a logical argument. If you are good at presenting convincing arguments, you will probably be a good programmer. Even if you aren’t, programming is the perfect vehicle for teaching logical thinking skills. You should learn programming for these skills even if you never intend to become a serious programmer.

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. 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 programs as well—word processing programs, spreadsheet programs, database management programs, accounting programs, games, educational software—the list is endless.

However, this book is more about teaching programming basics than it is about teaching C. 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.

Chapter 1 gives an overview of the programming process. Chapter 2 describes the basic building blocks needed to write programs. Chapter 3 explains how to write programs with the simplest kind of logic—sequence logic. Chapter 4 shows how to write programs which can make decisions. Chapter 5 explains the notion of ‘looping’ and how to use this powerful programming idea to solve more interesting problems. Chapter 6 deals with the oft-neglected, but important, topic of working with characters. Chapter 7 introduces functions—the key concept needed for writing large programs. Chapter 8 tackles the nemesis of many would-be programmers—array processing. Chapter 9 explains how lists of items stored in arrays can be searched, sorted and merged. And Chapter 10 deals with structures—the collection of one or more items, possibly of different types, grouped together under a single name for convenient handling.

The first step in becoming a good programmer is learning the syntax rules of the programming language. This is the easy part and many people mistakenly believe that this makes them a programmer. They get carried away by the cosmetics—they learn the features of a language without learning how to use them to solve problems.

xxii

■ PrefaCe

Of course, you must learn some features. But it is far better to learn a few features and be able to use them to solve many problems rather than learn many features but can’t use them to solve anything. For this reason, this book introduces a feature (like an if statement, say) and then discusses many examples to illustrate how the feature can be used to solve different problems.

This book is intended for anyone who is learning programming for the first time, regardless of age or institution. The material has been taught successfully to students preparing for high-school examinations in Computer Studies or Information Technology, students at college, university and other tertiary-level institutions.

The presentation is based on the experience that many people have difficulty in learning programming. To try and overcome this, we use an approach which provides clear examples, detailed explanations of very basic concepts and numerous interesting problems (not just artificial exercises whose only use is to illustrate some language feature).

While computer programming is essentially a mental activity and you can learn a fair amount of programming from just reading the book, it is important that you “get your hands dirty” by writing and running programs. One of life’s thrills is to write your first program and get it to run successfully on a computer. Don’t miss out on it.

But do not stop there. The only way to learn programming well is to write programs to solve new problems. The end-of-chapter exercises are a very rich source of problems, a result of the author’s forty-odd years in the teaching of programming.

Thank you for taking the time to read this book. I hope your venture into programming is a successful and enjoyable one.

—Noel Kalicharan