Sams Teach Yourself C in 24 Hours

Table of Contents | Next

About this Book

Teach Yourself C in 24 Hours
Tony Zhang
201 West 103rd Street
Indianapolis, Indiana 46290

To Ellen, my lovely wife, for her love and inspiration.

—Tony Zhang

Copyright © 1997 by Sams Publishing

FIRST EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 0-672-31068-6

Library of Congress Catalog Card Number: 97-65466

2000    99    98    97                       4    3    2

Interpretation of the printing code: the rightmost double-digit number is the year of the book's printing; the rightmost single-digit, the number of the book's printing. For example, a printing code of 97-1 shows that the first printing of the book occurred in 1997.

Composed in AGaramond and MCPdigital by Macmillan Computer Publishing

Printed in the United States of America

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

President, Sams Publishing
Richard K. Swadley

Publishing Manager
Greg Wiegand

Director of Editorial Services
Cindy Morrow

Managing Editor
Kitty Wilson Jarrett

Director of Marketing
Kelli Spencer

Product Marketing Manager
Wendy Gilbride

Assistant Marketing Managers
Jen Pock, Rachel Wolfe

Acquisitions Editor
Sharon Cox

Development Editor
Fran Hatton

Software Development Specialist
Brad Myers

Production Editors
Mary Ann Abramson
Kitty Wilson Jarrett

Copy Editor
Kimberly K. Hannel

Indexer
Benjamin Slen

Technical Reviewer
Karen Hay

Editorial Coordinators
Mandi Rouell
Katie Wise

Technical Edit Coordinator
Lynette Quinn

Editorial Assistants
Carol Ackerman
Andi Richter
Rhonda Tinch-Mize

Cover Designer
Tim Amrhein

Book Designer
Gary Adair

Copy Writer
David Reichwein

Production Team Supervisors
Brad Chinn
Charlotte Clapp

Production
Georgiana Briggs
Cyndi Davis
Sonja Hart
Mary Ellen Stephenson

Acknowledgments

Several years ago, my friend Joey Burton, who was then my supervisor at Kinley Corporation, asked me why many computer programming books were written in a way that set a deep learning curve and scared a lot of beginners away from learning programming languages. Joey, thank you for the question that became the motivation for me to write a computer book for beginners. Today I can proudly say that there is at least one book available for people who want to learn C, but have no previous programming experience.

It's said that editors and authors are friends. I couldn't agree more. Sharon Cox and Fran Hatton at Sams Publishing are my friends, and they have given me a lot of encouragement and help in every phase of the book's creation.

I'd also like to thank my other friends, Mary Ann Abramson, Kitty Wilson Jarrett, Kim Hannel, Karen Hay, and the other members of the editorial team at Sams. It would not have been possible to finish the book without their hard work. The readers of this book are very lucky to have this team, who is committed to producing high-quality books.

I greatly appreciate the love and support of my wife, Ellen, who has inspired me to look at the high-tech world from a different perspective. It's always a great joy to discuss issues of philosophy and literature with her. I wish I could sit in her class at Temple University.

My parents, whom I can never thank enough, gave me not only love and affection, but also the opportunity to receive the best education I could ever have when I was in China.

Tell Us What You Think!

As a reader, you are the most important critic and commentator of our books. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can help us make strong books that meet your needs and give you the computer guidance you require.

Do you have access to CompuServe or the World Wide Web? Then check out our CompuServe forum by typing GO SAMS at any prompt. If you prefer the World Wide Web, check out our site at http://www.mcp.com.

NOTE
If you have a technical question about this book, call the technical support line at 317-581-4669.

As the team leader of the group that created this book, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our books stronger. Here's the information:

Fax: 317-581-4669
E-mail: programming_mgr@sams.mcp.com
Mail: Greg Wiegand
Comments Department
Sams Publishing
201 W. 103rd Street
Indianapolis, IN 46290

About the Author

Tony Zhang is a software engineer with more than 15 years of computer programming experience. Besides application-level programming experience in GUI, client/server, database, and networking, Tony has enhanced his system-level programming skills for X86 microprocessors and advanced digital signal/image processors through his involvement on various projects. With a masters degree in physics, he has published dozens of research papers on solid-state lasers, light-scattering calculations, and computer programming.

Tony and his wife, Ellen, are currently working on a book that combines two fields: computer science and philosophy. Among his broad interests are painting and photography, the two things that Tony enjoys most.

You can reach Tony through Sams Publishing, or by e-mailing him at tt-zhang@ti.com.

Introduction

If one learns from others but does not think, one will be bewildered;
if one thinks but does not learn from others, one will be in peril.

—Confucius

Written in a plain and clear format, this book is designed to help you learn the C programming language as quickly as possible.

