Anda di halaman 1dari 36







1. Basics of programming fundamentals 03

2. Functions and Pointers 09

3. Pre-processor 11

4. Arrays 12

5. String Functions 14

6. Structures 15

7. I/O Function 17

8. Files 19

9. Dynamic Memory Allocation 21

10. Sorting Techniques 23

11. Sample programs 27



• cc• c  c

cc cc
 c ! c"  
c %cc

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.

c ' c  (

Problem solving is a creative process. It is an act of defining a problem, determining the cause of the
problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a

)cc cc  c

( ( c
c  c ( %c

The various steps involved in Program Development are:

a. Defining or Analyzing the problem e. Compiling and Running the Program

b. Design (Algorithm) f. Testing and Debugging

c. Coding g. Maintenance

d. Documenting the program

*c+,c c-c - cc ' %c

Tasks in defining a problem:

Specifying the input requirements.

Specifying the output requirements and

Specifying the processing requirements.

c c,cc 
cc  %c

A design is the path from the problem to a solution in code. Program Design is both a product and a
process. The process results in a theoretical framework for describing the effects and consequences
of a program as they are related to its development and implementation.


An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered

sequence of well-defined and effective operations which, when carried out for a given set of initial

conditions, produce output, and terminate in a finite time. The term ͞ordered sequence͟ specifies,

after the completion of each step in the algorithm, the next step must be unambiguously defined.
An algorithm must be: Definite, Finite, Precise and Effective and Implementation independent ( only
for problem not for programming languages).

c  c! %c

Pseudo code is an informal high-level description of an algorithm that uses the structural
conventions of programming languages, but omits language-specific syntax. It is an outline of a
program written in English or the user's natural language.

c$ ,c! %c  
cc -' c  %c

Flowchart is a diagrammatic representation of an algorithm. It uses different symbols to represent

the sequence of operations, required to solve a problem. It serves as a blueprint or a logical diagram
of the solution to a problem.

An algorithm expressed in programming languages is called Program. Writing a program is called
Coding. The logic that has been developed in the algorithm is used to write the program.

c !
cc c$c !
cc  %c

Documentation explains how the program works and how to use the program. Documentation can
be of great value, not only to those involved in maintaining or modifying a program, but also to the
programmers themselves. Details of particular programs, or particular pieces of programs, are easily
forgotten or confused without suitable documentation.
Documentation comes in two forms:
* External documentation, which includes things such as reference manuals, algorithm descriptions,
flowcharts, and project workbooks
* Internal documentation, which is part of the source code itself (essentially, the declarations,
statements, and comments)

c c$c!

cc  %c
Compilation is a process of translating a source program into machine understandable form. The
compiler is system software, which does the translation after examining each instruction for its
correctness. The translation results in the creation of object code. After compilation, Linking is done
if necessary. Linking is the process of putting together all the external references (other program
files and functions) that are required by the program. The program is now ready for execution.
During execution, the executable object code is loaded into the computer͛s memory and the
program instructions are executed.


Testing is the process of executing a program with the deliberate intent of finding errors. Testing is
needed to check whether the expected output matches the actual output. Program should be tested
with all possible input data and control conditions. Testing is done during every phase of program
development. Initially, requirements can be tested for its correctness. Then, the design (algorithm,
flow charts) can be tested for its exactness and efficiency. Structured walk through is made to verify

the design.
c '

Debugging is a process of correcting the errors. Programs may have logical errors which cannot be
caught during compilation. Debugging is the process of identifying their root causes. One of the ways
to ensure the correctness of the program is by printing out the intermediate results at strategic
points of computation. Debugging is the hardest part of programming because of improper

$$ !c',c '
c c 

Testing means detecting errors. Debugging means diagnosing and correcting the root causes.

Computer Programming is an art of making a computer to do the required operations, by means of
issuing sequence of commands to it.
/cc cc- c$c  
c  %c

There are two major types of programming languages:

Low Level Languages and High Level Languages.

c %c

C is a programming language developed at AT & T͛s Bell Laboratories of USA in 1972. It was designed
and written by a man named Dennis Ritchie. It is often know as middle level language as it inherits
both the features of high level and low level language.

0cc cc! !

! c$c!c  %c

Characteristics of C Language
The increasing popularity of C is due to its various desirable qualities:
*C language is well suited for structured modular programming.
* C is a robust language with rich set of built-in functions and operators.
* C is smaller which has minimal instruction set and programs written in C are efficient and fast.
* C is highly portable (code written in one machine can be moved to other).
* C is highly flexible.
* C allows access to the machine at bit level (Low level (Bitwise) programming).
* C supports pointer implementation - extensive use of pointers for memory, array, structures and

1cc c!  c !c 3!%c

Escape sequences are non printable characters, which begin with backward slash and followed by
one or more special characters. The frequently used escape sequences are given below:
Horizontal tab (\t) Form feed (\f)
Vertical tab (\v) Back Space (\b)
Carriage return (\r) Back Slash (\\)
New line (\n) Null (\0)


cc! %c
A constant is an entity that doesn͛t change. A constant in C refers to the fixed values that do not
change during the execution of a program.
There are two types of constants:
Symbolic constants and Constant variables, also called read-only variables.

&c+,c-c- c$c!  c c %cc c-%c

There are mainly two types of constants

a. Primary (integer, float, char)

b. Secondary (array, pointer, structure, union)

cc c4
' c

Variable is a named memory location. It can store one value at a time. Every time new value is
assigned, the old value is overwritten

c -c

Data types are used to indicate the type of value represented or stored in a variable, the number of
bytes to be reserved in memory, the range of values that can be represented in memory, and the
type of operation that can be performed on a particular data item.

cc c56-c, 7c-c!8c,c c6-c, c c(
' 8 c%c

Keywords are the words whose meaning has already been explained to the C compiler (or in a broad
sense to the computer). 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.



Identifiers are names given to various programming elements such as variables, constants, and
functions. It should start with an alphabet, followed by the combinations of alphabets and digits. No
special character is allowed except underscore (_). An Identifier can be of arbitrarily long. Some
implementation of C recognizes only the first eight characters and some other recognize first 32

&/c+,c-cc$c6-, c c c
c c %cc cc
$$ c!  c  !  c
' c
c %c

There are 32 keywords available in C language. The decision control statements are: if statement, if-
else statement and the conditional operator.

&cc cc
$$ c  c(
' c
The following are the different operators available in C:
Arithmetic operators Assignment operators
Relational operators Unary operators

Logical operators Bitwise operators


cc5  c$c ! !7%c

Operator Name Association
( ) [ ] -> . Parentheses, Index, member access operators Left to Right
! ʹ sizeof()
(Typecast) * & Logical NOT, unary minus, indirection, address Right to Left
++ -- Increment and decrement operators. Right to Left
*/% Multiplicative operators. Left to Right
+- Additive operators. Left to Right
< > <= >= Inequality comparators. Left to Right
== != Equality comparators Left to Right
&& Logical AND. Left tot Right
|| Logical OR. Left to Right
?: Conditional. Right to Left
= op= Assignment. Right to Left
, Comma Left to Right


C provides a mechanism for allowing the programmer to change the default data type of a given
expression. This is called Typecasting. Typecasting allows a variable to behave like a variable of
another type.
C provides two types of type conversions: Implicit and Explicit type conversions.

)2c c
$$ c•c  c

The if statement has three basic forms: Simple if-else, Nested if and if-else if ladder.

c c!

Whenever the expression with the operators && and || are evaluated, the evaluation process stops
as soon as the outcome, true or false is known.

  !-c$c  %c

  c -c

! Logical NOT
*/% Arithmetic and modulus
+- Arithmetic
< > <= >= Relational
== != Relational
&& Logical AND
|| Logical OR
= Assignment



 c  c"  -c  #%cc
 c - %c
It is shortened form of if-statement and its syntax:

Expression 1? Expression 2 : expression 3

)*cc cc
$$ c- c$c c!  c
' c
c %c

There are 3 loop control instructions. Those are

1.c For
2.c While
3.c Do...while

).c+,c  cc c, 6%c

The loop (loop control instruction) involves repeating some portion of the program either a specified
number of times or until a particular condition is being satisfied.

cc c$c9c %c

When breakcis encountered inside any loop, control automatically passes to the first statement after
the loop. A break is usually associated with an if.

cc c$c!
c %c

If we want to take the control to the beginning of the loop, bypassing the statements inside the loop,
which have not yet been executed. The keyword continue allows us to do this. When continuec is
encountered inside any loop, control automatically passes to the beginning of the loop. A continuec
is usually associated with an if.

$$ !c',cc -c!   c c cc
c!   c %c

If the condition of the loop is tested before the control enters into the loop then it is called entry
control loop (While)and if the condition is tested at exit then it is exit controlled loop(do-while).

c ,
!c %c

The control statement that allows us to make a decision from the number of choices is called a
switch, or more correctly a switch-case-default

cc c$c' 6c c
c ,

If the break is not used in a case statement the control will not come out of the switch and it goes
executing the following cases till it encounters a break otherwise it all the statements in the switch.

cc %c

Takes the control where ever you want, is done by using goto statement. Better don͛t use it.

cc cc $  c

The big problem with goto͛s is that when we do use them we can never be sure how we got to a

certain point in our code. They obscure the flow of control.

*)cc  cc
c %c

The exit ( )cfunction is a standard library function which terminates the execution of the program.

 • c c • c


A function is a self-contained block of statements that perform a coherent task of some kind.

*.c-c c,c c$!

We use functions because
1.c Writing functions avoids rewriting the same code over and over.
2.c Using functions it becomes easier to write programs and keep track of what they are doing.
If the operation of a program can be divided into separate activities, and each activity placed in a
different function, then each could be written and checked more or less independently.

c  cc!(-c ccc$!
The mechanism used to convey information to the function is the ͚argument͛.

*cc cc
$$ c  c
' %c
There are two parameter passing mechanism available. Those are: Call by value and Call by address

cc c$c  c %c

The return statement serves two purposes.

1. On executing the return statement it immediately transfers the control back to the calling
2. It returns the value present in the parentheses after return, to the calling program. In the above
program the value of sum of three numbers is being returned

cc $ c  c-c-c$!

The default return type of any function is int.

c! c'-c( c!
Whenever we called a function and passed something to it we have always passed the ͚values͛ of
variables to the called function. Such function calls are called ͚calls by value͛. By this we mean, on
calling a function we are passing values of variables to it.


Pointer is a variable which holds the address of another variable.

c !


A function is called ͚recursive͛ if a statement within the body of a function calls the same function.
cc  c !

Take a function as below

Void main()
Int n,p;
Int reverse (int);/* function prototype*/
Set of statements;
n=reverse (p); /* function is called with actual parameters*/
Set of statements;

Int reverse(int n)/* function heading with formal parameters*/

Set of statements;
Return(x); /* control goes back to calling function*/

1. In the above code snippet main () is calling function because the function reverse is called and
reverse is called function
2. If a function (here reverse ()) is written below main () its prototype must be included in the calling
function otherwise it should be declared globally so that the function call does not raise any error. It
informs the compiler about the function.
3. The parameters present in the function call are called actual parameters and the parameters
which are there in function heading are formal parameters
4. Return statement in function is the last executable statement. If we write any statements after if
those are not going to be executed
5. Return type of a function is the type of value that is returned by the function in the present
example int is the return type because reverse function returns int.

$$ !c',c! c'-c( c c! c'-c $ !c"  #%c
The difference between call by value and call by address is
1. The changes made to formal parameters are not reflected in the calling function in the call by
value. Where as in the call by address changes will be reflected
2. By using call by value at most we can change a single value by return statement from called
function where as by the use of call by address we can change many values in the calling function
$$ !cc
:c  c c c c- %c
Short is at least 2 bytes big, long is at least 4 bytes big, short is never bigger than int͛s and int͛s are
never bigger than longs.

$$ !c',c
c c

Declaring an integer as unsigned almost doubles the size of the largest possible value that it can
otherwise take.

.cc  cc  c!  c c %c

A storage class tells us:
1. Where the variable would be stored.

2. What will be the initial value of the variable, if initial value is not specifically assigned? (i.e. the
default initial value).

3. What is the scope of the variable; i.e. in which functions the value of the variable would be

4. What is the life of the variable; i.e. how long would the variable exist.

.0cc cc
$$ c!   c(
' c
c %c

There are 4 storage classes available in c. Those are

Automatic storage class (local) (default value is garbage)

Register storage class (default value is garbage)
Static storage class (default value is zero)
External storage class (global) (default value is zero)

.1cc c,c cc 

' %c

Use static storage class only if you want the value of a variable to persist between different function

/2cc c,c 
'  %c
(cc  c
Use register storage class for only those variables that are being used very often in a program. A
typical application of register storage class is loop counters, which get used a number of times in a
c c
cc c !  %c

It is a program that processes our source program before it is passed to the compiler.

c$c ; !  %c
Pre-processor expands Macro expansion and File inclusion.

c c !  c
# is called pre processor directive. Its job is to expand macros and files (headers)

cc! %c

Macro is a named constant. It is defined using #define

Ex. # define A 5
Where ever A is found in the program 5 is substituted there

We can have macro with arguments

Ex. #define AREA(x) (3.14 * x * x)
Macro call leads to substitution

$$ !c',c5!7c c<!=%c

#include "goto.c" This command would look for the file goto.c in the current
directory as well as the specified list of directories as mentioned
in the include search path that might have been set up.

#include <goto.c> This command would look for the file goto.c in the specified list
of directories only.

cc  !c%c

They include search path is nothing but a list of directories that would be searched for the file being
included. Different C compilers let you set the search path in different manners. If you are using
Turbo C/C++ compiler then the search path can be set up by selecting ͚Directories͛ from the
͚Options͛ menu. On doing this a dialog box appears. In this dialog box against ͚Include Directories͛
we can specify the search path.

/c• c c-c (

c!c cc  c !
c$ c cc

Yes we can. By using #pragma directive we can do it

Void fun1 ( );
Void fun2 ( );
#pragma startup fun1
#pragma exit fun2
main ( )
printf (͞\nInside maim͟);
void fun1 ( )
printf (͞\nInside fun1͟);
void fun2 ( )
printf (͞\nInside fun2͟);

Output :
Inside fun1
Inside main
Inside fun2



cc c$ c
cc -%c
If there are situations in which we would want to store more than one value at a time in a single
Ex. For example, suppose we wish to arrange the percentage marks obtained by 100 students in
ascending order. In such a case we have two options to store these marks in memory:
1. Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each
variable containing one student͛s marks.
2. Construct one variable (called array or subscripted variable) capable of storing or holding all the
hundred values.
Obviously, the second alternative is better. A simple reason for this is, it would be much easier to
handle one variable than handling 100 different variables.

cc -%c

An array is a collection of similar elements. The first element in the array is numbered 0, so the last
element is 1 less than the size of the array. An array is also known as a subscripted variable. Before
using an array its type and dimension must be declared.

2c• c c-c'  -c!!6c(

' c$ c - c

No, there is no boundary checking for arrays in c.

! cc! c'-c( c c! c'-c $ !c,
c - c

In the call by value we pass values of array elements to the function, whereas in the call by reference
we pass addresses of array elements to the function.

c !
 ccc -%c

Ex. Int a [10];

Int *p;
p [1] is same as a [1]
Here in the above snippet p is pointer and it is pointing to an array called a; we can access the whole
array with the help of the pointer

)c+,c c,c cc

c -ccc$!
Just passing the address of the zeroth element of the array to a function is as good as passing the
entire array to the function. It is also necessary to pass the total number of elements in the array


 c -%c
The two-dimensional array is also called a matrix.
Ex. Int a [4] [5];
It is two dimensional arrays of 4 rows and 5 columns
Indirectly two dimensional arrays is nothing but collection of 1D arrays

cc -c$c
Since a pointer variable always contains an address, an array of pointers would be nothing but a
collection of addresses. The addresses present in the array of pointers can be addresses of isolated
variables or addresses of array elements or any other addresses. All rules that apply to an ordinary
array apply to the array of pointers as well.

cc)c -%c
A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has
three elements.

cc cc
 cc!c'c cc

Addition of two pointers, Multiplication of a pointer with a constant and Division of a pointer with a

$$ c  
3 c
c c

Bubble sort, selection sort, insertion sort, quick sort, merge sort and heap sort.

• c • c

A string constant is a one-dimensional array of characters terminated by a null (͚\0͛). For example,
char name [ ] = {͚H͛, 'A', 'E', 'S', 'L', 'E', 'R', ' \0͛} ;
char name [] =͟UGY͟ /* \0 is appended by c*/
The terminating null (͚\0͛) is important, because it is the only way the functions that work with a
string can know where the string ends.

cc$ c !
 ccc  cc
 cccc ! %c
The %s used in printf ( ) is a format specification for printing out a string. The same specification can
be used to receive a string from the keyboard.

0cc cc
$$ c c $
' c
c %c

c  c
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another

strcpy Copies a string into another

strncpy Copies first n characters of one string into another
strcmp Compares two strings

strncmp Compares first n characters of two strings

strcmpi Compares two strings without regard to case ("i" denotes that this
function ignores case)
stricmp Compares two strings without regard to case (identical to strcmpi)

strnicmp Compares first n characters of two strings without regard to case

strdup Duplicates a string

strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string

0&c-c c,c c  ! %c

A structure contains a number of data types grouped together. These data types may or may not be
of the same type.

c  ! c

Structure is collection of variables of different data type name under single entity.

0*cc cc  c !
c  ! %c

Example 1:

Struct emp

Int empno;

Char ename [20];

Float sal;


This is called structure definition. Memory is not allocated to the members when the structure is

Struct emp a; a is structure variable of tag emp;

Memory is allocated to the members when the structure is instantiated.

In the above structure the total memory allocated to it is 2+20+4 i.e. 26

Example 2:

We can instantiate a structure at the time of definition it self

Struct emp {

Int empno;

Char ename [20];

Float sal;

} a, b, c;

a, b, c are structure variables

Example 3:

See these examples to have a better idea about declarations

struct book
char name;
float price;
int pages;
struct book b1, b2, b3;
Is same as...

struct book
char name;
float price;
int pages;
} b1, b2, b3;
Or even...

struct {
char name;
float price;
int pages;
} b1, b2, b3;

0.c-c cc  !  c $

 c ' -%c

Usually structure type declaration appears at the top of the source code file, before any variables or
functions are defined. In very large programs they are usually put in a separate header file, and the
file is included (using the pre-processor directive #include) in whichever program we want to use this
structure type.

0/c+,c c,c!! c  ! c' %c

Let us take the structure

struct book {
char name [20];

float price;
int pages;
} b1, b2, b3;

B1 is the name of the structure

We use dot operator to access structure members

Syntax is
Structure name. field name;

cc -c$c  ! %c

struct book {
char name [20];
float price;
int pages;
} b [100];
B is array of structures where each element is nothing it is structure.
Some times like this a lot of variables (b1 to b100 for storing data about hundred books) needed to
be handled. Therefore he allowed us to create an array of structures; an array of similar data types
which themselves are a collection of dissimilar data types.

00c c,c
c( c$c  ! cc c  ! %c

Yes we can assign for example a, b are two structures we can do a=b provided both structures
belong to the same tag

01c c,c(c  ! c,

cc  ! %c

We can use structure within a structure. But inner structure definition must be written in above
outer structure.

12c•$cc  ! c
c !
 :c,c c,c c' %c
By using -> operator we have to operate member fields of structure.

1c c-c  cc  ! ccc$!

c! c'-c( c c! c'-c  %c

We can send a structure to a function by both the mechanisms.

cc  $c $ 
 c  ! %c

If structure has one of its members type as its own type then it is called self referential structure.

• c • c

1)cc cc
$$ c•c$!
' %c

There are numerous library functions available for I/O. These can be classified into three broad
Console I/O - Functions to receive input from keyboard and write
functions output to VDU.

File I/O - Functions to perform I/O operations on floppy disk or

functions hard disk.

c!  %c
The screen and keyboard together are called a console.

1.c+,c  c 
"#c, 6%c
The sprintf( ) function works similar to the printf( ) function except for one small difference. Instead
of sending the output to the screen as printf( ) does, this function writes the output to an array of

1/c+,c  cc !$"#c, 6%c

It allows us to read characters from a string and to convert and store them in C variables according
to specified formats. The sscanf( ) function comes in handy for in-memory conversion of characters
to values. You may find it convenient to read in strings from a file and then extract values from a
string by using sscanf( ). The usage of sscanf( ) is same as scanf( ), except that the first argument is
the string from which reading is to take place.

$$ !c',c!"#c c!"#%c
These functions return the character that has been most recently typed. The ͚e͛ in getche( ) function
means it echoes (displays) the character that you typed to the screen. As against this getch( ) just
returns the character that you typed without echoing it on the screen.

$$ !c',c! "#c c$! "#%c
getchar( ) works similarly and echo͛s the character that you typed on the screen, but unfortunately
requires Enter key to be typed following the character that you typed. The difference between
getchar( ) and fgetchar( ) is that the former is a macro whereas the latter is a function. Here is a
sample program that illustrates the use of these functions.


A "union declaration" specifies a set of variable values and, optionally, a tag naming the union. The
variable values are called "members" of the union and can have different types. Unions are similar to
"variant records" in other languages.

A variable with union type stores one of the values defined by that type. The same rules govern
structure and union declarations. Unions can also have bit fields.

Members of unions cannot have an incomplete type, type void, or function type. Therefore
members cannot be an instance of the union but can be pointers to the union type being declared.

A union type declaration is a template only. Memory is not reserved until the variable is declared.
If a union of two types is declared and one value is stored, but the union is accessed with the other
type, the results are unreliable. For example, a union of float and int is declared. A float value is
stored, but the program later accesses the value as an int. In such a situation, the value would
depend on the internal storage of float values. The integer value would not be reliable.

22cc cc

c c  ! %c

Structures and unions share the following characteristics:

3c Their members can be objects of any type, including other structures and unions or arrays. A
member can also consist of a bit field.
3c The only operators valid for use with entire structures and unions are the simple assignment
(=) and sizeof operators. In particular, structures and unions cannot appear as operands of
the equality ( == ), inequality (!=), or cast operators. The two structures or unions in the
assignment must have the same members and member types.
3c A structure or a union can be passed by value to functions and returned by value by
functions. The argument must have the same type as the function parameter. A structure or
union is passed by value just like a scalar variable; that is, the entire structure or union is
copied into the corresponding parameter.

$$ !c',c  ! c cc

The union is a structure. The main difference between structure and union is, the size of the union is
equal to the size of the largest member of the union where as size of the structure is the sum of the
size of all members of the structure. And one more thing is that, at a time we can use one member
of the union.

2&c+,c c-ccc$

Before we can read (or write) information from (to) a file on a disk we must open the file. To open
the file we have called the function fopen( ).

2)c+,c c-c  c$

To read the file͛s contents from memory there exists a function called fgetc( ).

ch = fgetc ( fp ) ;
fgetc( ) reads the character from the current pointer position, advances the pointer position so that
it now points to the next character, and returns the character that is read, which we collected in the
variable ch.

2*cc  cc$!"#c %c

The fputc( ) function is similar to the putch( ) function, in the sense that both output characters.
However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. cc
$$ c$
c  %c

Read(r), write(w), append(a) modes

And r+, w+, a+ we can do read, write, append with these three.

2/c+,c c-c!  cc$


By using fclose() we can close a opened file.


A binary file is merely a collection of bytes. This collection might be a compiled version of a C
program (say PR1.EXE), or music data stored in a wave file or a picture stored in a graphic file. A very
easy way to find out whether a file is a text file or a binary file is to open that file in Turbo C/C++. If
on opening the file you can make out what is displayed then it is a text file, otherwise it is a binary

20c-c c c$


The only function that is available for storing numbers in a disk file is the fprintf( ) function.

Text and characters are stored one character per byte, as we would expect. Numbers are stored as
strings of characters.

21c-c c,cc$ cc'


If large amount of numerical data is to be stored in a disk file, using text mode may turn out to be
inefficient. The solution is to open the file in binary mode and use those functions (fread( ) and
fwrite( ) which are discussed later) which store the numbers in binary format. It means each number
would occupy same number of bytes on disk as it occupies in memory.

2c-c$  c c$,

c c c

Any database management application in C must make use of fread( ) and fwrite( ) functions, since
they store numbers more efficiently, and make writing/reading of structures quite easy. Note that
even if the number of elements belonging to the structure increases, the format of fread( ) and
fwrite( ) remains same.

c ,
 "#:$ "#:$ 6"#c

The rewind( ) function places the pointer to the beginning of the file, irrespective of where it is
present right now.
The fseek( ) function lets us move the pointer from one record to another.

fseek ( fp, -recsize, SEEK_CUR ) ;

If we wish to know where the pointer is positioned right now, we can use the function ftell( ). It
returns this position as a long int which is an offset from the beginning of the file. The value returned
by ftell( ) can be used in subsequent calls to fseek( )

&cc c! c
c  %c

The arguments that we pass on to main( ) at the command prompt are called command line

arguments. The function main( ) can have two arguments, traditionally named as argc and argv. Out
of these, argv is an array of pointers to strings and argc is an int whose value is equal to the number
of strings to which argv points. When the program is executed, the strings on the command line are
passed to main.

)cc cc'
c  %c


~ One͛s complement
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive OR)

*cc c  %c

An enumeration consists of a set of named integer constants. An enumeration type declaration gives
the name of the (optional) enumeration tag and defines the set of named integer identifiers (called
the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable with
enumeration type stores one of the values of the enumeration set defined by that type.

Variables of enum type can be used in indexing expressions and as operands of all arithmetic and
relational operators. Enumerations provide an alternative to the #define preprocessor directive with
the advantages that the values can be generated for you and obey normal scoping rules.

In ANSI C, the expressions that define the value of an enumerator constant always have int type;
thus, the storage associated with an enumeration variable is the storage required for a single int
value. An enumeration constant or a value of enumerated type can be used anywhere the C
language permits an integer expression.


enum DAY /* D efines an enumeration type */

saturday, /* Names day and declares a */
sunday = 0, /* variable named workday with */
monday, /* that type */
wednesday, /* wednesday is associated with 3 */
} workday;
The value 0 is associated with saturday by default. The identifier sunday is explicitly set to 0. The
remaining identifiers are given the values 1 through 5 by default.

> • c >c • c

c -
!c  c !
A storage allocation technique in which the storage assigned to a computer program varies during program
execution, based on the current needs of the program and of other executing programs. c

!c -c !

The process of allocating memory at run time is known as dynamic memory allocation.

cc cc -

!c -c !

Many languages permit a programmer to specify an array size at run time. Such languages have the
ability to calculate and assign during executions, the memory space required by the variables in the
program. But c inherently does not have this facility but supports with memory management
functions, which can be used to allocate and free memory during the program execution. The
following functions are used in c for purpose of memory management.

Function Task
Malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of
allocated space
Calloc Allocates space for an array of elements initializes them to zero and returns a
pointer to the memory
Free Frees previously allocated space
Realloc Modifies the size of previously allocated space.

c -c !
c ! c

According to the conceptual view the program instructions and global and static variable in a
permanent storage area and local area variables are stored in stacks. The memory space that is
located between these two regions in available for dynamic allocation during the execution of the
program. The free memory region is called the heap. The size of heap keeps changing when program
is executed due to creation and death of variables that are local for functions and blocks. Therefore
it is possible to encounter memory overflow during dynamic allocation process. In such situations,
the memory allocation functions mentioned above will return a null pointer.

1c+,cc !cc' !6c$c -%c

A block of memory may be allocated using the function malloc. The malloc function reserves a block
of memory of specified size and returns a pointer of type void. This means that we can assign it to
any type of pointer. It takes the following form:


ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory
with size byte-size.

Example: x=(int*)malloc(100*sizeof(int));

&2c+,cc !c 
 c' !6 c$c -%c

Calloc is another memory allocation function that is normally used to request multiple blocks of

storage each of the same size and then sets all bytes to zero. The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of elements size bytes. All
bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there
is not enough space a null pointer is returned.

&c+,cc   cc  c !%c

Compile time storage of a variable is allocated and released by the system in accordance with its
storage class. With the dynamic runtime allocation, it is our responsibility to release the space when
it is not required. The release of storage space becomes important when the storage is limited.
When we no longer need the data we stored in a block of memory and we do not intend to use that
block for storing any other information, we may release that block of memory for future use, using
the free function.


ptr is a pointer that has been created by using malloc or calloc.

&&c+,cc  cc
?c$c ! c -%c

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both
the situations we can change the memory size already allocated with the help of the function
realloc. This process is called reallocation of memory. The general statement of reallocation of
memory is :


This function allocates new memory space of size newsize to the pointer variable ptr ans returns a
pointer to the first byte of the memory block. The allocated new block may be or may not be at the
same region.

• c + •c


A sorting algorithm is an algorithm that puts elements of a list in a certain order.

&*c c
$$ c- c$c  

In this table, Ý is the number of records to be sorted. The columns "Average" and "Worst" give the
time complexity in each case, under the assumption that the length of each key is constant, and that
therefore all comparisons, swaps, and other needed operations can proceed in constant time.
"Memory" denotes the amount of auxiliary storage needed beyond that used by the list itself, under
the same assumption. These are all comparison sorts.

Name Average Worst Memory

Bubble sort O(n2) O(n2) O(1)
Selection sort O(n2) O(n2) O(1)

Inserting sort O(n2) O(n2) O(1)

Merge sort O(n logn) O(n logn) O(n)

Quick sort O(n logn) O(n2), O(log n)


e cs  c cc cc 1c


ñ  c sc c s 

  c c ss cc e
c  c s c  c
c sc sec c c e c
scecec ec c 
c s sc c
ec ec  c
ec  cse c  c c esc
ec  s c c
eee s c c c
ec  s csc e e c
ecsecc cs sc
ec cc escc
sc  ce c
  c c j ce ceee sc c
ecec c
ec cse c c
ecs sc  c
ec  s c ceee sc
ee c  c c s sc
vec cc ec c
ec  s c  ssc 
ec sec
c sc

e ce c c sc eyc sec e ce c c ec c c s
yc e e c v   ccc  c s c  sc yc
ve c
ec  e c c  e  c c
ec  ssc  ec c c  e  c  ssesc  sc ve ec c sec c
 s cc sec ec

S e-y-s ece ec

e csc ec
ec yc ce sc5c1c4c2c8c cs c
ec yc ces ce c c
 e es ce cscecs c  
cce c
cs eceee sc  eccc ec
ecc ec

F s c ss c
c.cc4c2c8cc cc.c4c2c8cc e ec  
cc esc
ec  s c ceee sc cs sc

c1c.c*c2c8cc c1c*c.c2c8cc
c1c4c.c&c8cc c1c4c&c.c8cc
c1c4c2c.c0cc c1c4c2c.c0cccscec
eseceee sc ec  e ycc e c  
 cs c
Secc ss c
cc*c2c5c8cc cc*c2c5c8cc
c1c*c&c5c8cc c1c&c*c5c8cc
c1c2c*c.c8cc c1c2c*c.c8cc
c1c2c4c.c0cc c1c2c4c.c0cc
ec ycsc  e ycs ec c c  
cesc cc c cscce ec
ec ssc
 c ycs c cc cscs ec

 c ss c
cc&c4c5c8cc cc&c4c5c8cc
c1c&c*c5c8cc c1c&c*c5c8cc
c1c2c*c.c8cc c1c2c*c.c8cc
c1c2c4c.c0cc c1c2c4c.c0cc
F yc
ec ycscs ec c
cc c e  ec

c  cecs c

 ce eceS cc cs c cs ec escce ec s c

cc  ce c
ccc1c ce
c c
ccccc  ce c
c cc+c1c c
ccccccc c[cjc-1cc]c>c[cjc]c
cccccccccs c[cjc-c1]cc[cjc]cc
cccccccec c
cccccec  c

end for
end procedure

c !
c  c

a  Ý    is a simple sorting algorithm that improves on the performance of bubble sort. It
works by first finding the smallest element using a linear scan and swapping it into the first position
in the list, then finding the second smallest element by scanning the remaining elements, and so on.
Selection sort is unique compared to almost any other algorithm in that its running time is not
affected by the prior ordering of the list: it performs the same number of operations because of its
simple structure. Selection sort requires (Ý - 1) swaps and hence Ⱥ(Ý) memory writes. However,
Selection sort requires (Ý - 1) + (Ý - 2) + ... + 2 + 1 = Ý(Ý - 1) / 2 = Ⱥ(Ý2) comparisons. Thus it can be
very attractive if writes are the most expensive operation, but otherwise selection sort will usually
be outperformed by insertion sort or the more complicated algorithms.

Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64

Pseudo code for selection sort:

for i і 0 to n-2 do
min і i
for j і (i + 1) to n-1 do
if A[j] < A[min]
min і j
swap A[i] and A[min]

c  c

•Ý Ý   is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted
lists, and often is used as part of more sophisticated algorithms. It works by taking elements from
the list one by one and inserting them in their correct position into a new sorted list. In arrays, the
new list and the remaining elements can share the array's space, but insertion is expensive, requiring
shifting all following elements over by one. The insertion sort works just like its name suggests - it
inserts each item into its proper place in the final list. The simplest implementation of this requires
two list structures - the source list and the list into which sorted items are inserted. To save memory,
most implementations use an in-place sort that works by moving the current item past the already
sorted items and repeatedly swapping it with the preceding item until it is in place. Shell sort is a
variant of insertion sort that is more efficient for larger lists. This method is much more efficient
than the bubble sort, though it has more constraints.

Pseudo code of insertion sort:

insertionSort(array A)
for i = 1 to length[A]-1 do


ccccccccv ec=c[]c
ecjc>=c0c c[j]c>cv ecc
cccccccc[j+1]c=cv ec


 c esc v  ec c

ece sec ce c  e ycs ecs sc c cecs ecs c cs sc
yc c c eve yc c eee sc ec 1c 
c 2c
ec 3c 
c 4c c s c
ec  c
ec  s c
ccec e c
ecsecc c
ece esce c
c c
ec es cs sc c c cs sc c  c
e esc
secs sc c  c csc!c c c s c cs sc ece ec c
ec  cs ecs c c
scesc ec
e ec
ec  s c
csc escec cve yc ecs scec sec sc s -c sec
c ecscÝccÝc

"# e c

seccec  ce ecs c

c ce es c

ccccv c
ce c 
c es c
cccc ce
cccccccc e  cc
ccccv cec=ce
cccc  ce c
c#cccc cec
ccccccccc c#c ce c
cccc  ce c
c#ccc e cec
ccccccccc c#c c 
cccce c=ce es e c

right = mergesort(right)
result = merge(left, right)
return result

c+c  c

Heap sort is a much more efficient version of selection sort. It also works by determining the
largest (or smallest) element of the list, placing that at the end (or beginning) of the list,
then continuing with the rest of the list, but accomplishes this task efficiently by using a data
structure called a heap, a special type of binary tree. Once the data list has been made into
a heap, the root node is guaranteed to be the largest element. When it is removed and
placed at the end of the list, the heap is rearranged so the largest element remaining moves
to the root. Using the heap, finding the next largest element takes O(log n) time, instead of
O(n) for a linear scan as in simple selection sort. This allows Heap sort to run in O(n log n)

!6c  c

Quick sort is a divide and conquer algorithm which relies on a partition operation: to
partition an array, we choose an element, called a pivot, move all smaller elements before
the pivot, and move all greater elements after it. This can be done efficiently in linear time
and in-place. We then recursively sort the lesser and greater sub lists. Efficient
implementations of quick sort (with in-place partitioning) are typically unstable sorts and
somewhat complex, but are among the fastest sorting algorithms in practice. Together with
its modest O(log n) space usage, this makes quick sort one of the most popular sorting
algorithms, available in many standard libraries. The most complex issue in quick sort is
choosing a good pivot element; consistently poor choices of pivots can result in drastically
slower (O(n²)) performance, but if at each step we choose the median as the pivot then it
works in O(n log n).

Pseudo code for quick sort:

function partition(array, left, right, pivotIndex)

pivotValue := array[pivotIndex]
swap array[pivotIndex] and array[right] ¦¦     Ý
storeIndex := left
for i from left to right о 1
if array[i] $ pivotValue
swap array[i] and array[storeIndex]
storeIndex := storeIndex + 1
swap array[storeIndex] and array[right] ¦¦      Ý   
return storeIndex


c !

long double facto(int n)
void main()
int n;
printf("enter number\n");

&c( c$cc' c



void main()

int sum=0,x,n;


printf("enter a value of n: ");




sum=sum*10 + x;




)c   c' c



void main()

int s,sum=0,n,a;


printf("\nEnter the no.");








printf("\nThe an armstrong no.",a);


printf("\nNot an armstrong no");



*c( c$cc 


void main()

char a[10];

int i,j,count=0;


printf("Enter the first string:");







!c$ cc 






void main()

int f1=0,f2=1,f3,n,i=3;


printf("Enter the number greater than 2: ");










c cc
(c' c
c cc



void main()

int n,i=1,count=0;


printf("enter a number greater than two");



printf("\nre-enter a value i.e greater than 1\n");






printf("the number is a prime number");


printf("the number is not a prime number");



c' cccc



void main()

int n,i=1,c=0,x,count=0;


printf("enter any number");











printf("\n Number of prime numbers is %d", count);


1c+,cc  c c
cc) )c



void main()

int i,j,a[3][3];


printf("Enter the values in the matrix:\n");





printf("\nThe following is the values entered in the matrix:\n");






2c !6c, cc, c cc' c

 c cc



void pal(int i, int j,char s[])

if (s[i]==s[j])


printf("\n Palindrome");



printf("\n not a palindrome");


void main()

char a[20];

int i,l=0;


printf("enter string");






c,c,c' c,
' c



void main()

int a,b;


printf(͞\n Enter the two numbers a and b:͟);

scanf(͞%d%d͟, &a, &b);




printf(͞\n The swapped numbers are a=%d and b=%d͟,a,b);