Tải bản đầy đủ (.pdf) (550 trang)

IT training c in depth (2nd ed ) srivastava 2009 06 30

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (23.72 MB, 550 trang )


"

Preface to Second Edition
The first edition of this book was appreciated by the students for its simplicity. The ~.'lr_~ ""~-'-'
maintains this feature along with inclusion of new tOfics and errors of previous edition
d pnlg:J~s.
Every topic has been explained in depth without compromising over the lucidity of the tex
This approach makes this book suitable for both novices and advanced programmers.
Developl)1ent of logic and familiarity with the syntax and features of the language are the two p - of excellent programming skills. The comprehensive contents of the chapters along with the num
example programs helps you to develop your logic in a stepwise manner and makes you feel comfo
with the syntax of the language. Remember that you can't learn swimming by just reading a book
how to swim, you have to jump into water for that, similarly if you want to learn programming, .
is essential for you to make your own programs. So start by understanding the programs given in the
book, work on them, modify them and see the results and try to make similar programs.
Each chapter is complemented by exercises with solutions that act as a review of the chapter. We strongly
recommend that you solve all the exercises before switching over to another topic. Exercises have been
structured in such a way that you can test and implement the knowledge acquired from the chapter,
and this is really important for getting full hold over a topic. We're sure if you understand the concepts,
you'll enjoy doing the exercises.
Our aim of writing this book is to, enable any student emerge as a full-fledged C programmer who can
withstand the challenges of the industry. This is the reason for inclusion of chapters on project building,
'"
library development and code optimization.
We are thankful to our family and friends for their love and support.
If you have any problems or

sugg~stions,

please feel free to contact us at-




Suresh Kumar Srivastava
Deepali Srivastava


C

in Depth

