[go: up one dir, main page]

0% found this document useful (0 votes)
197 views202 pages

Learn C in Three Days

Learn c program in three days, by daily practices

Uploaded by

HARISH S ECE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
197 views202 pages

Learn C in Three Days

Learn c program in three days, by daily practices

Uploaded by

HARISH S ECE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 202
eA A GaGa UC A MLL ES By n nr Learn C in Three Days Sam A. Abolrous BPB PUBLICATIONS B-14, CONNAUGHT PLACE, NEW DELHI-110001 FIRST INDIAN EDITION-1993 Distributors: BPB BOOK CENTRE 376, Old Lajpat Rai Market, Delhi-110006 BUSINESS PROMOTION BUREAU 8/1, Ritchie Street, Mount Road, Madras-600002 BUSINESS PROMOTION BUREAU 4-3-268-C, Giriraj Lane, Bank Street, Hyderabad-500195 COMPUTER BOOK CENTRE 12, Shrungar Complex, M. G. Road, Bangalore-5600014 COMPUTER BOOK CENTRE Kothi No.—535, Sector-7, Panchkula-134109, CHANDIGARH Copyright © Wordware Publishing, Inc., USA The examples and programs contained in this book are compatible with the ANSI standard, Microsoft C, Quick C, Turbo C++, Power C and many others. The programs in this book were compiled using Turbo C++ and tested for compatibility on Quick C and Power C. Microsoft C and Quick C are trademarks of Microsoft Corporatios. Turbo C and Turbo C++ are trademarks of Borland Intemational. Power C is a trademark of Mix Software, Inc. Other product names mentioned are used for identification purposes only and may be trademarks of their respective companies. Printed in India under arrangement with WORDWARE PUBLISHING INC., USA No part of ihis book may be repioduced in any form or by any means without permission in writing from Wordware Publishing, Inc. ISBN 81-7029-170-4 Published hy Manish Jain for BPB Publications, B-14, Connaught Place, New Delhi and Printed by XPRESS GRAFICS, Dalhi-28 Chapter One — Your First Tour of C 1-1 1-2 1-3 1-4 1-5 1-6 1-7 Summary Chapter Two — Input and Output. 2-1 2-2 2-3 2-4 Contents DAY ONE The C Program Displaying Text . . Crunching Numbers ae Using Variables ....... Declaring Variables . . Assignment Drill1-1........ Multiple Assignment . Formatted Output Drill1-2........- The Single Character Variable ... . Text Strings and Pointers ....... Declaring Pointers ....... Initialization of Character Pointers . Examining Memory Locations . Drill 1-3 2. ee ee Formatted Input... ......... Multiple Variables Per Statement Mixed Types of Variables . . . . Input Separators The User Prompt . . . Drill2-1 0 ee eee A Closer Look at Text Strings .............2- Declaration of a Character Array Unformatted String Input The Function gets . . The Function fgets . Drill2-2....... Unformatted String Output The Function puts. . The Function fputs ................. 2-5 CharacterInput ...............0.004 The Function getchar....... . The Functions getch, and getche . oe Drill 2-3 eee 2-6 Character Output ..............2.-2. The Function putchar The Function pute Summary «1... 0... eee ee ee Chapter Three — Putting Things Together... .... . 3-1 Literals 2.2... 2. ee ee ee eee Drill3-1.... 3-2 Basic Data Types . . 3-3. Type Conversion The Range Problem. . . The Type Casts ... . Drill3-2........ 3-4 The Precision of Results . . 3-5 Data Type Modifiers .... 3-6 Output Format........ Format Modifiers . . . Drill3-3........ The Backslash Codes . 3-7 Input Format ............ 0.0 -0000- 3-8 Constants 2.2... ee ee ee ee Summary 6 6. ee DAY TWO Chapter Four — All About C Operators ......... 4-1 Expressions and Operators ............-- 4-2 Arithmetic Operators ......... Modulo Division Operator Increment and Decrement Operators . . . Drill 4-10... . 66 eee eee Precedence of Arithmetic Operators . . . 4-3 Relational and Logical Operators. .......... Evalyation of Logical Expressions ...... . Precedence of Relational and Logical Operators . . . 4-4 Assignment Operators ©... . 0.0.0.0 eee 4-5 Pointer Operators... 2-1... ee eee eee Drill 4-2 2. ee ee ee 4-6 Special Operators . . oe os The ? Operator ..... The Comma Operator . . The sizeof Operator . . . 4-7 Bitwise Operators... ......005 eae tee The Right Shift Operator oe we The Left Shift Operator... ..........00.% Precedence of Bitwise Operators. .......... 4-8 Precedence fo C Operators oe Summary 2... ee eee Chapter Five— Decisions ..............-2005- 5-1 Making Decisions 5-2 The Simple if Statement 5-3. The Complete if-else Structure Drill5-1......... 5-4 Nesting Conditions . 5-5 The if-else-if Ladder Drill 5-2... . 5-6 The goto Statement ...... 5-7 Tipson UserInput ...... Pitfalls of Character Input Numeric Input as a String 5-8 The switch Construct Drill 5-3... . : oe oe see Summary... ee eee - Chapter Six— Loops... 1.2... 0.0002 cece eee 6-1 Looping... 2.2... ee eee 6-2 TheforLoop ........... 00.000 eeeeeee The Loop Block Infinite Loops . 6-3 The while Loop . . The Factorial of aNumber . . . Drill6-1..........00.8 The Power Operator. . 6-4 The do-while Loop . Drill 6-2... 6-5 Nesting of Loops . . . oan wee Drill 6-3 6. ee ee 6-6 Thebreak...............-, rs 90 6-7 Loopsand Arrays... 6. ee ee 91 Summary 6... ee ee 96 Chapter Seven — Functions and Macros. 7-1 The C Program Structure... ..... Prototyping of Functions . The return of a Function . The Function Definition Example: A User Menu Function Example: The Factorial Function Drill 7-12.02... 0000005 7-2 Passing Variables to Functions oan The Scope of a Variable... . . . Example: The “Swap” Function . Drill 7-22... 00.0.0 20008 7-3. Function Recursion 7-4 The Duration of a Variable ..........-.% 7-5 Storage Classes ........ Register Variables . External Variables . 7-6 Macros ....... Drill 7-3... . 7-1 Header Files...... 7-8 The “Project” Files Example: The Secret-Letter Game Summary «6. ee DAY THREE Chapter Eight — Data Structures 8-1 DataArchitecture...... 8-2. AFinal Tour of Arrays .. . Initialization of Arrays Arrays and Pointers . . Memory Allocation . . os see cae Pointer Arrays 2... 0 ee ee Passing ArraystoFunctions .........-.-.4% 123 Drill8-1.......... fee eee eee 125 vi 8-3 Structures ©... eee 125 Structure Templates and Variables 126 Accessing Members 127 Example: Employee Record . . 128 Structure Initialization - 130 Pointers to Structures 131 Structure Arrays and Databases . 133 8-4 Enumerations ....... 0.00.00. 0 eee eee 8-5 Defining Your Own Types. « Summary 2... ee ee Chapter Nine — Miscellaneous Tools .............. 139 9-1 Tools to Manipulate Strings... .. . . 139 The Length of a String strien . . oe -.. 139 String Conoatenation streat.............. 140 Copying Strings and Substrings strepy, strncpy . . . 142 Comparing Two Strings stremp ........... 143 Changing the Case strupr, strliwr .......... 144 String Segmentation strehr.............. 144 Changing the Case of a Character tolower, foupper . 145 Drill 9-1. oe . 146 9-2 Conversion Functions atol- Htoa . 146 9-3 Character Testing Tools isascii- -isxdigit wee 148 Drill 9-2 2. ee eee . 151 9-4 Executing DOS Commands system wee. 151 Summary 2... ee ee 152 Chapter Ten — Files and Applications ............. 153 10-1 DataFilesinC ............ » 153 Sequential and Random Access . . 153 Data Input Output . . 153 Access Functions . . :.. ++. 154 Files, Streams, and Physical Devices... ....46. 154 10-2 The File Protocol fopen, fclose 10-3. ASCII and Binary Files... ..... 10-4 File Input and Output sae Writing a Character toa Filepute .......... Writing a String to a File fputs, fprintf Reading Characters from a File gete . . tte Reading a String fom a File fgets .......... vii 10-5 Application 1: A Telephone Directory ........... 162 Drill 10-1 2... ee eee ee eee 166 10-6 Sending the Output to the Printer. . . . ae .. 166 Drill 10-2... 2... ee eee . 167 10-7 Filing Numbers as Strings sprintf . . . - 167 10-8 Application 2: Payroll . oe - - 168 Summary 2... ee ee ee ee 171 Appendix A The ASCII CharacterSet .............. 175 Appendix B The Prototypes of Functions Discussed in This Book Index ww we ee eee oe viii Preface “Is it possible to Learn C in three days?” The answer is YES. Without too much hassle with types of identifiers, pointers, and constants, this book will take you to the heart of the C programming language through step-by-step examples, giving you experience in C in a small amount of time. You start with simple programs which crunch some numbers and print some strings, and you end up with useful applications of data structures and files. The examples contained in this book are carefully chosen to show you the pitfalls that you may face in creating your own programs. The second question is: “Which C am I going to lear ,?” You know that there are many dialects of C around, such as Turbo C, Quick C, Power C, and the extensions of C++, and so forth. The original C language was introduced by Brian Kernighan and Dennis Ritchie (K&R) in their book The C Programming. Language (Prentice-Hall, 1978), then the proposed ANSI standard introduced an expanded version of the language. The different versions of the languages are nonportable in some areas (such as graphics), but you can still write a portable program that compiles and runs using any compiler. This is the main feature of this book. Whatever compiler you use, the programs will still compile and run. Sam A. Abolrous DAY ONE Chapter One YOUR FIRST TOUR OF C 1-1 THE C PROGRAM In order to see what the structure of a C program looks like, it is best to start with a simple program. Figure 1-1 shows a program that displays on the screen the message “Hi there.” J+ Figure 1-1 ¢/ #include main() printf ("Bi there"); , The heart of this program is the function printf, which actually does the work here. As a matter of fact, the C language is built from functions (like printf) that execute different tasks. The function(s), however, must be used inside a framework which starts with the word main(), followed by the block containing the function(s) which is marked by the braces ({ }). The first line starting with the characters /* and ending with the characters */ is a comment. You may type as many lines as you wish between these two sets of characters and the compiler will ignore them as being comments. Comments can appear anywhere in the program. The second line that starts with #include is called a directive. It is not a part of the actual program. It is used as a command to the compiler to direct the translation of the program. There are other directives which must be used according to the type of functions used in the main block, but this specific directive appears in all programs as it refers to the standard input output header file (stdio.h). Many compilers may compile this simple program successfully without the directive, but it is a good habit to include this directive at the beginning of any C Chapter One program. When using more than one directive each must appear on a single line. - Blank lines and spaces inside the program are optional except the blank space following the directives and similar keywords. The function printf is embedded into a statement whose ending is marked by the semicolon (;). This is important syntax of the C program because the semicolon tells the compiler that a statement Is finished. As is clear from Figure 1-1, all C programs are written in lowercase letters. 1-2 DISPLAYING TEXT The printf is the most important function used to display text on the screen. Like any function it has two parentheses, between which comes the string to be displayed, enclosed in quotations. Look at the output of the program shown in Figure 1-2. It uses two successive statements using the printf function. NOTE . A companion diskette comes along with this book to help you save time and effort. This diskette contains the source code of all the examples, in addition to the solutions to the drills. You can either compile them directly or use them for comparison and error checking. Please read the “readme” file on the distribution disk. Just type the command README and press Enter. }* Figure 1-2 */ include main() printf("#i there"); printf (*Bov are you today?"); ) : If you compile this program and run it, the displayed output is: AL thereBov are you today? Just like that. In order to have the output displayed on two separate lines you must add the new-line character (\n) at the end of the first string, as shcwn in Figure 1-3. Your First Tour of C /* Figure 1-3 */ #include aain() { printf ("Bi there\n"); printf ("How are you today?*); } Now the output is: EL there How are you today? It is clear that the new-line character (\n) comes right after the string and must be inside the quotation marks. Each \n corresponds to a new line, so you can skip another line by using \n\n at the end of the first string. Actually, any spaces or characters written between the quotations, unless they have a special meaning, will be displayed as a past of the text. Figure 1-4 demonstrates how to join two strings with | a blank space between them. dt Figure 1-4 #/ finclude nain() printf("Bi there, "); printf("how are you today?"); } The output of this program is: Hi there, how are you today? This way you can design a label for yourself, by writing a small program like the one shown in Figure 1-5. (+ Figure 1-5 ¢/ Finclude main() 1 { printf (*WORDWARE PUSLISBING, INC.’ SS w printf("PLANO, TEXAS woniin")y ) This program displays on the screen the following text: WORDWARE PUBLISHING, 19. . 1506 CAPITAL AVEMUE PLAWO, TEXAS 75074 More about the printf function later. Chapter One 1-3 CRUNCHING NUMBERS When dealing with numbers you have to pay attention to the type of each number, whether float, integer, etc. Each type has to be used with the printf function in a specific format. The example in Figure 1-6 displays the two numbers 128 and 128.0. The first is of the type int while the second is of the type float. Notice two new characters inside the quotation marks, %d (which stands for “decimal”), and. Jf (which stands for “float”). The number itself appears outside the quotation marks, preceded by a comma. (+ Figure 1-6 ” #include aain() ‘ printf (*td\n", 128); ; printé(*#f\n", 128.0); The characters %d and %f are called conversion specifiers. In this program, they are used to tell the compiler about the types of numbers appearing in the program, which in turn determine the suitable memory storage locations. They are referred to also as format characters or format specifiers. They have other properties that are discussed later. Executing this program displays the following: 128 128.000000 What if you used the wrong conversion specifiers? Try that by swapping the %d and the %f as shown in Figure 1-7. /* Figure 1-7 / Finelude aain() printf(“8f\n",128); printf ("td\n",128.0}; } The output from this program is: 0.090000 0 Wrong results! Some compilers, however, will give unpredictable results by dumping some garbage numbers in the output. Your First Tour of C The printf can also handle mathematical expressions which are evaluated and displayed. Figure 1-8 shows an example of such simple mathematical expressions. The first one (128*2) is multiplication, and the second (128.0/2) is division. (+ Pigure 1-8 ¢/ #include main() ‘ printf("td\n",12802); printf ("sf\n",128.0/2); } The output from this program is: 256 64,000000 Did you notice that we used the integer 2 in the division? It is possible to use mixed types and still get a float output, but it is recommended to use the same type of numbers in the expression. 1-4 USING VARIABLES Variables are actually memory locations, but programmers refer to them by names because it is easier than referring to them by addresses. In C, there are not as many restrictions on naming variables as with other languages. Some names are reserved for the compiler (such as int and main) because they have special meanings. The user-invented names of the variables are called identifiers. They may be composed of letters (a-z or A-Z), digits (0-9), or underscores (_), with the first character being a letter or an underscore. A good feature of the C identifiers is that they may be very long, which allows for descriptive names like: The_total_number_of_cars_sold_year_to_date ‘The_total_direct_cost_for_12_months_budget_period If the identifier is longer than 32 characters, only the first 32 characters are significant. While both uppercase and lowercase letters are accepted as identifiers, they are not equivalent. In other words, the variable “PRICE” is not the same as the variable “price.” Chapter One DECLARING VARIABLES The most important restriction on using variables is that they have to be declared at the beginning of the program. For example: /* Pigure 1-9 */ Finclude nain() { /* Declarations */ int a; float b; /* Display output */ printf(*sd\n*,a); printf(*#f\n",b); } As you can see in Figure 1-9, the declarations come at the beginning. Two variables are declared, “a” as an integer, and “b” as a float. The next part of the program displays the values stored in the variables using the suitable conversion specifiers. No values are really stored in the variables so far, so you should expect the output to be something like: 7212 0.000000 The first value is nothing but what was there in the memory location. In other words, variables which are not initialized or assigned values may contain garbage. ASSIGNMENT In the next step we assign values to these variables. See Figure 1-10. /* Hgure 1-10 */ #include main() { /* Declarations */ int a; float b; /* Assignment */ a=1024; be512; /* Display output */ printé("td\n",a); printe(*sf\n",b); Now the program contains one more part, where the value 1024 is assigned to the variable “a,” and the value 512 is assigned to the variable “b.” Your First Tour of C This program gives the result: 1024 512.000000 You also can assign variables (or expressions containing variables) to other variables as in the following example, Figure 1-11. /* Figure 1-11 */ Hinclude main() { /* Declarations */ int a; float b,c; /* Notice multiple declaration */ /* Aspignnents */ a 1024; b= a/2.0; ce bray /* Display output */ print£(*the result © ¢f\n",c); } The output of this program is: The result = 1536.000000 Here the expression “a/2.0” is assigned to the variable “b,” then the sum of “a” and “b” is assigned to the variable “c.” Finally, the result stored in “c” is displayed preceded by a suitable text string. You must have noticed in Figure 1-10 that an integer value (512) was assigned to a float variable, and the result was a correct float number (512.000000); however, the opposite will lead to truncation of the fraction part, if any. The following example demonstrates this truncation when dividing 8 by 3. See Figure 1-12. J+ Figure 1-12 +/ #include main() { /* Declarations */ be 0/3; /* Display output */ printf("td\n",b); The output is: 2 Chapter One DRILL 1-1 The following three examples are different trials to display the value of the fraction “3/4”; only the last one is correct. Try them all to see the different responses of the compiler to errors. C compilers are different in responses. Some of them may compile the program without any error messages but result in an erroneous output. J* Figure 1-13 #/ include main() printé("td\n",3/4); ) /* Pigure 1-14 */ Hnclude main() printg("#f\n",3/4); } J+ Figure 1-15 #/ Hinclude main() printt(*st\n",3.0/4.0); MULTIPLE ASSIGNMENT Multiple assignment is possible in C. You can, for instance, assign the value 24 to more than one variable x, y, and z using one statement as follows: xeyere 2; Another shortcut is to declare a variable and assign it a value in one statement like: int price of_unit=99; float radius=3.65; This is called variable initialization. The following example demonstrates these shortcuts, as well as multiple display of all the variables using one printf function: 10. Your First Tour of C © Figure 1-16 */ #include main() { int a,b,c; float 303.4; aeb=c=24; printf(*a=td,\nb=8d,\nc=td, and\nx=tf\n",a,b,c,x); } The output of the program is: and, be24, e=24, and x=3.400000 TIP It is well known that, when locating syntax errors, many C compilers always “talk about something else!” Try to remove a semicolon or a single comment character from a program, and compile it. Only rarely does the error message tell you about the missing character, but it may tell you instead about everything else in the world. With such a feature, you have to be careful when writing your statements. This is much easier than trying to figure out afterwards what the mistake was. 1-5 FORMATTED OUTPUT The function printf is called “The print formatted output function,” because it enables the programmer to format the output using either strings that appear in the output, or format characters such as %d and %f. You may wish to see the number 75.000000 displayed in a more manageable form like 75 or 75.00. This is done by using modifiers along with the format characters in order to specify the required field width. The format % .0f will suppress all the zeros to the right of the decimal point, while the format %.2£ will keep two zeros only, and so forth. Let us look at some examples in Figure 1-17. © Figure 1-17 ¢/ #include aain() { float x; 375; printf (“s.0f\n",x); Chapter One printf ("t.1f\n",x); printf (*\.2E\n",x); ) The output is: 5 15.0 15.00 The value of “x” is displayed three times in three different formats: the first one without any decimal places, the second with one decimal place, and the third with two decimal places. What if there is a number containing fractions? The number will be rounded to the required number of decimal places, as stated in the format. The following example shows different approximations of the number “0.75”: 7+ Figure 1-18 */ #include main() printt("s.0f\n",3.0/4.0); print¢("s.1f\n",3.0/4.0); printf("s.2¢\n",3.0/4.0); The output is: 1 0.8 0.75 DRILL 1-2 Write a program to assign the number 3.45678 to a variable named “number,” then display two outputs: 1- The “number” rounded to the nearest integer value. 2- The “number” rounded to tvo decimal places. Display each output on a separate line, preceded by the suitable text. 1-6 THE SINGLE CHARACTER VARIABLE The third type of variable, in addition to int and float, is the char variable that can only hold a single character. Any data character can be stored in a char variable, including unprintable characters. 12 Your First Tour of C Character variables are declared using the char keyword. For example; to declare a variable “b” of the type char write the statement: char b; To assign a character to this variable, it must be enclosed in single quotes: ben; It is now time to introduce the conversion specifier %c (which stands for “character”), which is used with char type variables. In the following example you declare the variable “first_letter,” assign it a value “A,” then display its contents using the %c conversion specifier. /* Pigure 1-19 */ #include pain() { char firet_letter; firat_letter=’A"; printf (*tc\n",first_letter); , The output is: a If you use the conversion specifier %d to display the contents of the variable “first_letter” instead, you get the ASCII value of the character instead of the character itself (see the ASCII codes in appendix A). Now add one more line to the program as follows in Figure 1-20: J+ Figure 1-20 */ #include aain() { char first_letter; tirat_letter=/A"; printf(*tc\n*,first_letter); /* display the character */ printt("sd\n",firet_letter); /* display the ASCII of the character */ } The output is: a 65 This program makes clear the meaning of the name “conversion specifiers.” As you can see, they are used to convert the type of the output data. Without using any variables you can just write the statement: print£("tc\n",65); which gives the output “A.” 13 Chapter One You can also write the statement: printt("sd\o",‘a"); which gives the output “65.” 1-7 TEXT STRINGS AND POINTERS Strings in C are handled differently than in any other language. When a text string is stored in the memory, you keep track of the first character by storing its address in a special type of variable called a pointer. Knowing the beginning address and the length of the string, the program can locate it. This means that a pointer is a variable containing an address of another variable (rather than data). Pointers play a very important role in C, and they can point to any type of data. DECLARING POINTERS The pointer is declared using the indirection operator (*). For example, if a pointer “a” is pointing to an integer, it is declared as: int *a; If “a” is a pointer to a character, it is declared as: char *ay INITIALIZATION OF CHARACTER POINTERS In the following example, a character pointer “a” is used to point to the location of the first character in the string “Hello again.” Then the value of “a” is displayed using the new conversion specifier Ys (which stands for “string”), which is of course used with strings. + Pigure 1-21 */ #include aain() { char *a; as"Hello printf (*W , The output is: Hello again. In this example “a” is a pointer to a char, while “*a” is the data being Pointed to, which is actually the first letter in the string (H). 14 Your First Tour of C The example in Figure 1-22 demonstrates handling two strings using pointers: (* Pigure 1-22 #/ #include main() { char ¢a,*b; ae"Hi, I am the string pointed to by the pointer a.*; be"Hello, 1 am the string pointed to by the pointer b. *; printf("ts\nts\o",a,b); } The output is: Bi, I am the string pointed to by the pointer a. Bello, I am the string pointed to by the pointer b. EXAMINING MEMORY LOCATIONS In order to make sure that you understand the meaning of the pointer, examine the output of the program in Figure 1-23. This program points to the string “Hello again” with the pointer “a.” Then, using the proper conversion specifier, you can examine the addresses and contents of variables. A new conversion.specifier %p is introduced in the program, which is used to convert the output to hexadecimal numbers. J+ Pigure 1-23 */ #include main() { print£(*ta\n' print£(*tc\n' print #(*sd\n' print#(*\p\n",a); printé("td\n",¢a); The output of this program is: Hello again a 168 ong n The first printf statement displays the string itself by the use of the conversion specifier %s. The second one displays the character pointed to by the pointer, using the conversion specifier %c. The third and the fourth printf statements display the address contained in the pointer in decimal and hexadecimal respectively, using the conversion specifiers %d and %p. The last printf statement displays the ASCII of the first character in the string (72 is the ASCII of the letter H). 15

You might also like