My Basket
You have nothing in your shopping cart yet.
Title: MASTER OF COMPUTER APPLICATION (RGPV UNIVERSITY BHOPAL)
Description: rgpv 5th semester notes for mca students
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Let Us C
Fifth Edition
Yashavant P
...
About the Author
Destiny drew Yashavant Kanetkar towards computers when the IT
industry was just making a beginning in India
...
Yashavant has a passion for writing and is an author of several
books in C, C++, VC++, C#,
...
He is a much sought after speaker on various
technology subjects and is a regular columnist for Express
Computers and Developer 2
...
His current affiliations include
being a Director of KICIT, a training company and DCube
Software Technologies, a software development company
...
NET Technical Contributor” award recently
...
com
...
During this journey I have met so many students,
developers, professors, publishers and authors who expressed their
opinions about Let Us C
...
In particular I am indebted to Manish Jain who had a faith in this
book idea, believed in my writing ability, whispered the words of
encouragement and made helpful suggestions from time to time
...
During this course people like Ajay Joshi, Amol Tambat, Ajay
Daga, Nandita Shastri, Mrunal Khandekar and Rahul Bedge
helped in writing programs, spotting bugs, drawing figures and
preparing index
...
Anup Das, my colleague has a lot of influence on this Fifth
Edition
...
He sincerely wanted this edition
to offer “C, in today’s perspective”
...
I thank Seema, my wife, for her friendship and for her
contributions in everything that I do in IT in ways more than she
could ever guess
...
And finally my heartfelt gratitude to the countless students who
made me look into every nook and cranny of C
...
v
Preface to the Fifth Edition
It is mid 2004
...
and moved on
...
At times I take
secret pleasure in seeing that a book that I have been part of, has
contributed in its own little way in shaping so many budding
careers that have made the “India” brand acceptable
...
So overwhelming has been the response to all the
previous editions of “Let Us C” that I have now decided that each
year I would come up with a new edition of it so that I can keep
the readers abreast with the way C is being used at that point in
time
...
In the first
phase he is a learner trying to understand the language elements
and their nuances
...
In my opinion,
even today there isn’t any learning environment that can beat
Turbo C/C++ for simplicity
...
Armed with the knowledge of language elements the C
programmer enters the second phase
...
I am pointing towards programs in
Windows and Linux world
...
I
would like to your attention the fact that if you want to program
Windows or Linux you need to have a very good grasp over the
programming model used by each of these OS
...
Once you understand these thoroughly rest is just a
vi
matter of time
...
In Linux programming the basic hurdle is in choosing the Linux
distribution, compiler, editor, shell, libraries, etc
...
They have been mentioned in Chapter 20 and Appendix H
...
In fourth edition of Let Us C there were chapters on ‘Disk Basics’,
‘VDU Basics’, ‘Graphics’, ‘Mouse Programming’, ‘C and
Assembly’
...
Modern
counterparts of all of these have been covered in Chapters 16 to
21
...
kicit
...
Also, all the programs present in the book are available in source
code form at www
...
com/books/letusc/sourcecode
...
If you wish to get solutions for the Exercises in the
book they are available in another book titled ‘Let Us C
Solutions’
...
So if you feel that I
could have done certain job better than what I have, or you have
any suggestions about what you would like to see in the next
edition, please drop a line to letuscsuggestions@kicit
...
All the best and happy programming!
vii
Contents
1
...
The Decision Control Structure
49
Decisions! Decisions!
The if Statement
The Real Thing
Multiple Statements within if
The if-else Statement
50
51
55
56
58
viii
Nested if-elses
Forms of if
Use of Logical Operators
The else if Clause
The ! Operator
Hierarchy of Operators Revisited
A Word of Caution
The Conditional Operators
Summary
Exercise
3
...
The Case Control Structure
Decisions Using switch
The Tips and Traps
switch Versus if-else Ladder
The goto Keyword
Summary
Exercise
ix
61
62
64
66
72
73
73
76
77
78
97
98
99
101
105
107
114
115
116
118
120
121
124
124
135
136
140
144
145
148
149
5
...
Data Types Revisited
158
165
166
171
172
173
174
175
178
178
179
186
189
189
194
197
201
201
213
Integers, long and short
Integers, signed and unsigned
Chars, signed and unsigned
Floats and Doubles
A Few More Issues…
Storage Classes in C
Automatic Storage Class
Register Storage Class
Static Storage Class
External Storage Class
Which to Use When
Summary
Exercise
x
214
216
217
219
221
223
224
226
227
230
233
234
235
7
...
Arrays
242
244
248
252
253
255
258
260
260
261
263
264
269
What are Arrays
A Simple Program Using Array
More on Arrays
Array Initialization
Bounds Checking
Passing Array Elements to a Function
Pointers and Arrays
Passing an Entire Array to a Function
The Real Thing
Two Dimensional Arrays
Initializing a 2-Dimensional Array
Memory Map of a 2-Dimensional Array
Pointers and 2-Dimensional Arrays
Pointer to an Array
Passing 2-D array to a Function
Array of Pointers
Three Dimensional Array
Summary
xi
270
272
275
275
276
277
279
286
287
289
290
291
292
295
297
300
302
304
Exercise
304
9
...
Structures
328
329
334
335
337
339
342
343
344
347
351
352
353
354
363
Why Use Structures
Declaring a Structure
Accessing Structure Elements
How Structure Elements are Stored
Array of Structures
Additional Features of Structures
Uses of Structures
Summary
Exercise
11
...
File Input/Output
404
405
409
409
415
Data Organization
File Operations
Opening a File
Reading from a File
Trouble in Opening a File
Closing the File
Counting Characters, Tabs, Spaces, …
A File-copy Program
Writing to a File
File Opening Modes
String (line) I/O in Files
The Awkward Newline
Record I/O in Files
Text Files and Binary Files
Record I/O Revisited
Database Management
Low Level Disk I/O
A Low Level File-copy Program
I/O Under Windows
Summary
Exercise
13
...
Operations On Bits
481
Bitwise Operators
One’s Complement Operator
Right Shift Operator
Left Shift Operator
Bitwise AND Operator
Bitwise OR Operator
Bitwise XOR Operator
The showbits( ) Function
Summary
Exercise
15
...
C Under Windows
535
Which Windows…
Integers
The Use of typedef
Pointers in the 32-bit World
Memory Management
Device Access
DOS Programming Model
Windows Programming Model
Event Driven Model
Windows Programming, a Closer Look
The First Windows Program
Hungarian Notation
Summary
Exercise
17
...
Graphics Under Windows
Graphics as of Now
Device Independent Drawing
xv
562
563
566
567
569
570
572
575
575
576
579
580
580
Hello Windows
Drawing Shapes
Types of Pens
Types of Brushes
Code and Resources
Freehand Drawing, the Paintbrush Style
Capturing the Mouse
Device Context, a Closer Look
Displaying a Bitmap
Animation at Work
WM_CREATE and OnCreate( )
WM_TIMER and OnTimer( )
A Few More Points…
Windows, the Endless World…
Summary
Exercise
19
...
C Under Linux
649
What is Linux
C Programming Under Linux
The ‘Hello Linux’ Program
Processes
Parent and Child Processes
More Processes
Zombies and Orphans
One Interesting Fact
Summary
Exercise
21
...
h File
Appendix G – Boot Parameters
Appendix H – Linux Installation
Index
687
691
701
713
719
725
729
735
739
xvii
1
Getting Started
• What is C
• Getting Started with C
The C Character Set
Constants, Variables and Keywords
Types of C Constants
Rules for Constructing Integer Constants
Rules for Constructing Real Constants
Rules for Constructing Character Constants
Types of C Variables
Rules for Constructing Variable Names
C Keywords
• The First C Program
• Compilation and Execution
• Receiving Input
• C Instructions
Type Declaration Instruction
Arithmetic Instruction
Integer and Float Conversions
Hierarchy of Operations
Associativity Of Operators
• Control Instruction in C
• Summary
• Exercise
1
2
Let Us C
B
efore we can begin to write serious programs in C, it would
be interesting to find out what really is C, how it came into
existence and how does it compare with other computer
languages
...
Four important aspects of any language are the way it stores data,
the way it operates upon this data, how it accomplishes input and
output and how it lets you control the sequence of execution of
instructions in a program
...
What is C
C is a programming language developed at AT & T’s Bell
Laboratories of USA in 1972
...
In the late seventies C began to
replace the more familiar languages of that time like PL/I,
ALGOL, etc
...
It wasn’t made the ‘official’ Bell
Labs language
...
Ritchie seems to have been
rather surprised that so many programmers preferred C to older
languages like FORTRAN or PL/I, or the newer ones like Pascal
and APL
...
Possibly why C seems so popular is because it is reliable, simple
and easy to use
...
An opinion that is often heard today is – “C has been already
superceded by languages like C++, C# and Java, so why bother to
Chapter 1: Getting Started
3
learn C today”
...
There
are several reasons for this:
(a) I believe that nobody can learn C++ or Java directly
...
do deal with apart from
knowing the actual language elements
...
Hence one should first learn all the language
elements very thoroughly using C language before migrating
to C++, C# or Java
...
(b) C++, C# or Java make use of a principle called Object
Oriented Programming (OOP) to organize the program
...
But even
while using this organizing principle you would still need a
good hold over the language elements of C and the basic
programming skills
...
(d) Major parts of popular operating systems like Windows,
UNIX, Linux is still written in C
...
Moreover, if one is to extend the operating system to
work with new devices one needs to write device driver
programs
...
4
Let Us C
(e) Mobile devices like cellular phones and palmtops are
becoming increasingly popular
...
This smartness comes
from a microprocessor, an operating system and a program
embedded in this devices
...
No wonder that such programs are written in C
...
(f) You must have seen several professional 3D computer games
where the user navigates some object, like say a spaceship and
fires bullets at the invaders
...
Needless to say, such games won't become popular if
they takes a long time to move the spaceship or to fire a
bullet
...
This is where C language
scores over other languages
...
(g) At times one is required to very closely interact with the
hardware devices
...
I hope that these are very convincing reasons why one should
adopt C as the first and the very important step in your quest for
learning programming languages
...
However, there is
5
Chapter 1: Getting Started
a close analogy between learning English language and learning C
language
...
Learning C is similar and easier
...
A group of instructions
would be combined later on to form a program
...
1
...
1
The C Character Set
A character denotes any alphabet, digit or special symbol used to
represent information
...
2 shows the valid alphabets,
numbers and special symbols allowed in C
...
, Y, Z
a, b, ……, y, z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols
~‘!@# %^&*()_-+=|\{}
[]:; "'<>,
...
2
Constants, Variables and Keywords
The alphabets, numbers and special symbols when properly
combined form constants, variables and keywords
...
A constant is an entity that
doesn’t change whereas a variable is an entity that may change
...
The results of
these calculations are stored in computers memory
...
The calculated values are stored in these memory cells
...
Since the value
stored in each location may change the names given to these
locations are called variable names
...
Here 3 is stored in a memory location and a name x is given to it
...
This would overwrite the earlier value 3, since a memory
location can hold only one value at a time
...
3
...
3
Since the location whose name is x can hold different values at
different times x is known as a variable
...
Types of C Constants
C constants can be divided into two major categories:
(a) Primary Constants
(b) Secondary Constants
These constants are further categorized as shown in Figure 1
...
8
Let Us C
C Constants
Primary Constants
Secondary Constants
Integer Constant
Array
Real Constant
Pointer
Character Constant
Structure
Union
Enum, etc
...
4
At this stage we would restrict our discussion to only Primary
Constants, namely, Integer, Real and Character constants
...
For constructing these
different types of constants certain rules have been laid down
...
It must not have a decimal point
...
If no sign precedes an integer constant it is assumed to be
positive
...
(f) The allowable range for integer constants is -32768 to 32767
...
For a 16-bit compiler like Turbo C or Turbo C++ the
vipin
Chapter 1: Getting Started
9
range is –32768 to 32767
...
Question like what exactly do you mean by a 16bit or a 32-bit compiler, what range of an Integer constant has to
do with the type of compiler and such questions are discussed in
detail in Chapter 16
...
Ex
...
The real
constants could be written in two forms—Fractional form and
Exponential form
...
It must have a decimal point
...
Default sign is positive
...
Ex
...
34
426
...
76
-48
...
It
however doesn’t restrict us in any way from using exponential
form of representation for other real constants
...
The part appearing before ‘e’ is called
mantissa, whereas the part following ‘e’ is called exponent
...
(b) The mantissa part may have a positive or negative sign
...
(d) The exponent must have at least one digit, which must be a
positive or negative integer
...
(e) Range of real constants expressed in exponential form is
-3
...
4e38
...
: +3
...
1e8
-0
...
2e-5
Rules for Constructing Character Constants
(a) A character constant is a single alphabet, a single digit or a
single special symbol enclosed within single inverted
commas
...
For example, ’A’ is a valid character constant whereas ‘A’ is
not
...
Ex
...
Variable names are names given to
locations in memory
...
In any language, the types of variables that it
can support depend on the types of constants that it can handle
...
For example, an integer variable can hold only an
integer constant, a real variable can hold only a real constant and a
character variable can hold only a character constant
...
However, for constructing variable names of all types the same set
of rules apply
...
Rules for Constructing Variable Names
(a) A variable name is any combination of 1 to 31 alphabets,
digits or underscores
...
Still, it would be
safer to stick to the rule of 31 characters
...
(b) The first character in the variable name must be an alphabet or
underscore
...
(d) No special symbol other than an underscore (as in gross_sal)
can be used in a variable name
...
: si_int
m_hra
pop_e_89
These rules remain same for all the types of primary and secondary
variables
...
how is C able to
differentiate between these variables? This is a rather simple
12
Let Us C
matter
...
This type
declaration is done at the beginning of the program
...
: int si, m_hra ;
float bassal ;
char code ;
Since, the maximum allowable length of a variable name is 31
characters, an enormous number of variable names can be
constructed using the above-mentioned rules
...
Thus, if we want to calculate simple interest, it is always advisable
to construct meaningful variable names like prin, roi, noy to
represent Principle, Rate of interest and Number of years rather
than using the variables a, b, c
...
The keywords cannot be used as variable names because if we do
so we are trying to assign a new meaning to the keyword, which is
not allowed by the computer
...
However, it would be safer not to mix up the variable names and
the keywords
...
There are only 32 keywords available in C
...
5 gives a list
of these keywords for your ready reference
...
13
Chapter 1: Getting Started
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
goto
sizeof
volatile
do
if
static
while
Figure 1
...
) provide
their own keywords apart from the ones mentioned above
...
Though it has
been suggested by the ANSI committee that every such compiler
specific keyword should be preceded by two underscores (as in
__asm ), not every vendor follows this rule
...
However, instead of this, we would write our first C
program now
...
Before we begin with our first C program do remember the
following rules that are applicable to all C programs:
(a) Each instruction in a C program is written as a separate
statement
...
14
Let Us C
(b) The statements in a program must appear in the same order in
which we wish them to be executed; unless of course the logic
of the problem demands a deliberate ‘jump’ or transfer of
control to a statement, which is out of sequence
...
However, no blank spaces are
allowed within a variable, constant or keyword
...
(e) C has no specific rules for the position at which a statement is
to be written
...
(f)
Every C statement must end with a ;
...
Let us now write down our first C program
...
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n=3;
r = 8
...
−
Comment about the program should be enclosed within /* */
...
−
Though comments are not necessary, it is a good practice to
begin a program with a comment indicating the purpose of the
program, its author and the date on which the program was
written
...
For example, a comment can be written before the
statement, after the statement or within the statement as shown
below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
−
Sometimes it is not so obvious as to what a particular
statement in a program accomplishes
...
For example:
/* formula for simple interest */
si = p * n * r / 100 ;
−
Often programmers seem to ignore writing of comments
...
16
Let Us C
−
Although a lot of comments are probably not necessary in this
program, it is usually the case that programmers tend to use
too few comments rather than too many
...
−
The normal language rules do not apply to text written within
/*
...
This is because the comments are solely given
for the understanding of the programmer or the fellow
programmers and are completely ignored by the compiler
...
For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid
...
−
main( ) is a collective name given to a set of statements
...
All
statements that belong to main( ) are enclosed within a pair of
braces { } as shown below
...
Every function has
a pair of parentheses ( ) associated with it
...
−
Any variable used in the program must be declared before
using it
...
5 ;
−
In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators
...
C is very rich in operators
...
Surprisingly there
is no operator for exponentiation
...
−
Once the value of si is calculated it needs to be displayed on
the screen
...
All output to screen
is achieved using readymade library functions
...
We have used it display on the screen the
value contained in si
...
These
characters are printed as they are when the printf( ) is
executed
...
%f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this
...
5
What is ‘\n’ doing in this statement? It is called newline and it
takes the cursor to the next line
...
‘\n’ is one of the several Escape
Sequences available in C
...
Right now, all that we can say is ‘\n’ comes in
Chapter 1: Getting Started
19
handy when we want to format the output properly on
separate lines
...
An expression is nothing but
a valid combination of constants, variables and operators
...
The results of these expressions can be printed as shown
below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions
...
To type your C program you need
another program called Editor
...
To carry out this conversion we need
another program called Compiler
...
There are several such IDEs available in the market targeted
towards different operating systems
...
Note that Turbo C++, Microsoft C++ and Borland C++
software also contain a C compiler bundled with them
...
Once you have mastered the language
elements you can then switch over to more sophisticated compilers
like Visual C++ under Windows or gcc under Linux
...
Wherever there is a deviation I would point it out that time
...
The compiler (TC
...
(b) Select New from the File menu
...
(d) Save the program using F2 under a proper name (say
Program1
...
(e) Use Ctrl + F9 to compile and execute the program
...
Note that on compiling the program its machine language
equivalent is stored as an EXE file (Program1
...
This file is called an executable file
...
In fact the other machine need not even have a
compiler to be able to execute the file
...
To get rid of this error, perform the following
steps and then recompile the program
...
In the dialog box that pops up, select ‘CPP always’
in the ‘Use C++ Compiler’ options
...
Make sure that the default extension is ‘C’ rather than
‘CPP’
...
5
...
If we want to calculate
simple interest for some other set of values then we are required to
make the relevant change in the program, and again compile and
execute it
...
Moreover, if you distribute the
EXE file of this program to somebody he would not even be able
to make changes in the program
...
To make the program general the program itself should ask the
user to supply the values of p, n and r through the keyboard during
execution
...
This function is a counter-part of the printf( ) function
...
This is illustrated in the program shown below
...
Here we have not used any expression in printf( )
which means that using expressions in printf( ) is optional
...
& is an ‘Address of’ operator
...
When we say
&a, we are telling scanf( ) at which memory location should it
store the value supplied by the user from the keyboard
...
Note that a blank, a tab or a new line must separate the values
supplied to scanf( )
...
This is
shown below:
Ex
...
5
Ex
...
1000 5
15
...
: The three values separated by newline
...
5
So much for the tips
...
/* Just for fun
...
" ) ;
printf ( "You have just entered the number %d", num ) ;
}
C Instructions
Now that we have written a few programs let us look at the
instructions that we used in these programs
...
(b) Arithmetic instruction
−
To perform arithmetic
operations between constants and variables
...
Since, the elementary C programs would usually contain only the
type declaration and the arithmetic instructions; we would discuss
only these two instructions at this stage
...
24
Let Us C
Type Declaration Instruction
This instruction is used to declare the type of variables being used
in the program
...
The type declaration statement is
written at the beginning of main( ) function
...
: int bas ;
float rs, grosssal ;
char name, code ;
There are several subtle variations of the type declaration
instruction
...
int i = 10, j = 25 ;
float a = 1
...
99 + 2
...
44 ;
(b) The order in which we define the variables is sometimes
important sometimes not
...
5, b = a + 3
...
1, a = 1
...
This is because here we are trying to use a even before
defining it
...
Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left
hand side of = and variable names & constants on the right hand
side of =
...
Ex
...
0056 ;
deta = alpha * beta / gamma + 3
...
= is the assignment operator
...
3
...
0056 are real constants
...
kot, deta, alpha, beta, gamma are real variables
...
A C arithmetic statement could be of three types
...
Ex
...
Ex
...
123 / 4
...
3442 ;
si = prin * anoy * roi / 100
...
Ex
...
0 ;
avg = ( a + b + c + num ) / 4 ;
It is very important to understand how the execution of an
arithmetic statement takes place
...
This value is then assigned to the variable on the
left-hand side
...
Let us take a closer look at
these statements
...
(a) C allows only one variable on left-hand side of =
...
(b) In addition to the division operator C also provides a modular
division operator
...
Thus the expression 10 / 2
yields 5, whereas, 10 % 2 yields 0
...
Also note that on
using % the sign of the remainder is always same as the sign
of the numerator
...
(c) An arithmetic instruction is often used for storing character
constants in character variables
...
ASCII values are used to represent any
character in memory
...
(d) Arithmetic operations can be performed on ints, floats and
chars
...
The ASCII values of ‘a’ and ‘b’ are 97 and 98,
and hence can definitely be added
...
It must be written
explicitly
...
a = c
...
b(xy)
b=c*d*b*(x*y)
usual arithmetic statement
C statement
(f) Unlike other high level languages, there is no operator for
performing exponentiation operation
...
a = 3 ** 2 ;
b=3^2;
If we want to do the exponentiation we can get it done this
way:
#include