Preface to First Edition
Hello ! I am Suresh Kumar Srivastava. Firstly I want to tell you how the idea of writing a book on
'C' language came to my mind. When I was in 1st semester of 'B Level', C language was in my course.
I didn't know anything about computers. So at that time learning of 'C' language was very difficult
for me. I faced a lot of problems. After thorough studies o(many standard and authentic books in
'C', it became convenient for me to work in 'C'. Presently I am in a position to say that that I have
in-depth knowledge of 'c' and find myself in a position to help my juniors in making them comfortable
with 'C'. This idea inspired me to write a book which is easily understandable by beginners and contains
all theoretical concepts and their implementation in programming.
v

I was alone in this work. I was the initiator, visualizer and accomplisher for this work.
I am very thankful to my elder brother_ Raju Bhaiya and sister Reena didi for their love and care for
me and my work. I am thankful to g1y friend Sh-'lilesh Raghuvanshi for proof reading of my book.
Anil Tyagi of BPB Publications for considering my work.
I am also thankful to Mr. Manish Jain and

Mr.

Suresh Kumar Srivastava



C in Deptl;

vi

Contents
1.:6

1. Introduction to C
1.1

1.2

1.3
1.4
1.5
1.6
1.7

Design Methods
1.1.1
Top-Down Design
1.1.2 Bottom-Up Design
1.1.3
Modular Approach
Programming Languages
1.2.1
Low Level Languages
1.2.1.1

Machine Level Language
1.2.1.2
Assembly Language
1.2.2 High-Level Languages
Translators
History Of C
Characteristics Of C
Structure Of A C Program
Environment For C
1.7.1
Unix Environment
1.7.2 MS-DOS Environment
1.7.2.1
Command Line
1.7.2.2
Integrated Development Environment

2. Elements of C
2.1
C Character Set
2.1.1
Alphabets
2.1.2
Digits
2.1.3
Special characters
2.2 Execution Characters/Escape Sequences
2.3 Trigraph Characters
2.4 Delimiters
2.5 Reserved Words / Keywords

2.6 Identifiers
2.7 Data Types
2.8 Constants
2.8.1
Numeric Constants
2.8.1.1· Integer constant
2.8.1.2
Real ( floating point) Constants
2.8.2 Character Constants
2.8.3
String Constants

1
1
2
2
2
2'
2
2
3
3
3
4
4

5
5
5
5


'"

6

7-16
7
7
7
7
8
8
9
9
9
10
10
11
11
12
13
13



-----.
C in Depth
4.12 Type Conversion
4.12.1 Implicit Type Conversions
4.12.2 Automatic Conversions

4.12.3 Type Conversion In Assignment
4.12.4 Explicit Type Conversion Or Type Casting
4.13 Precedence And Associativity Of Operators
4.14 Role Of Parentheses In Evaluating Expressions
4.15 Order Of Evaluation Of Operands
Exercise
Programming Exercise
Answers

5. Control Statements
5.1
5.2

Compound Statement' or Block
if...else
5.2.1
Nesting ofif...else'
5.2.2 else if Ladder
5.3 Loops
5.3.1
while loop
5.3.2 do...while loop
5.3.3 for loop
5.3.4 Nesting Of Loops
5.3.5 Infinite Loops
5.4 break statement
5.5 continue statement
5.6 goto
5.7 switch
5.8 Some Additional Problems

5.9 Pyramids
Exercise
Programming Exercise
Answers

6. Functions
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9

Advantages Of Using Functions
Library Functions
User-Defined Functions'
Fu.nction Definition
Function Call
Function Declaration
return statement
Function Arguments
Types Of Functions
6.9.1
Functions With No Arguments And No Return Value6.9.2
Function With No Arguments But A Return Value
6.9,3
Function With Arguments But No Return Value


44
44
44
45
46

47
50
53
53
56
56

58-109
58
59

6\
63
65
65
69
71
75
77

78
80
82

84

9Q
99
103
108
109

110-157
110
110

III
112
113
114
116
118
120
120
121
121


~

i;..

r


-

ix

C in Depth

123
124
124
125
125
125
126
126
126
130
130
131
132
132
136
139
139
140
149
155
·156

6.9.4 Function With Arguments And Return Value
More About Function Declaration

Declaration Of Functions With No Arguments
If Declaration Is Absent
Order Of Evaluation Of Function Arguments
main() Function
Library Functions
Old Style Of Function Declaration
Old Style Of Function Definition
Local, Global And Static Variables
6.18.1 Local Variables
6.18.2 Global Variables
6.18.3 Static Variables
6.19 Recursion
6.19.1 Tower Of Hanoi
6.19.2 Advantages And Disadvantages Of Recursion
6.19.3 Local Variables In Recursion
6.20 Some Additional Problems
Exercise
Programming Exercise
Answers

6.10
6.11
6.12
6.13
6.14
6.15
6.16
6.17
6.18


7. Arrays

158-195'

7.1

One Dimensional Array
7.1. 1 Declaration of 1-D Array
7: 1.2 Accessing I-D Array Elements
7.1.3
Processing 1-D Arrays
7.1.4 Initialization of I-D Array
7.1.5
I-D Arrays And Functions
7.1.5.1
Passing Individual Array Elements to a Function
7.1.5.2 Passing whole 1-D Array to a Function.
7.2 Two Dimensional Array
7.2.1
Declaration and Accessing Individual Elements of a 2-D array
7.2.2 Processing 2-D Arrays
7.2.3
Initialization of 2-D Arrays
7.3 Arrays With More Than Two Dimensions
7.3.1
Multidimensional Array And Functions
7.4 Introduction To Strings
7.4.1
Input and output of strings
7.5 Some Additional Problems

Exercise
Programming Exercise
Answers

8. Pointers
8.1

158
158
159
160
«.162
165
165
165
167
167
168
169
173
174
175
175
175
191
193
194

196-252


About Memory

1%

;


C in Depth

x

8.2
8.3

Address Operator
Pointers Variables
8.3.1 Declaration Of Pointer Variables
8.3.2 Assigning Address To Pointer Variables
8.3.3 Dereferencing Pointer Variables
8.4 Pointer Arithmetic
8.5 Precedence Of Dereferencing Operator And Increment/Decrement Operators
8.6 Pointer Comp.arisons \
,
8.7 Pointer To Pointer
8.8 Pointers and One Dimensional Arrays
8.9 Subscripting Pointer Variables
8.10 :Rpinter to an Array
8.11 PbintersAnd Two Dimensional Arrays
8.12 Subscripting Pointer To An Array
8.13 Pointers And Three Dimensional Arrays

8.14 Pointers And Functions
8.15 Returning More Than One Value From A Function
8.16, Function Returning Pointer
8.17 Passing a 1-D Array to a Function
8.18 Passing a 2-D Array to a Function
8.19 Array Of Pointers
. 8.20 void Pointers
8.21 Dynamic Memory Allocation
8.21.1 malloc()
8.21.2 calloc()
8.21.3 realloc()
8.21.4 free()
8.21.5 Dynamic Arrays
8.22 Pointers To Functions
8.22.1 Dedaring A Pointer To A Function
8.22.2 Calling A Function Through Function Pointer
8.22.3 Passing a Function's Address as an Argument to Other Function
8.22.4 Using Arrays Of Function Pointers
Exercise
Answers
\

9. Strings
\
9.1 String Constant or String Literal
9.2 String Variables
9.3 String Library Functidns
strlen()
, 9.3.1
9.3.2 strcmp()

9.3.3 st{'cpy()
9.3.4 strcat()
9.4 String Pointers
9.5 Array Of Strings Or Two Dimensional Array Of Characters

1,.,.'

197
197
198
198
199
201
204
206
206
208
211
212
213
216
·217
219
221
222
223'
225
227
229
231


131
233
233
234
235
238
239
240
240
242
244
251

253-287
253
255
257
25 7
258
259
, /261
262
264
1


C in D?[Jth

267


9.6 Array Of Pointers To Strings
9.7 sprintf()
9.8 sscanf()
9.9 Some Additional Problems
Exercise
Programming Exercise'
Answers

10. Structure And Union
10.1
10.2

3
~

o
o
2
4
1

:7
53

55
57
5,7
58
59


61

.62
~64

Defining a Structure
Declaring Structure Variables
10.2.1
With Structure Definition
10.2.2
Using Structure Tag
Initialization Of Structure Variables
10.3
Accessing Member:s of a Structure
10.4
Assignment of Structure Variables
10.5
Storage of Structures in Memory
10.6
10.7
Size of Structure
10.8
Array of Structures
Arrays Within Structures
10.9
10.10 Nested Structures (Structure Within Structure)
10.11 Pointers to Structures
10.12 Pointers Within Structures
10.13 Structures And Functions

10. 13. 1 Passing Structure Members As Arguments
10.13.2 Passing Structure Variable As Argument
10.13.3 Passing Pointers To Structures As Arguments
10.13.4 Returning A Structure Variable From Function
10.13.5 Returning A Pointer To Structure From A Function
10.13.6 Passing Array Of Structures As Argument
10.14 Self Referential Structures
10.15 Linked List
10.15.1 Traversing a Linked List
10.15.2 Searching in a Linked List
10.15.3 Insertion into a Linked List
10.15.4 Insertion in the Beginning
10.15.5 Insertion in Between or at the end
10.15.6 Deletion From A Linked List
10.15.7 Deletion of First Node
10.15.8 Deletion of a Node in Between or at the End
10.15.9 Creation Of List
10.15. 10 Reversing A Linked List
10.16 union
10.17 typedef
Exercise
Programming Exercise
Answers

272

273
274
280


284
286

288-333'
288
289
289
289
290
290
292
292
293
293
295
296
298
299
299
299
300
301
302
303
303
309
309
311
311
311

312
312
313
313
<,

314
314
318·
321
326
329
332

332


C in Depth

11. Files
Text And Binary Modes
Concept Of BufTer
Opening a File
11.3.1
Errors in Opening Files
11.4
Closing a File
End of File
11.5
Structure of a General File Program

11.6
Predefined File Pointers
11.7
Character I/O
11.8
fputc ( )
11.8.1
fgetc()
11.8.2
11.8.3
getc( ) and putc( )
Integer i/o
11.9
11.9.1
putw ( )
getw()
11.9.2
11.1 0 String I/O
11.10.1 fputs()
11.1 0.2 fgets()
11.11
Formatted I/O
11.11.1
fprintf ( )
11.11.2 fscanf ( )
11.12 Block Read / Write
11.12.1 fwrite()
11.12.2 fread()
11.13 Random Access To File
'11.13.1 . fseek ( )

11.13.2 ftelI()
11.13.3 rewind()
11.14 Other File Functions
11.14.1 feof()
11.14.'2 ferror()
11.14.3 c1earerr()
11.14.4 perror()
11.14.5 rename()
11.14.6 unlink()
11.14.7 remove()
11.14.8 fflush()
11.14.9 tmpfile()
11.14.10 tmpnam( )
11.14.11 freopen()
11.15 Conmland Line Arguments
11.16 Some Additional Problems
Exercise
Programming Exercise
Answers
11".1
11.2
11.3

334-376
334
335
335
337
337
338

338
339
339
339
340
340
341
341
341
342
342
342
343
343
344
345
345
347
348
349
.. 350
351
362
362
363
364
364
364
365
365

366
366
366
367
367
368
374
375
376


xiii

C in Depth

12. The C Preprocessor
12.1
12.2
12.3
12.4
12.5
12.6
12.7
12.8
12.9
12.10
12.11

#define
Macros with Arguments

Nesting in Macros
Problems with Macros
Macros Vs Functions
Generic Functions
#undef
Stringizing Operator ( # )
Token Pasting Operator( ## )
Including Files
Conditional Compilation
12.11.1 #if And #endif
12.11.2 #else and #elif
12.11.3 de.fined Operator
12.11.4 #ifdef arid #ifndef
12.11.5 Writing Portable Code
12.11.6 Debugging
12.11.7 Commenting A Part Of Code
12.11.8 Other Uses of conditional compilation
12.12 PredefiI).ed· Macro Names
12.13 #line
12.14 #error
12.15 Null Directive
12.16 #pragma
12.17 How to see the code expanded by the Preprocessor
Exercise
Answers

13. Operations on Bits
I
l
l

l

5
5
5
6
6
7
7
8
4
5
6

13.1
13.2
13.3
13.4
13.5
13.6
13.7
13.8

Bitwise AND ( & )
Bitwise OR ( I )
Bitwise XOR ( 1\ )
One's Complement ( ~ )
Bitwise Left Shift ( « ) .
Bitwise Right Shift ( » )
Multiplication and Division by 2 using shift operators

Masking
13.8.1
Masking Using Bitwise AND
13.8.2
Masking Using Bitwise OR
13.8.3
Masking Using Bitwise XOR
13.8.4
Switching off Bits Using Bitwise AND and Complement Operator
13.9
Some additional Problems
13.10 Bit Fields
Exercise
Answers

377-406
3 8

~

379
381
382
385
386
387
387
388
389
389

390
390
393
393
395
396
397
397
·398
399
399
400
400
401
401
405

407-432
408
408
409
410
411

411
412
413
413
415
415

416
18
~_6

_9


C ill Depth

14. Miscellaneous Features In C

433-463
433
437
437
439
442
442
443
444
445
445
445
447
449
450
454
456
457
457

457
457
457
458'
463

14.1
14.2

Enumeration
Storage C1as~es
14.2.1
Automatic
14.2.2
External
14.2.3
Static
14.2.3.1 Local Static Variables
14.2.3.2 Global Static Variables
14.2.4
Register
14.3
Storage Classes in Functions
14.4
Linkage
Memory During Program Execution
14.5
14.6
const
14.7

volatile
14.8
Functions With Variable Number Of Arguments
14.8.1
Passing Variable Number of Arguments To Another Function
14.9
lvahie and rvalue
14.10 Compilation And Execution of C Programs
14.10.1 PreprocessoJ;
14.10.2. Compiler
14.10.3 Assembler
14.10.4 Linker
.Exercise
Answers

15. Building project and, creation of library
15.1
15.2
15.3
15.4

Requirement Analysis
Top Level Design
Detail Design
Coding
15.4.1
Dtmanip.h
15.4.2 . Datefmt.c
15.4.3
Valid.c

15.4.4
Leap.c
15.4.5
Julian.c
15.4.6
Weekday.c
15.4.7
Cmpdate.c
15.4.8
Diffymd.c
15.4.9
Diffdays.c
15.4.10 Addyear.c
15.4.11 Subyear.c
15.4.12 Addmonth.c
15.4.13 Submonth.c
15.4.14 Adddays.c
15A15 Subdays.c
15:4.16 Main.c

464-486
~

464
465
465
468
468
469
469

470
470
471
472
472
473
474
474
475
475
476
·477
477


C in Depth
15.5
15.6
15.7

15.8

15.9

5
5
7
9

o


16.1,
16.2
16.3

6

7
;7
i7

i8'

;3

16
54
55
55
58
68
69
69
70
70
71
72
72
73
·74

f74

16.4

16.5
16.6
16.7
16.8
16.9
16.1 0
16.11
16.12
16.13
16.14
16.15
16.16
16.17
16.18
16.19
16.20
16.21

17.1
17.2

~75
~77

P7


Project in Turbo C
Of Library And Using it in your Program in Turbo C
Deletion of a Module From Library
Getting Modules From Library
Changing Version Of Module In Library
Project On Unix
Writing Makefile
Building Project With Make
Of Library And Using In Your Program in Unix

Optimization is a Technique
Optimization With Tool
Optimization With Loop
16.3,1
Loop Unrolling
16.3.2
Avoiding Calculations In Loops
Fast Mathem~tics
16.4.1
Avoid Unnecessary Integer Division
16.4.2
Multiplication And Division by Power Of 2
Simplifying Expressions
,Declare prototypes for Functions
Better Way Of Calling Function
Prefer int to char or short
Use of Register Variables
Opti~ization With Switch Statement
Avoid Pointer Dereference
Prefer Pre Increment/Decrement to Post Increment/Decrement

Prefer Array to Memory Allocation
Use Array Style Code Rather Than Pointer
Expression Order {,Jnderstanding
Declaration Of Local Function
Breaking Loop With Parallel Coding
Trick to use Common Expression
Declaring Local Variables Based On Size
Prefer Integer Comparison
Avoid String Comparison

. C and Assembly Interaction

~75

~76

Building
Testing
Creation
15.7.1
15.7.2
15.7.3
Building
15.8. ~
15.8.2
Creation

16. Code Optimization in C

4

7
7 -

xv

17.3

Inline Assembly Language
Linking Of Two Assembly Files
17.2. 1
Memory Models
17.2.2
C And Segments in Library
Linking Assembly Procedure in C Program

481
48'1
482
482
483
483
483
484
486
486

487-494
487
487
487

487
488
488
488
488
489
489
489
489
490
490
492
... 492 .
492
492
492
493
493
493
494
494
494

495-504
495
498
, 500
500
502



C in Dept!.

18. Library Functions
18.1
Mathematical Functions
18.1.1abs( )
18.1.2
acos()
18.1.3
asin( )
18.1.4
atan()
18.1.5
atan2()
18.1.6
cabs()
18.1.7
ceil( )
18.1.8
cos()
18:1.9
cosh()
18.1.10 exp()
18.1.11 fabs( J
18.1.12 floor()
18.1.13 fmod()
18.1.14 frexpC)
18,1.15 Idexp()
18.1.16 log()

18.1.17 log10()
18.1.18 modf()
18.1.19 pow()
18.1.20 sin()
18.1.21 sinh()
18.1.22 sqrt()
18.1.23 tan()
18.1.24 tanh()
18.2
Character Type Functions
18.2.1 ,isalnum()
18.2.2
isalpha( )
18.2.3
iscntrl( )
18.2.4
,isdigit( )
18.2.5
isgraph( )
18.2.6
islower( )
18.2.7
isprint( )
18.2.8
ispunct( )
18.2.9
isspace( )
18.2.10 isupper()
18.2.11 isxdigit( )
18.2.12 tolower()

18.2.13 toupper()
18.3
String Manipulation Functions
18.3.1
strcat( )
18.3.2
strchr( )
18.3.3
strcmp( )
18.3.4
strcpy()
18.3.5
strcspn()

505-52:
50:
50:
50:
50:
50:
50:
50:
501
501

,SOl

501
501
501

501
501
50'
50'
50'
50'
50'

SO',

'§O'

SO',

50~

50~

501
501
501

SOl

501
501
501
501

SOl

SOl

505
505

505

50S
50S
50S
50S

SIC
SIC
SIC


7th

;21
505
505 .
505
505
505
505
505
506
506
,506

506
506
506
506
506
507
507
507
507
507
507
~07

507
507
507
508
508
508
508
508
508
508 .
508
508

508
509
509
509

509 .
509
509
509
510

510
-10

C in Depth

18.4

18.3.6
strlen()
18.3.7strncat( )
18.3.8
strncmp( )
18.3.9
strncpy( )
18.3.10 strpbrk()
18.3.11 strrchr()
18.3.12 . strspn( )
18.3.13 strstr()
Input/Output Functions
18.4.1
access()
18.4.2
chmod()
18.4.3

clearerr( )
close()
18.4.4
18.4.5
create )
18.4.6
fclose( )
18.4.7
feof()
18.4.8
ferror( )
18.4.9
fflush( )
18.4.10 fgetc()
18.4.11 fgets()
18.4.12 fileno()
18.4.13 fopen()
18.4.14 fprintf()
18.4.15 fplitc()
18.4.16 fputs()
_18.4.17 fread()
18.4.18 fputchar()
18.4.19 fscanf()
18.4.20 fseek()
18.4.21 fstat()
18.4.22 ftell()
18.4.23 isatty()
18.4.24 open()
18.4.25· read()
18.4.26 remove()

18.4.27 rename()
18.4.28 setbuf()
18.4.29 sopen()
18.4.30 stat()
18.4.31 sprintf()
18.4.32 sscanf()
18.4.33 tell()
18.4.34 tmpfile()
18.4.35 tmpnam()
18.4.36 unlink( )

510
510
511
511

512
512
512
512
513
513
513
514
514
514 .
514
514
514
515

-515
515
515
515
515
516

516
.516

516
" 516
SIp
517
517
517
517
518 518
518
518
519

520
. 520
520

520
520
520
521



"
Chapter 1

Introduction to C
oftware is a collection of programs and a program is a collection of instructions given to the computer.
Development of software is a stepwise process. Before developing a software, number of processes
e done. The first step is to understand the user requirements. Problem analysis arises during the
requirement phase of software development. Problem analysis is done for obtaining the user requirements
and to determine the input and output of the program.
'=or solving the problem, an "algorithm" is implemented. Algorithm is a sequence of steps that gives
ethod of solving a problem. This "algoritnm" creates the logic of program. On the basis of this
-algorithm", program code is written. The steps before writing program .code are as~
User requirements

Problem analysis

t
t
Designing algorithm
Input and Output

Program coding
Process of program development'

.1

/
/


/

Design Methods

:Jesigning is the first step for obtaining solution of a given problem. The purpose of designing is ~o
represent the solution for the system. It is really difficult to design a large system because the complexity
system cannot be represented easily. So variqus methods have been evolved for designing.

.1.1
.c:.

~

Top-Down Design

'ery system has several hierarchies of components. The top-level com~onent represents the whole
tern. Top-Down design method starts from top-level component to lowest level (bottom) component.
this design method, the system is divided into some major components.


C ill Depth
Then each major component is divided into lower level components. Similarly other components are
divided till the lowest level component.

1.1.2

Bottom-Up Design

Bottom-Up design method is the reverse of Top-Down approach. It starts from the lowest level component

to the highest-level component. It first designs the basic components and from these basic components
the higher-level components are designed.

1.1.3

Modular Approach

It is better to divide a large system into modules. In terms of programming, module is logically a welldefined part of program. Each module is a separate part of the program. It is easy to modify a program
written with modular approach because changes in one module don't affect other modules of program.
It is also easy to check bugs in the program in module level programming.

1.2

Programming Languages

Before learning any language, it is important to know about the various types of languages and their
features. It is interesting to know what were the basic requirements of the programmers and wha1
difficulties they faced with the existing languages. The programming languages can be classified into
two types1. Low level languages
.
\
2.
HIgh level languages

1.2.1

Low Lev"el Languages

The languages in this category are the Machine level language and Assembly language.


1.2.1.1

Machine Level Language

Computers can understand only digital signals, which are in binary digits i.e. 0 and 1. So the instructiom
given to the computer can be only in binary codes. The machine language consists of instructions thai
are in binary 0 or 1. Computers can understand only machine level language.
Writing a program in machine level language is a difficult task because it is not easy for programmen
to write instructions in binary code. A machine level language program is error-prone and its maintenancE
is very difficult. Furthennore ma.chine language programs are not portable. Every computer has its owr
n'1achine instructions, so the programs written for one computer are not valid for other computers.
1.2~.1.2

Assembly Language

The et~ifficulties faced in machine level language were reduced to some extent by using a modified fom
ofmacL'ine level language called assembly language. In assembly language instructions are given in Englist
like words, such as MOV, ADD, SUB etc. So it is easier to write and understand assembly programs,
Since a computer can understand only machine level language, hence assembly language program musl
be translated into machine language. The translator that is used for Itranslating is called "assembler"
Although writing programs in assembly language is a bit easier, but still the programmer has to knoVl
all the low level details related with the hardware of a computer. In assembly language, data is stored
in computer registers and each computer has different set of r~gisters. Hence the assembly languagE
program is also not portable. Since the low level languages are related with the hardware, hence thE
execution of a low-level program is faster.
.


th


lfe

Introduction to C

1.2.2

3

High-Level Languages

ent
nts

High-level languages are designed keeping in mind the features of portability i.e. these languages are
machine independent. These are English like languages, so it is easy to write and understand the programs
of high-level language. While programming in a high level languag\e, the programmer is not concerned
with the low level details, and so the whole attention can be paid to the logic of the problem being
solved. For translating a high-level language program into machine language, compiler or interpreter is
used. Every language has its own compiler or interpreter. Some languages in this category are- FORTRAN,
COBOL, BASIC, Pascal etc.

ell-

1.3

~am

am.

heir

That
into

Translators

We know that computers can understand only machine level language, which is in binary 1 or O. It
is difficult to write and maintain programs in machine level language. So the need arises for converting
the code of high-level and low-level languages into machine level language and translators are used for
this purpose. These translators are just computer programs, which accept a program written in high
level or low-level, language and produce an equivalent machine language program as output. The three
types of translators used are•
Assembler

Compiler

Interpreter'
Assembler is used for converting the code oflow-levellanguage (assembly language) into machine level
language.
Compilers and interpreters are used to convert the code of high-level language into machine language.
The high level program is known as source program and the corresponding rn~chine language program
is k~own ~~ obje~t prog~am. Although both complle;s and interPr~ters perform the ;ame task but the~e
is a' differerice in their working.
.

IOns
that

ners
ance
own

ters.

A compiler searches all the errors of program and lists them. If the program is error free then it converts
the code of program i~to machine cod~ and then the program can be executed by separate comlnands.
An interpreter checks the errors of program statement by statement. After checking one statement, it
converts that statement into machine erode and then executes that statement. This process continues
until the last statement of program or an erroneous statement occurs.

1.4

History Of C

In earlier days, every language was designed for some specific purpose. For example FORTRAN (Formula

form
glish
ams.
must
ller".

mow
tored
~uage

e the'

Translator) was used for scientific and mathematical applications, COBOL (Common Business Oriented
Language) was used for business applications. So need of such a language was felt which could withstand
most of the purposes. "Necessity is the mother of invention". From here the first step towards C was
put forward by Dennis Ritchie.

The C lalfguage was developed in 1970's at Bell laboratories by Dennis Ritchie. Initially it was designed
for programming in the operating system called UNIX. After the advent of C, the whole UNIX operating
system was rewritten using it. Now almost tlvc entire UNIX operating system and the tools supplied
with it including the C compiler itself are written in C.
The C language is derived from the B language, which was written by Ken Thompson at AT&T Bell
laboratories. The B language was adopted from a language called BCPL (Basic Combined Programming
Language), which was developed by Martin Richards at Cambridge University.


C in Depth

In 1982 a committee was formed by ANSI (American National Standards Institute) to standardize thl
C language. Finally in 1989, the standard for C language was introduced known as ANSI C. Generall~
most of the modern compilers conform to this standard.

1.5

Characteristics of C

It is a middle level language. It has the simplicity of a high level language as well as the power of ;

I

low level language. This asp;ct of C makes it suitabl~ for writing both application' programs and systen
programs. Hence it is an excellent, efficient and general-purpose language for most of the application
such as mathematical, scientific, business and system software applications.

C is small language, consisting of only 32 English words known as keywords (if, else, for, break etc.:
The power of C is augmen,ted by the library functions provided with it. Moreover, the langua'ge i
extendible since it allows the users to add their own library functions to the library.

\
C contains control constructs needed to write a structured program hence it is considered a structure
programming language. It includes structures for selection (if.. .else, switch), repetition (while, fo
do ... while) and for loop exit\ (break).
.
.
The programs w~itten in C aile portable i.e. programs written for one type of computer or operatin
system can be run \on anothet type of computer or operating system.

1.6

StructJre of a C Program

,

C program is a colle\tion of one or more- functions. Every function is a collection of statements an
performs some specific task. The general structure of C program isComments
Preprocessor di'r'fctives
Global variables \
main(
function\
{

local variables
\tatements

}

funcl(
{


local variables
statements

}

func2(
{

local variables
statements

Comments can be placed anywhere in a program and are enclosed qetween the delimiters /* at
*/.Comments are generally used for documentation purposes.
I


Introduction to C

5

Preprocessor directives are processed through preprocessor before the C source code passes through
ompiler. The commoniy used preprocessor directives are #include and #define. #include is used for
including header files. #define is used to define symbolic constants and macros.
Every C program has one or more functions. If a program has only one function then it must be mainO..
Execution of every C program starts with maine ) .function. It has two parts, declaration of local variables
and statements. The ~ci'pe of the local variable is local to that function only. Statements in the mainO
function are executed one by one. Other functions are the user-defined functions, which also have local
variables and C statements. They can be defined before or after maine ). It may be possible that some
ariables have to be used in many functions, so it is necessary to declare them globally. These variables

are called global variables.

1.7
The
1.
2.
3.

Environment For C
steps for
Program
Program
Program

the execution of C program are ascreation
compilation
execution

The C programs are written in :mostly two environments, UNIX and MS-DOS.

1.7.1

Unix Environment

Generally a command line C compiler is provided with the UNIX operating system. This compiler is
named cc or gcc,

(a) Program creation
In unix environment, file can be created with vi editor as-


$ vi filename.c

--

Here $ is the unix prompt. The file can be saved by pressing ESC and SHIFT+zz.
.

) Program compilation
After creation of C program, it can be compiled as$cc filename.c

the program has mathematical function then it is compiled as$cc filename.c -1m
After compilation, the executable code is stored in the file a.out .

) Program execution
_\fier the compilation of program, it can be executed as$ a.out

.....

.7.2

MS-DOS Environment

- MS-DOS environment creation, compilation and execution can be done using command line or IDE
mtegrated Development Environment).

.7.2.1

Command Line

Borland C, the command line compiler is bcc.exe and in Turbo C the command line compiler is tcc.exe.



C in Depth

6

(a) Program creation
The program file can be created using any editor and should be saved with .c extension.

(b) Program compilation
After saving the file, C program Gan be compiled at DOS prompt by writingC:\>tcc filen'ame (in Turbo C)
C:\>bcc filename (in Borland C)

(c) Program execution
After compilation of C program, the executable file filename.exe is created. It is executed at DOS promp
by writingC:\>filename

1. 7.2.2

Integrated Development Environment

All these steps can be performed in an IDE using menu options or shortcut keys. In Borland C thl
program bc.exe is the IDE and in Turbo C the program tC.exe is the IDE. So we can open the IDI
by typing bc or tc at the command prompt.

(a). Program creation
A new file can be created from menu optign New. The file can be saved by menu option Save. If th,
file is unnamed then it is savell by menu option Save as. An existing file can be opened from the mem
option Open.
(b) Program. compilation

The file compiled by the menu option Compile. (Alt+F9)

(c) Program execution
The file can be executed by the menu option Run. (Ctrl+F9). The output appears in the outp,ut windm
that can be seen using the keys Alt+F5.
.
We have' given you just a preliminary knowledge of how to execute your programs. There are seven;
other options that you can explore while working and it is best to check the manual of your compile
to know about these options.


pth

Chapter 2

Elements of C

Impt

~

the
IDE

Every language has some basic elements and grammatical rules. Before understanding programming,
- is must to know the basic elements of C language. These basic elements are character set, variables,
tatypes, constants, keywords (reserved words), variable declaration, expressions, statements etc. All
of these are l,lsed to construct a- C program.

.1

:fie

f the

nenu

C Character Set
c~aracters

.1.1

that are used in C programs are given below-

Alphabets

A, B, C
a, b, c

Z
z

Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Idow

_.1.3

Special characters
Character


veral
tpiler

+

*
\
<
>
(
{
[

,
,

:

?
&
@
$

-

Meaning
plus sign
asterisk
Backward slash
less than sign .

greater than sign
left parenthesis
left braces
left bracket
comma
single quotes
colon
Question mark
ampersand
at the rate
dollar sign
tilde sign

Character

%
/

=
-

)

}
]
"
;

!


I
A

#

,

Meaning
minus sign(hyphen)
percent sign
forward slash
equal to sign
underscore
right parenthesis
right braces
right bracket
period
double quotes
Semicolon
Exclamation sign
vertical bar
caret sign
hash sign
back quotation mark

"


C in Depth


8

2.2

Execution Characters/Escape Sequences

. Characters are printed on the screen through the keyboard but some characters such as newline, tab,
. backspace cannot be printed like other normal characters. C supports the combination of backslash (\)
and some characters from the C character set to print these characters.

These. character combinations are known as escape sequences and are represented by two characters.
The first character is "\" and second character is from the C character set. Some escape sequences
are given below-

Escape
Sequence

Meaning

ASCII Value

\b

backspace

008

\a
\r
\n

\f

bellealert)
carriage returnnewline
form feed

007
013
010
012

\0
\v

.null
vertical tab
Horizontal tab
backslash

000
011
009
092

\t
\\

Purpose
Moves the cursor to the previous position of the
current line

Produces a beep sound for alert
Moves the cursor to beginning of the current line.·
Moves the cursor to the beginning of the next line
Moves the cursor to the initial position of the next
logical page.
Null
Moves the cursor to next vertical tab position
Moves the cursor to the next horizontal tab position.
Presents a character with backslash ( \ )

Blank, horizontal tab, vertical tab, newline, carriage return, form feed are known as whitespace in (
language.

2.3

Trigraph Characters

There is a possibility that the keyboard doesn't print some characters. C supports the facility of "trigrapJ
sequence" to print these characters. These trigraph 'sequences have three characters.. First two an
'??' and third character is any character from C character ·set. Some trigraph sequences are as give]
helow-

Trigraph Sequence
??<
17>

??(
??)
??!
??/

??=
????'

Symbol
{ left brace
} right brace
[ left bracket
] right bracket
I vertical bar
\ backslash
# hash slgn
tilde
/\
caret
~


Jth

2.4

tab,
(\)

9

Element of C

Delimiters


Delimiters are used for syntactic meaning in C. These are as given belowcolon
semicolon
parentheses
square brackets
curly braces
hash
comma

'.

ers.
ices

()
[ ]

{}
#

the

ne.

ine

2.5

Reserved Words / Keywords

There are certain words that are reserved for doing specific tasks. These words are known as keywords

d they have standard, predefin~d meaning in C. They are always written in lowercase. There are only
_ keywords available in C which are given belowauto .
const
double
float

lext

int

short
struct
unsigned

in C

_.6
sraph
o are
given

used for label
end of statement
used in expression
used for array
used for block of statements
preprocessor directive
variable delimiter

break

continue
else
for
long
signed
switch
void

case
default
enum
goto
register
sizeof
typedef
volatile

char
do
extern
if
return
static
umon
while

Identifiers

the words that we'll use in our C programs will be either keywords or identifiers. Keywords are
_ defined and can't be changed by the user, while identifiers are user defined words and are used to

-' e names to entities like variables, arrays, fUi1ctions, structures etc. Rules for naming identifiers are
~. 'en below) The name should consist of only alphabets (both upper and lower case), digits and underscore
sign( _ ).
_) First character should be an alphabet or underscore.
) The name should not be a keyword.
) Since C is case sensitive, the uppercase and lowercase letters are considered different. For example
code, Code and CODE are three different identifiers.
:) An identifier name may be arbitrarily long. Some implementations of C recognize only the first
eight characters, though most implementations recognize 31 characters. ANSI standard compilers
recognIze 31 characters.
_ e identifiers are generally given meaningful names. Some examples of valid identifier namesValue

