C Notes PDF
C Notes PDF
Security etc
Syntax errors: The grammatical rules, which govern programming languages, are
called as syntax.
Ex: wrongly typed statements like missing semicolon, spelling mistakes etc.
a) Dividing by zero
b) Square root of a negative number
c) Logarithm of a negative number
d) Mixing of various data types
(ii)
Logical errors: Logical errors are due to the existence of logically incorrect
instruction in the program. These errors can be known only after output is
examined. Logical errors are often hard to find even when they are known to
exist.
6) Testing
7) Document and maintenance
Documentation is process of collecting, organizing and maintaining
complete information about the program.
Modifications of the program according to the user requirement are
Oval
Terminal
Start / Stop
Making
Parallelogram
Input / output
for
data available
processing
recording
of
or
the
processed information
An assignment operation
Rectangle
Process
normally represented by
this symbol.
Diamond
Decision
Used
Circle
Connector
different
to
connect
parts
of
flowchart.
Joins two symbols and
Arrow
Flow
Bracket with
Annotation
broken line
Descriptive comments
Double sided
Predefined
rectangle
process
Modules or subroutines
INTRODUCTION TO C:
It was developed in the 1970s by Dennis M. Ritche at Bell Telephone
Laboratories (AT & T Bell Labs). C is an outgrowth of BCPL (Basic Combined
Programming Language) developed by Martin Richards at Cambridge University.
BCPL also called as B language.
C is a middle-level computer programming language, because it has the
features of both high-level languages, such as ADA, C++, JAVA, FORTAN, COBOL,
ALGOL, BASIC, PASCAL etc., and low-level languages such as assembly language,
Machine-level languages.
C FEATURES:
1) C has very small instruction set. Just we have only 32 keywords in C.
2) C is portable i.e., software written for computer can be run on another
computer.
3) We can add user defined functions to C library.
4) C is modular.
5) C is robust.
ADVANTAGES OF C:
1) C programs take less memory than other languages.
2) C programs runs faster than all other languages.
APPLICATIONS OF C:
1) To develop 2D, 3D games
2) To develop Operating Systems like DOS, WINDOWS, UNIX, LINUX,
MACINTOSH etc. The entire UNIX OS developed in C.
3) Programs for device drivers
STRUCTURE OF A C PROGRAM:
Documentation section
Global declaration section
Preprocessor section
Main ( )
{
Declaration part;
Executable part;
- - - - - - - - - - - - - - - - - - - - - }
Sub Function section
DATE: 2-12-2006
*/
# include<stdio.h>
Void main ( )
{
printf (HEARTLY WELCOME TO C LEARNERS);
}
Comments in the C program are optional and may appear anywhere in a C
program.
Comments are enclosed between /* and */.
Comments can not be nested.
Comments are used to write to tell information about a program like
programmer name, program name, date etc.
All comments are ignored by the compiler.
The execution of the C program starts from main and executes all instructions
sequentially. The word main is followed by a pair of ordinary parenthesis ( ), which
indicates that main is a function.
-------- Run
Alphabets
Nested IF:
Words
Sentences
Paragraph
IN C
Alphabets
,l
(A-Z, a-z),
Digits (0-9),
Special symbols
Constants,
Variables,
Keywords
Statements,
Sub functions
Programs
Software
* ^ & @ ! ~ + ( [ etc
A variable is a name that is used to store data value and is allowed to vary the
value during the program execution.
Ex: int x=10; //here int is data type x is a variable, 10 is constant and =, ; are special
characters.
Rules for constructing variable names:
1) The first character must be either underscore (_), or a letter.
2) No special characters permitted except underscore.
3) Blanks are not allowed with in a variable name.
4) Upper case and lower case letters are not same.
5) The variable name should not be a C keyword.
6) The variable name should not be a user defined or library function name.
To declare a variable syntax is: data-type var-name;
Ex: int x, y, z;
A digit, or an alphabet, or a special symbol enclosed in a single quote is called
a character. Ex: 9, a,#. Every character contains its equivalent ASCII
(American Standard Code for Information Interchange) value.
Group of alphanumeric characters enclosed with in the double quotes is called
a string. To identify the end of the string every string in C ends with a null
character (\0). Ex: 9, abc123, hello, +-*//+
Note: 9, 9, 9 are not same.
9) double
17) int
25) struct
2) break
10) else
18) long
26) switch
3) case
11) enum
19) register
27) typedef
4) char
12) extern
20) return
28) union
5) const
13) float
21) short
29) unsigned
6) continue
14) for
22) signed
30) void
7) default
15) goto
23) sizeof
31) volatile
8) do
16) if
24) static
32) while
DATA TYPES:
A datatype defines a set of values and the operations that can be performed on
them. They are 3 types.
1) Primary (Basic) -------- int, char, float, double, void
2) Derived ------------------array, structure, union, pointer
3) User defined ----------- typedef, enum
Size in
Format
bytes
Specifier
signed char
%c
-128 to 127
unsigned char
%c
0 to 255
signed int
%d or %u
unsigned int
%u
0 to 65535
%d
-32768 to 32767
%d
0 to 65535
%ld
-2147483648 to 2147483647
%ud
0 to 4294967295
float
%f
3.4E-38 to 3.4E+38
double
%lf
1.7-308 to 1.7E+308
Type- keyword
Range
-32768 to 32767
long double
10
%Lf
3.4E-4932 to 1.1E+4932
1) printf(string);
2) printf( format string, list of variables);
printf(WELCOME TO C WORLD);
Ex:
Scanf() returns number of items read and stored, in case of any error it returns
-1.
Note: C is not a strongly typed programming language. That is in C even you assign
integer value to float variable or float value to character variable compiler does not
show any error. Examples for strongly typed programming languages are Java,
COBOL etc.
C, C++, Java are free form languages. That means you can write a same single
statement in multiple lines.
OPERATORS & EXPRESSIONS:
Operator: It is a symbol that tells the computer to perform certain mathematical
or logical manipulations.
Expression: It is a combination of constants, variables and operators produce a
single value after evaluation.2 types of expressions are
1) Numerical Expressions: which gives numerical value
Ex: 2, 2+3, 2/a, a*b, (x+y)*c+5 etc
2) Boolean expressions: which return true or false
Precedence of Operators:
OPERATOR
ASSOCIATIVITY
RANK
( ), [ ], ->
Left to Right
Right to Left
*, /, %
Left to Right
+, -
<<, >>
= =, !=
&
10
&&
11
||
12
?:
Right to Left
13
14
Left to Right
15
TYPE CONVERSION:
The process of converting one data type to another data type is called a type
conversion. The value of the right side of the assignment operator (rvalue) is
converted to the type of the left side variable (lvalue).
Ex:
int i;
float f;
i=8.25;
f=10;
2) switch
Types of If are 1) if
if syntax:
3) goto
2) if-else
if (expression)
{
statement-1;
statement-2;
-------------statement-n;
}
3) else-if ladder
if-else syntax:
4) nested-if
if (expression)
{
statement-1;
statement-2;
-------------statement-n;
}
else
{
statements;
}
--------------------------------}
nested-if Syntax: If (condition)
{
If (condition)
{
11
statement-1;
statement-2;
--------------
statement-n;
}
}
label-name: statement-1;
statement-2;
-------------statement-3;
goto label-name;
** GOTO may be after or before the label name.
SWITCH:
The switch makes one selection when there are several choices to be made.
Syntax: switch (integer expression)
{
case casevalue-1: statement-1;
--------------;
statement-n;
break;
case casevalue-2: statement-1;
--------------;
statement-n;
break;
case casevalue-n: statement-1;
--------------;
statement-n;
break;
default:
statement-1;
--------------;
statement-n;
break;
}
12
For the casevalue we can write either an integer or a character but not float and
string.
Each casevalue must be distinct.
The break causes an immediate exit from the switch. If the break is not
included, all of the statements below the match will be executed.
When integer expression matches with casevalue, compiler executes the
statements following that case.
If the break statement is not included, all of the statements below the match will
be executed.
If no match is found with any one of the case statement then the default
statements will be executed.
2) do-while
3) for
Syntax:
initialization;
do
while( expression)
statement-1;
statement-1;
statement-1;
statement-2;
statement-2;
statement-2;
----------------
----------------
----------------
statement-n;
statement-n;
statement-n;
increment / decrement;
}
increment / decrement;
}
while(expression);
In while first if the condition is true then only compiler executes the while
statements. If condition is false then compiler executes the next instruction
which is after the close brace of while. So while is called an entry-control loop.
In do-while first compiler executes the instructions then it checks the condition.
If that condition is false it goes to the next instruction which is after the close
brace of while. So it is called an entry-control loop.
The main difference between while and do-while is in while if the condition is
false compiler does not executes instruction. Where as in do-while even
condition is false compiler executes the instructions at least once.
13
The advantage with for is we can write initialization, condition and increment /
decrement parts in a single statement.
In for loop any or all of the 3 sections in the parentheses can be omitted,
although the semicolons must remain. If the conditional expression is assumed
to have a value 1 and the loop continues infinitely.
for ( ; ; )
{
statement-1;
---------------statement-n;
}
C allows nested loops i.e., a loop with in a loop.
One or more statements enclosed with in the open brace( { ) and close brace
( } ) is called a block.
Loops are also called as iterative statements.
BREAK AND CONTINUE:
C allows the break and continue statements to stop a particular iteration of a
loop / block early, for instance if an abnormal condition occurs.
A break statement inside the body of a loop / block breaks out of the loop /
block. No more instructions in the body of the loop / block are executed, and the next
statement after the loop / block will be executed.
The continue statement just skips any instructions after it on that iteration of the
loop. The current iteration of the loop is terminated, and the loop statement executed
again as if the last instruction of the loop body has been reached.
The exit ( ) function:
It causes immediate termination of the program and execution return to the
operating system.
break terminates the execution of loop or switch in which it is written, whereas
exit( ) terminates the execution program itself.
PREPROCESSOR DIRECTIVES:
C processor is a program that processes our source program before it is
passed to the compiler. Preprocessor commands often known as directives.
14
ARRAYS:
An array is a collection of elements of same data type. The individual
elements of an array can be referenced by means of its index (subscript). Arrays index
starts from zero. That is, if we declare an array of size n, we can refer the elements
from 0 to (n-1)th element. Array types are
$ One dimensional $ Two dimensional $ Three dimensional $ Multi dimensional
Syntax:
15
If we give values less than the size of an array some compilers initializes rest of
elements by spaces or zeroes.
C will not allow to specify repetition of an initialization, or to initialize an element
in the middle of an array without supplying all the preceding values.
Two dimensional syntax: data-type var-name [rows] [cols];
Ex: int x[3][4]={ {10, 20, 30, 40},
{50, 60, 70, 80},
{11, 22, 33, 44}
};
Since, the array elements are stored in adjacent locations, the above declaration also
can be written as
Int x[3][4]= {10, 20, 30, 40, 50, 60, 70, 80, 11, 22, 33, 44};
While initializing an array it is necessary to mention the second (column)
dimension, where as the first dimension (row) is optional.
Multi-dimensional arrays can be declared in C just by adding more subscripts.
The general form of multi-dimensional array is
data-type var-name [size1] [size2] [size3].. [sizen] ;
There is no restriction on the number of dimensions in C but it is limited only by
the amount of memory available to the program.
FUNCTIONS:
A self-contained block of statements is called a function.
Advantages:
1) reusability
2) debugging is easy
3) decreases the program complexity etc
Syntax: return-type function-name (parameter list)
{
Parameter declaration;
Body of function;
}
Variables declared in functions are called local variables and the scope is
limited to that function itself.
16
If the function does not return any value then write void before the function.
We can pass more than one parameter to a function but function returns a
single value.
C allows declaring the type of parameters along with the parameters itself.
There may be any number of return statements in function definition, but only
one statement will active in a function call.
The variable declarations within the function are local to the function and are
not available outside the function.
There should be one to one correspondence between the actual and formal
parameters in type, order and number.
A function can not be defined in another function. But we can declare any
number of functions.
Function Prototype:
Before defining a function other than main ( ), first we have to declare it. The
declaration of a function is known as function prototype.
A function prototype contains the function name and the data type of return
value, and the parameters and their types.
17
In case, the complete function is defined before main ( ), then the declaration
prototype is not required.
1) Call by value: Here we are calling a function by sending variable values. In this
we pass copy of variable values. In program even you change the formal
parameters; we can not find change in the actual parameters.
2) Call by reference: Here we are calling a function by sending variable addresses.
So the function receives reference to variable and works directly with the original
variable.
Recursion:
If a function called by it-self then it is known as recursion.
Storage Classes:
We can declare variables in 3 places.
1) inside the function local variables
2) outside of all functions global variables
3) in the definition of function parameters block variables
The storage classes tell how, when and where storage will be allocated for the
variable. In C we have 4 types of storage classes.
S.C
Type
auto
(default-
Local
local)
register
static
Local
Local
Initial
value
Declaration
or block
or block
Within function
or block
18
Storage
Memory
CPU
Registers
Memory
Scope
Lifetime
Within
Until
function
function no
or block
longer active
Within
Until
function
function no
or block
longer active
Within
Between
function
different
or block
function
calls
Programs
extern
(default- Global
global)
Within
program
Memory
Within all
execution
programs
does not
come to end
The initial value for a global variable must be a constant, whereas a local
variable may contain variables.
A local variable loses its value, the moment the function or block containing it is
exited. Whereas global variables retain their values throughout their execution.
If we write static before function then it become inaccessible outside the file.
STRINGS:
Group of alphanumeric characters enclosed within double quotes is
known as string. Ex: computer, 1234, 8, ad34cx+&z, *-/+ etc.
char str-name[size];
char name[10];
Initialization:
char name[10]=raghu; or
char name[10]={r,a,g,h,u,\0}; or
char date [ ] =27-01-2007;
Reading Strings:
We can use scanf( ), gets( ), getchar( ) functions to read strings.
In scanf( ) function use %s format specifier, and do not write & symbol
before string variable name. This is because, C treats the array name itself
as the address of first location of an array.
19
To overcome this problem, we can use gets( ) function. It will read string until
encounters a new line. It reads entire string at a time.
FUNCTION
isalphanum( )
Alphabetic or numeric
isalpha( )
Alphabetic
isdigit( )
Decimal digit
islower( )
isupper( )
isspace( )
White space
20
S.No
Function
Meaning
strlen(s1)
strrev(s1)
strlwr(s1)
strupr(s1)
strcat(s1, s2)
Append s2 to s1
strcpy(s1, s2)
Copies s2 to s1
strncpy(s1, s2)
strcmp(s1, s2)
s1<s2 => -1
10
11
strcmpi(s1,s2)
strchr(str,search
12
13
char)
strtok(str,char)
POINTERS:
Pointers are useful to work with memory address, to allocate memory
dynamically and to effectively represent complex data structures.
A pointer is a variable which holds address of another variable.
Syn: datatype * var-name;
Ex: int *x; char *p; or int* x, char* p;
Note that *(indirection operator) is part of variable type, not part of the name itself.
21
One pointer can be subtracted from another pointer but can not be added. The
expression returns the number of elements between them.
By using pointers the memory can be allocated or de-allocated dynamically. But it
is not possible with arrays.
The unary operator & is used to know the address of variable.
The unary operator * is used to know the value at the address location of a
variable.
& is called reference operator and * is called de-reference operator.
A global pointer variable gets initialized to a NULL pointer. NULL pointer address
is 0. We should not apply * on a NULL pointer because 0 th location usually used
by operating system.
Let ptr= 20 ptr = ptr+2; now the value of pte is 24 not 22
= 2*sizeof(int) = 2*2 = 4
Pointers to constant objects:
const int* pi;
int x[10];
pi=x;
*pi=200; or pi[4]=300; or not valid. But pi itself can be changed like pi++.
Constant pointers:
int * const pi=x;
*pi=100; is valid but pi++ is not valid.
const int * const pi=x; will disallow any modification to pi or the integer
which pi is pointing to.
22
23
FILES:
A file is a collection is a data stored permanently on secondary storage
devices such as disks, optical disks and tapes etc.
C works with files using a new data type called a file pointer.
C treats data file as a stream of characters. A stream is a general name given
to a flow of data.
C provides a data structure FILE declared in header file stdio.h to access the
streams of characters from the disk files. It acts as a link between OS and our
program.
Syntax: FILE *pointer-name;
24
File Operations:
1) open 2) close
3) rename
4) update
5) copy
6) append etc
Open:
fopen (file name, mode);
The different modes are
Mode
r
Description
Read. If the file does not exist it returns NULL value.
write. If file already exist, its contents are overwritten. Otherwise a new
r+
w+
a+
CLOSE:
fclose (file-pointer);
However, C closes all the files that are opened when the execution of the
program is completed.
Built-in File functions:
fputc (char-variable, file-pointer);
fgetc (file-pointer);
fputs (string-variable, file-pointer);
fgets (string-variable, length, file-pointer);
fscanf(file-pointer, format string, argument list);
fprintf(file-pointer, format string, argument list);
x = ftellp(file-pointer); - returns long integer which corresponds to the
current position in the file.
rewind(file-pointer); - moves file pointer to the beginning of a file. Rewind
is done implicitly whenever a file is opened.
fseek(file-pointer, off-set, position);
Here the position is 3 types.
1) 0 indicates beginning of the file
SEEK_SET
25
SEEK_CUR
SEEK_END
The fseek( ) is used to move the file pointer position to desired location.
The offset may be positive or negative. A positive value moves the pointer
toward the end of the file, while the negative offset moves the pointer towards
the beginning of the file.
The negative offset is used only when the position is 1.
fseek (fp, 0L, 0); - goto beginning of the file
fseek (fp, -10L, 1); - move backwards 10 bytes from the current position
EOF = -1. NULL = 0
Text Files and Binary Files:
A text file contains only textual information like alphabets, digits and special
symbols. A binary file is merely a collection of bytes. We can open a file in binary
mode use rb, wb, ab modes in place of r, w, a etc. Defualt mode is text mode so we
no need to write rt, at, wt etc.
In binary file there is no new line character, EOF.
In text mode the value 3865 occupies 4 bytes where as in binary mode only 2
bytes.
DATA STRUCTURES
Data structure is a study of different methods of organizing the data and
possible operations on these structures.
Data structures are classified into 2 types
1) Linear organize the data in a linear sequence like elements in an array.
Ex: array, stack, queue
2) Non-linear - organize the data in a non-linear fashion.
Ex: trees, graphs
The complexity of algorithms in terms of time and space is specified by O
(spelled by Big-Oh) notation.
A function f is a complexity of order at most g(n), written with big-oh notation as
f=O(g), if there exist a positive constant c and a positive integer n 0 such that
| f(n) | c.|g(n)|
26
The usage of O notation is very simple. For example, if the time or memory required to
execute an algorithm to N (N is total number of elements), we write the algorithm
complexity is O(N). The constants factors do not affect the complexity. For example
O(2N) = O(N).
27