Unlike most other C books, this book offers many sample programs and exercises with
clear explanations and answers, which makes the concepts of the C language easier to be
understood. After reading this book, you'll be able to write C programs on your own.

Teach Yourself C in 24 Hours lays a solid groundwork for you in C programming. You will profit from this when you start to apply C programs to real problems or move on to learn other programming languages, such as Perl, C++, and Java.

Who Should Read This Book?

If this is your initial introduction to C, this book is written for you. In fact, in writing this book I assume that my reader has no previous programming experience. Of course, it's always a big plus if you have some knowledge of computers.

Special Features of This Book

This book contains the following special elements that make it simpler and clearer for you to digest the rudimentary features and concepts of C as they are introduced:

Syntax boxes explain some of the more complicated features of C, such as control structures. Each syntax box consists of a formal definition of the feature followed by an explanation. Here is an example of a syntax box:

The syntax for the malloc() function is

#include <stdlib.h>
void *malloc(size_t size);

Here, size specifies the number of bytes of storage to allocate. The header file, stdlib.h, has to be included before the malloc() function can be called. Because the malloc() function returns a void pointer, its type is automatically converted to the type of pointer on the left side of an assignment operator.

(You'll learn more about the malloc() function later in the book.)

Notes are explanations of interesting properties of a particular C program feature. Let's have a look at the following example of a note:

NOTE
In left-justified output, the value being displayed appears at the left end of the value field. In right-justified output, the value being displayed appears at the right end of the value field.

Warnings alert you to programming pitfalls you should avoid. Here is a typical warning:

WARNING
Never use the reserved keywords in C, or names of the C library functions as variable names in your program.

Tips are hints on how to write better C programs. The following is an example of a tip:

TIP
Using global variables increases your program's complexity, which in turn makes your program hard to maintain or debug. Generally, you're not advised to declare and use global variables unless they're absolutely necessary.

Programming Examples

As mentioned earlier, this book contains many useful programming examples with explanations. These examples are meant to show you how to use different data types and functions provided in C.

TYPE
OUTPUT
ANALYSIS
Each example has a listing of the C program; the output generated from that listing will follow. The example also offers an analysis of how the program works. Special icons are used to point out each part of the example: Type, Input/Output, and Analysis.

In the example shown in Listing IN.1, there are some special typographic conventions. The input you enter is shown in bold monospace type, and the output generated by the executable program of Listing IN.1 is shown in plain monospace type. The system prompt (C:\app> in the examples in this book) is also shown so that you know when a command is to be entered on the command line.

Listing IN.1 Read in a character entered by the user.

1:  /* INL01.c: Read input by calling getc() */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int ch;
7:
8:     printf("Please type in one character:\n");
9:     ch = getc(stdin);
10:    printf("The character you just entered is: %c\n", ch);
11:    return 0;
12: }

The following output is displayed after the executable file INL01.exe is created and run. The user enters the H character.

C:\app> INL01
Please type in one character:
H
The character you just entered is: H
C:\app>

In line 2 of Listing IN.1, the header file stdio.h is included for both the getc() and printf() functions used in the program. Lines 4_12 give the name and body of the main() function.

In line 6, an integer variable ch is declared, which is assigned to the return value from the getc() function later in line 9. Line 8 prints out a message that asks the user to enter one character from the keyboard. The printf() function in line 8 uses the default standard output stdout to display messages on the screen.

In line 9, the standard input stdin is passed to the getc() function, which indicates that the file stream is from the keyboard. After the user types in a character, the getc() function returns the numeric value (that is, an integer) of the character. Note that in line 9 the numeric value is assigned to the integer variable ch.

In line 10, the character entered is displayed on the screen with the help of printf(). Note that the character format specifier %c is used within the printf() function in line 10.

Q&A and Workshop

Each hour (that is, each chapter) ends with a Q&A section that contains answers to common questions relating to the lesson of the chapter. Following the Q&A section, there is a Workshop that consists of quiz questions and programming exercises. The answers to these quiz questions and sample solutions for the exercises are presented in Appendix E, "Answers to Quiz Questions and Exercises."

To help you solidify your understanding of each lesson, you are encouraged to try to answer the quiz questions and finish the exercises provided in the workshop.

Conventions Used in This Book

This book uses special typefaces to help you differentiate between C code and regular English, and to identify important concepts.

What You'll Learn in 24 Hours

Teach Yourself C in 24 Hours consists of five parts. In Part I, "The Basics of C," you'll learn the basics of the C language. Here is an overview of what you're going to learn:

Hour 1, "Getting Started," introduces you to the C language, the ANSI standard, and the basic software and hardware requirements for C programming.

Hour 2, "Writing Your First C Program," demonstrates the entire procedure of writing, compiling, linking, and running a C program.