a

net-pay

rec 1

e examples of invalid identifier names are-

data

MARKS


10

C in Depth

5bc

int
rec#
avg no

2.7

First character should be an alphabet or underscore
int is a keyword
# is a special character
blank space is not permitted

Data Types

C supports different types of data. Storage representation of these data types is different in memory.
There are four fundamental datatypes in C, which are int, char, float and double..
'char' is used to store any single character, Oint' is used to store integer value, 'float'·is used for storing
single precision floating point number and 'double' is used for storing double precision floating point
number. We can use type qualifiers with these basic types to get some more types.
There are two types of type qualifiers1. Size qualifiers
short, long
2. Sign qualifiers
signed, unsigned
When the qualifier unsigned is used the number is always positive, and when signed is used number
may be positive or negative. If the sign qualifier is not mentioned, then by default signed qualifier is
assumed. The range of values for signed data types is less thantliat of unsigned type. This is because
in signed type, the leftmost bit is used to represent the sign, while in unsigned type this bit is also used
to represent the value.
The size and range of different data types on a 16-bit machine is given in the following table. The size
and range may vary on machines with different word sizes.
.

Basic data
types
char

Data types with
type qualifiers

Range

Size(bytes)

char or signed char

1

-128 to 127

unsigned char

1

o to

int or signed int

2

-32768 to 32767

unsigned int


2

o to

short int or signed short int

1

-128 to 127

unsigned short int

1

o to

-lopg int or signed long int

4

-2147483648 to 214748,3647

unsigned long int

4

o to 4294967295

float


float

4

3.4E-38 to 3.4E+38

double

double

8

1.7E-308 to 1.7E+308

long double

10

3.4E-4932 to 1.1E+4932

int

2.8

255 .
65535
255

Constants'


Constant is a vll1ue that cannot be changed during execution of the program. There are three type1
of constants-


×