My Basket
You have nothing in your shopping cart yet.
Title: Complete Guide To C Language
Description: Complete Guide To C language, With Exercises, Useful Referance Book to First Year Undergraduate to Last Year Graduate
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Complete
Guide To C
Contents
1
...
Getting Started 1
What is C 2
Getting Started with C 4
The C Character Set 5
Constants, Variables and Keywords 6
Types of C Constants 7
Rules for Constructing Integer Constants 8
Rules for Constructing Real Constants 9
Rules for Constructing Character Constants 10
Types of C Variables 11
Rules for Constructing Variable Names 11
C Keywords 12
The First C Program 13
Compilation and Execution 19
Receiving Input 21
C Instructions 23
Type Declaration Instruction 24
Arithmetic Instruction 25
Integer and Float Conversions 29
Type Conversion in Assignments 29
Hierarchy of Operations 31
Associativity of Operators 34
Control Instructions in C 37
Summary 37
Exercise 38
The Decision Control Structure 49
Decisions! Decisions! 50
The if Statement 51
The Real Thing 55
Multiple Statements within if 56
The if-else Statement 58
viii
Nested if-elses 61
Forms of if 62
Use of Logical Operators 64
The else if Clause 66
The ! Operator 72
Hierarchy of Operators Revisited 73
A Word of Caution 73
The Conditional Operators 76
Summary 77
Exercise 78
3
...
The Loop Control Structure 97
Loops 98
The while Loop 99
Tips and Traps 101
More Operators 105
The for Loop 107
Nesting of Loops 114
Multiple Initialisations in the for Loop 115
The Odd Loop 116
The break Statement 118
The continue Statement 120
The do-while Loop 121
Summary 124
Exercise 124
The Case Control Structure 135
Decisions Using switch 136
The Tips and Traps 140
switch Versus if-else Ladder 144
The goto Keyword 145
Summary 148
Exercise 149
ix
5
...
Functions & Pointers 157
What is a Function 158
Why Use Functions 165
Passing Values between Functions 166
Scope Rule of Functions 171
Calling Convention 172
One Dicey Issue 173
Advanced Features of Functions 174
Function Declaration and Prototypes 175
Call by Value and Call by Reference 178
An Introduction to Pointers 178
Pointer Notation 179
Back to Function Calls 186
Conclusions 189
Recursion 189
Recursion and Stack 194
Adding Functions to the Library 197
Summary 201
Exercise 201
Data Types Revisited 213
Integers, long and short 214
Integers, signed and unsigned 216
Chars, signed and unsigned 217
Floats and Doubles 219
A Few More Issues… 221
Storage Classes in C 223
Automatic Storage Class 224
Register Storage Class 226
Static Storage Class 227
External Storage Class 230
Which to Use When 233
Summary 234
Exercise 235
x
The C Preprocessor 241
Features of C Preprocessor 242
Macro Expansion 244
Macros with Arguments 248
Macros versus Functions 252
File Inclusion 253
Conditional Compilation 255
#if and #elif Directives 258
Miscellaneous Directives 260
#undef Directive 260
#pragma Directive 261
Summary 263
Exercise 264
7
...
Arrays 269
What are Arrays 270
A Simple Program Using Array 272
More on Arrays 275
Array Initialization 275
Bounds Checking 276
Passing Array Elements to a Function 277
Pointers and Arrays 279
Passing an Entire Array to a Function 286
The Real Thing 287
Two Dimensional Arrays 289
Initializing a 2-Dimensional Array 290
Memory Map of a 2-Dimensional Array 291
Pointers and 2-Dimensional Arrays 292
Pointer to an Array 295
Passing 2-D array to a Function 297
Array of Pointers 300
Three Dimensional Array 302
Summary 304
xi
Exercise 304
Puppetting On Strings 327
What are Strings 328
More about Strings 329
Pointers and Strings 334
Standard Library String Functions 335
strlen( ) 337
strcpy( ) 339
strcat( ) 342
strcmp( ) 343
Two-Dimensional Array of Characters 344
Array of Pointers to Strings 347
Limitation of Array of Pointers to Strings 351
Solution 352
Summary 353
Exercise 354
9
...
11
...
13
...
15
...
17
...
Windows Programming 561
The Role of a Message Box 562
Here Comes the window… 563
More Windows 566
A Real-World Window 567
Creation and Displaying of Window 569
Interaction with Window 570
Reacting to Messages 572
Program Instances 575
Summary 575
Exercise 576
Graphics Under Windows 579
Graphics as of Now 580
Device Independent Drawing 580
xv
Hello Windows 582
Drawing Shapes 586
Types of Pens 590
Types of Brushes 592
Code and Resources 596
Freehand Drawing, the Paintbrush Style 596
Capturing the Mouse 600
Device Context, a Closer Look 601
Displaying a Bitmap 603
Animation at Work 607
WM_CREATE and OnCreate( ) 611
WM_TIMER and OnTimer( ) 611
A Few More Points… 612
Windows, the Endless World… 613
Summary 614
Exercise 615
19
...
21
...
h File 725
Appendix G – Boot Parameters 729
Appendix H – Linux Installation 735
Index 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 Complete Guide To C
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
...
B
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)
(b)
(c)
(d)
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
...
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
...
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 Complete Guide To C
(e)
(f)
(g)
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
...
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
...
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
Chapter 1: Getting Started 5
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
x3x5
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)
(b)
Primary Constants
Secondary Constants
These constants are further categorized as shown in Figure 1
...
8 Complete Guide To C
Figure 1
...
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
...
(b)
(c)
(d)
(e)
(f)
It must not have a decimal point
...
If no sign precedes an integer constant it is assumed to be
positive
...
The allowable range for integer constants is -32768 to 32767
...
For a 16-bit compiler like Turbo C or Turbo C++ the
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
...
The mantissa part may have a positive or negative sign
...
The exponent must have at least one digit, which must be a
positive or negative integer
...
Range of real constants expressed in exponential form is
-3
...
4e38
...
: +3
...
1e8
-0
...
2e-5
Rules for Constructing Character Constants
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)
(b)
(c)
(d)
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
...
The first character in the variable name must be an alphabet or
underscore
...
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 Complete Guide To 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
...
Chapter 1: Getting Started 13
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 Complete Guide To C
(b)
(c)
(d)
(e)
(f)
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
...
C has no specific rules for the position at which a statement is
to be written
...
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 Complete Guide To 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
...
Select New from the File menu
...
Save the program using F2 under a proper name (say
Program1
...
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
...
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 Complete Guide To 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 ;
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)
(b)
(c)
(d)
C allows only one variable on left-hand side of =
...
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
...
An arithmetic instruction is often used for storing character
constants in character variables
...
ASCII values are used to represent any
character in memory
...
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) usual arithmetic statement
b = c * d * b * ( x * y ) C statement
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