Hour 3, "The Essentials of C Programs," teaches you several important concepts, such as constants, variables, expressions, and statements. The anatomy of a function is introduced in this hour as well.

Hour 4, "Data Types and Names in C," lists all reserved C keywords. Four data types, char, int, float, and double, are introduced in detail. Also, the rules of naming a variable are explained.

Hour 5, "Reading from and Writing to Standard I/O," teaches you to receive input from the keyboard, and print output on the screen with the help of a set of C functions, such as getc(), getchar(), putc(), putchar(), and printf().

Part II, "Operators and Control-Flow Statements," emphasizes operators and control-flow statements in C. The following is an overview of what you'll learn:

Hour 6, "Manipulating Data with Operators," teaches you how to use arithmetic assignment operators, the unary minus operator, increment/decrement operators, relational operators, and the cast operator.

Hour 7, "Doing the Same Thing Over and Over," introduces looping (that is, iteration) with the for, while, or do-while statements.

Hour 8, "More Operators," tells you about more operators, such as logical operators, bitwise operators, the sizeof operator, and the ?: operator, which are frequently used
in C.

Hour 9, "Playing with Data Modifiers and Math Functions," describes how to use data modifiers to enable or disable the sign bit, or change the size of a data type. Also, several mathematical functions provided by C are introduced.

Hour 10, "Getting Controls," introduces all the control-flow statements used in C. They are the if, if-else, switch, break, continue, and goto statements.

Pointers and arrays are discussed in Part III of this book, "Pointers and Arrays." The following is an overview of what you'll learn:

Hour 11, "An Introduction to Pointers," teaches you how to reference variables with pointers. Concepts such as left value and right value are also introduced.

Hour 12, "Storing Similar Data Items," explains how to declare and initialize arrays. The relationship between the array and the pointer in C is also discussed.

Hour 13, "Manipulating Strings," focuses on reading and writing strings. Several C library functions, such as strlen(), strcpy(), gets(), puts(), and scanf() are introduced to manipulate strings.

Hour 14, "Scope and Storage Classes in C," introduces block scope, function scope, program scope, and file scope. In addition, storage class specifiers or modifiers, such as auto, static, register, extern, const, and volatile are explained.

Part IV of this book, "Functions and Dynamic Memory Allocation," focuses on functions and dynamic memory allocations in C. The following is an overview of what you'll learn:

Hour 15, "Functions in C," describes the function declaration and definition in C. The function prototyping is explained, along with the function return type specification.

Hour 16, "Applying Pointers," teaches you how to perform pointer arithmetic operations, access elements in arrays with pointers, and how to pass pointers to functions.

Hour 17, "Allocating Memory," explains the concept of allocating memory dynamically. C functions, such as malloc(), calloc(), realloc(), and free(), are introduced with regard to the dynamic memory allocation.

Hour 18, "More Data Types and Functions," introduces the enum data type and the use of typedef. Function recursion and command-line arguments to the main() function are also taught in this hour.

Part V, "Structure, Union, File I/O, and More," discusses structures, unions, and disk file I/O in C. The following is an overview of what you'll learn:

Hour 19, "Collecting Data Items of Different Types," introduces the structure data type. You learn to access structure members, and pass structures to functions with the help of pointers. Nested and forward-referencing structures are also discussed in this hour.

Hour 20, "Unions: Another Way to Collect Dissimilar Data," describes the union data type, and the difference between union and structure. The applications of unions are demonstrated in several examples.

Hour 21, "Disk File Input and Output: Part I," explains the concepts of the file and the stream in C. The basics of disk file input and output are introduced in this first part. The following C functions, along with several examples are introduced in this hour: fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fread(), fwrite(), and feof().

Hour 22, "Disk File Input and Output: Part II," is the second part of disk file I/O, in which fseek(), ftell(), and rewind() are introduced to show how they can help you get random access to disk files. In addition, the fscanf(), fprintf(), and freopen() functions are taught and invoked in sample programs.

Hour 23, "The C Preprocessor," describes the role played by the C preprocessor. You can learn the preprocessor directives, such as #define, #undef, #ifdef, #endif, #ifndef, #if, #elis, and #else through the examples given in this hour.

Hour 24, "What You Can Do Now," summarizes the important concepts and features introduced in this book. In addition, programming style, modular programming, and debugging are explained briefly. A list of recommended C books is provided for further reading.

Publishing Notice

Due to paper and printing constraints, the appendixes for this book have been provided on the CD-ROM rather than in the back of the book as you would expect. When you see a reference to any of the appendixes as you're reading—including the appendix containing the answers for the book's quizzes and exercises—please consult the CD-ROM for them.

Now you're ready to start the journey of learning the C language. Have fun reading this book!

Tony Zhang
Plano, Texas
May 1997

Table of Contents | Next