ebook img

Programming in Ansi C PDF

485 Pages·2016·3.4 MB·Tagalog
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Programming in Ansi C

Programming in C Ram Kumar Late, Professor, University of Udaipur, Udaipur Late, Professor, Motilal Nehru Regional Engineering College, Allahabad Rakesh Agrawal IBM Almaden Research Center, San Jose, California West Publishing Company St. Paul New York Los Angeles San Francisco Production credits Copyediting: Martha Knutson Composition: Professional Book Center Text Design: Lois Stanfield Cover Design: Elaine Saint-Marie COPYRIGHT © 1992 By WEST PUBLISHING COMPANY 610 Opperman Drive P.O. Box 64526 St. Paul, MN 55164-0526 All rights reserved Printed in the United States of America 99 98 97 96 95 94 93 8765432 Library of Congress Cataloging-in-Publication Data Kumar, Ram. Programming in ANSI C / Ram Kumar, Rakesh Agrawal p. cm. Includes bibliographical references and index. ISBN 0-314-89563-9 (soft) 1. C (Computer program language) I. Agrawal, Rakesh. n. Title. QA76.73.C15K86 1992 005.26'2—dc20 91-26474 CIP For Mrs. Urmila Agrawal with love and gratitude Notices IBM is a registered trademark of International Business Machines Corp. Microsoft is a registered trademark of Microsoft Corp. MS-DOS is a registered trademark of Microsoft Corp. PDP and VAX are registered trademarks of Digital Equipment Corp. Turbo C is a registered trademark of Borland International Incorporated. UNIX is a registered trademark of AT&T. WordPerfect is a registered trademark of WordPerfect Corp. WordStar is a registered trademark of MicroPro International Corp. The programs presented in this book have been included for their instruc- tional value. The authors do not offer any warranties or representations, nor do they accept any liabilities. vi Biographies RAM KUMAR Dr. Ram Kumar was Professor and Head of the Department of Mathematics, University of Udaipur, Udaipur, and Motilal Nehru Regional Engineering Col- lege, Allahabad. He was a noted scholar and was engaged in research and teaching for over 40 years. He wrote several books, including the highly popu- lar Programming with FORTRAN 77. He was a holder of both Ph.D. and D.Sc. degrees. On his D.Sc. thesis, he was awarded the Bonarjee Research Prize by the University of Lucknow for the best research production of 1963. He was a Fellow of the National Academy of Sciences, India. RAKESH AGRAWAL Dr. Rakesh Agrawal is a Research Staff Member at the IBM Almaden Research Center, San Jose, California. He was a member of Technical of Staff at the AT&T Bell Laboratories, Murray Hill, New Jersey from September 1983 to December 1989. He holds M.S. and Ph.D. degrees in Computer Science from the Univer- sity of Wisconsin, Madison. He has published extensively in technical journals and conferences. He is a co-designer of 0++, a database programming lan- guage based on C++. He is an Editor of the IEEE Data Engineering and the Database Technology, and was a Program Chairman of the 2nd International Sym- posium on Databases in Parallel and Distributed Systems. He is a Senior Member of IEEE and a Member of ACM. vii PREFACE in order for you to develop an intuitive understanding of them. They are then rigorously discussed in the remainder of the chapter. Each chapter ends with a set of exercises that allow you to review and test your understanding of the new material. Examples and exercises have beenv selected from various dis- ciplines and application domains, including business, engineering, science, mathematics, and statistics. Illustrative programs have been run and tested under both UNIX and DOS environments. Organization We begin with an overview of the computer organization in Chapter 1. The principal components of computer hardware — memory, control unit, arithme- tic-logic unit, and input/output devices — are described. We then discuss com- puter software and programming languages, explaining the differences between machine, assembly, and higher level languages. A brief history of the evolution of C is also given. We then describe the programming process: prob- lem definition, program design, program coding, program compilation and execution, program testing and debugging, and program documentation. Algorithm development, which is the heart of computer programming, is also discussed in this chapter. We start learning the specifics of C in Chapter 2. A useful starting point for understanding computer programming is that all programs can be written using just three logical structures: sequential, selective, repetitive, or a combi- nation thereof. We first discuss the sequential structure, which consists of one operation followed by another, and then introduce some C constructs sufficient to write simple sequential programs. In particular, we examine the main func- tion, the C character set, various data types, variables and constants, arithmetic operators, assignment statements, input and output functions, type conver- sions, and simple macros. The selective structure, which consists of a test for a condition followed by alternative paths that the program can follow, is discussed in Chapter 3. Selec- tion among alternative processing is programmed with certain decision-mak- ing constructs: conditional statement, nested conditional statement, multiway conditional statement, and constant multiway conditional statement. Besides introducing these constructs, we also examine the relational, logical, and condi- tional expression operators necessary for understanding these constructs. The repetitive structure, also known as the iterative or loop structure, allows a set of program statements to be executed several times even though they appear only once in the program. This topic is discussed in Chapter 4. The constructs presented include while loop, do-while loop, for loop, and nested loops. The facilities for loop interruption are also discussed. A C program is usually developed by dividing it into logically coherent functional components, each of which carries out a specific task. We discuss the user-defined functions in Chapter 5. In particular, we look at how a function is defined and called, function prototypes, block structure, external variables, storage classes, separate compilation and data abstraction, and recursion. Arrays, which enable a user to organize and process a set of ordered data items, are the subject of Chapter 6. We discuss array type declaration, arrav ini- Preface C has emerged as the most widely used programming language for software development. It is a small, yet powerful language. It features modem control flow and data types that allow the development of well-structured programs. Its data types and control structures are directly supported by most computers, resulting in the construction of efficient programs. It is independent of any particular machine architecture or operating system, which makes it easy to write portable programs. It is this combination of rich control structures and data types, ability to get close to computer hardware, efficiency, portability, and concisenessi that has contributed to the popularity of C. Audience This book teaches computer programming using C. It does not presume prior knowledge of some other programming language, and teaches C from first principles. At the same time, it is a complete description of C. Even knowledge- able C programmers should find the examples and exercises interesting and challenging. This book can be used either as a textbook for a course on pro- gramming, as a source book for a training course on C, as a guide for self-teach- ing C, or as a reference by software professionals. Approach The text is designed in such a way that it gradually introduces new concepts, gives examples based on the concepts introduced so far, and then builds on what you have already assimilated. There is a strong emphasis on examples. The book is full of illustrative programs that exemplify how different language con- structs can be put together to solve a given problem. Examples in each chapter have been chosen so that they not only embody the various language con- structs introduced in that chapter, but also use the ideas learned in previous chapters. In this way, concepts are reinforced and covered at a deeper level in each new context. In several instances, the same problem has been solved using different language constructs to clarify differences between them. Concepts are first introduced informally through one or more motivating example programs ix PREFACE xi tialization, and how array elements are accessed. We also study arrays as func- tion arguments. We examine in Chapter 7 one of the most sophisticated features of C: point- ers. After introducing the basics of pointers, such as pointer type declaration, pointer assignment, pointer initialization, pointer arithmetic, pointer compari- son, and pointer conversion, we discuss the relationship between functions and pointers, arrays and pointers, strings and pointers, and multidimensional arrays and pointers. We then look at pointer arrays, pointers to functions, and dynamic memory management. Structures allow a fixed number of data items, possibly of different types, to be treated as a single object, whereas unions allow a number of different types of grouped data items to be referred to using the same name. These top- ics form the subject matter of Chapter 8. Besides introducing the techniques for defining and using structures and unions, we discuss the scope rules for struc- ture definitions, structures as function arguments, structures as function val- ues, nested structures, arrays of structures, structures containing arrays, struc- tures containing pointers, and self-referential structures. Systems programs frequently require the capability to manipulate individ- ual bits of a word. C provides four operators, called bitwise logical operators, for masking operations on bits, and two operators, called the bitwise shift oper- ators, for shifting bits in a word. In addition, C allows a word to be partitioned into groups of bits, called bit-fields, and names to be assigned to them. We study these features in Chapter 9. C does not provide language constructs for input/output (I/O) operations. However, ANSI C has defined a rich set of functions to provide a standard I/O system for C programs. We discuss in Chapter 10 the functions available in the standard I/O library and their use in writing applications involving file pro- cessing that require large amount of data to be read, processed, and saved for later use. The C preprocessor, which can conceptually be thought of as a program that processes the source text of a C program before it is compiled, is the subject of Chapter 11. The three major functions of the C proeprocessor discussed are macro replacement, conditional inclusion, and file inclusion. Macro replace- ment is the replacement of one string by another, conditional inclusion is the selective inclusion and exclusion of portions of source text on the basis of a computed condition, and file inclusion is the insertion of the text of a file into the current file. In addition, the line, error, pragma, and null directives, and the predefined macro names are also described. We discuss some additional C features in Chapter 12. In particular, we describe the type definition facility, which allows synonyms to be defined for existing data types; the type qualification facility, which permits greater control over program optimization; the enumeration type, which provides the facility to specify the possible values of a variable by meaningful symbolic names; the facility to define functions that take variable number of arguments; the storage class specifier register, which can speed up programs by specifying to the com- piler the heavily used variables to be kept in machine registers; facilities for alternative representation of characters; and the goto statement, which can be used to branch around one or more statements. xii PREFACE The book contains six appendices. Appendix A describes functions included in the standard library but not presented in the text earlier. Appendix B summarizes C operators together with their precedence and associativity. Appendix C explains the main differences between ANSI C and the version of C as described in Kernighan and Ritchie's 1978 book "The C Programming Language." Those of you who still have pre-ANSI C compilers will find this appendix particulary useful. Appendix D reviews the decimal, binary, octal, and hexadecimal number systems, discusses how numbers in any one of these systems can be converted into numbers in the others, and describes how num- bers and characters are represented inside the computer. Appendix E gives a table of ASCII and EBCDIC character codes and equivalent representations of some decimal numbers in the binary, octal, and hexadecimal systems. Appen- dix F lists some classical references on programming and C. We believe that the best way to learn programming is by reading, writing, and experimenting with programs. To increase your understanding of C, we encourage you to read and re-read the example programs given in the book and to solve as many exercises as you can. We also encourage you to experi- ment with the programs by running them with different test inputs, by modify- ing them to use alternate constructs, and by enhancing them with error check- ing and additional functionality. The source code for the programs given in the illustrative examples has been made available on a compainion diskette to aid this process. We hope that this text will make problem solving on computers an exciting and rewarding endeavor, and that you will find computer programming a fun experience. We appreciate receiving suggestions for improvements and ideas for additional illustrative examples and exercises. Acknowledgments We have been fortunate to have had the advise and criticism of many talented people who reviewed earlier drafts of this book. In particular, we would like to mention Stephen J. Allan, Utah State University; Eric P. Bloom, Bentley College; John L. Carroll, San Diego State University; John Crenshaw, Western Kentucky University; Grady Early, Southwest Texas State University; Maurice L. Eggen, Trinity University; Rhonda Ficek, Moorhead State University; Robert C. Gann, Hartwick College; Gordon Hoagland, Ricks College; Peter C. Isaacson, Univer- sity of Northern Colorado; Keith E. Jolly, Chabot College; William Jones, Cali- fornia State University, Dominquez Hills; Lyndon Marshall, College of Great Falls; Eric Nagler, De Anza, Mission, and Ohlone Colleges; Kenneth Pierce, University of Mary Hardin-Baylor; Arline Sachs, Northern Virginia Commu- nity College; Peter Schleppenbach, Los Angeles Pierce College; and Jack van Luik, Mount Hood Community College. We have had a pleasant relationship with West. Rick Mixter believed in this project from day one and kept us focused on students. Keith Dodson put in a great deal of effort in bringing this project to fruition. Tom Modi enthusiasti- cally experimented with many new ideas in the production of this book. Mar- tha Knutson helped us smooth many language wrinkles. Liz Grantham was instrumental in the promotion of the book. We thank them and others at West. PREFACE xiii This book would not have completed without the support and patience of our family. They are the ones who had to constantly endure our "Not this weekend, I have to work on the book" answers. Ram Kumar Rakesh Agrawal

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.