m3 o Level Programming
m3 o Level Programming
(Module M3:R4)
‘C’ LANGUAGE
Based on
Latest syllabus of NIELIT
TBALAJI PUBLICATION
Triloki Complex, Infront of A.N. Jha Hostel, Allahabad- 211002
Uttar Pradesh
Lectures = 60
Practical/tutorials = 60
Total = 120
Detailed Syllabus
1. Introduction to Programming 04 Hrs.
The Basic Model of Computation, Algorithms, Flow-charts, Programming Languages, Compilation,
Linking and Loading, Testing and Debugging, Documentation
2. Algorithms for Problem Solving 10 Hrs.
Exchanging values of two variables, summation of a set of numbers, Decimal Base to Binary Base
conversion, Reversing digits of an integer, GCD (Greatest Common Division) of two numbers, Test
whether a number is prime, Organize numbers in ascending order, Find square root of a number,
factorial computation, Fibonacci sequence, Evaluate ‘sin x’ as sum of a series, Reverse order of
2
Chapter 1 Introduction to programming
ri
elements of an array, Find largest number in an array, Print elements of upper triangular matrix,
multiplication of two matrices, Evaluate a Polynomial
3. Introduction to ‘C’ Language 04 Hrs.
Character set, Variables and Identifiers, Built-in Data Types, Variable Definition, Arithmetic operators
and Expressions, Constants and Literals, Simple assignment statement, Basic input/output statement,
Simple ‘C’ programs.
4. Conditional Statements and Loops 07 Hrs.
Decision making within a program, Conditions, Relational Operators, Logical Connectives, if
statement, if-else statement, Loops: while loop, do while, for loop, Nested loops, Infinite loops, Switch
statement, structured Programming .
5. Arrays 06 Hrs.
One dimensional arrays: Array manipulation; Searching, Insertion, Deletion of an element from an
array; Finding the largest/smallest element in an array; Two dimensional arrays,
Addition/Multiplication of two matrices, Transpose of a square matrix; Null terminated strings as
array of characters, Standard library string functions
6. Functions 06 Hrs.
Top-down approach of problem solving, Modular programming and functions, Standard Library of C
functions, Prototype of a function: Formal parameter list, Return Type, Function call, Block structure,
Passing arguments to a Function: call by reference, call by value, Recursive Functions, arrays as
function arguments.
7. Storage Classes 03 Hrs.
Scope and extent, Storage Classes in a single source file: auto, extern and static, register, Storage
Classes in a multiple source files: extern and static
8. Structures and Unions 06 Hrs.
Structure variables, initialization, structure assignment, nested structure, structures and functions,
structures and arrays: arrays of structures, structures containing arrays, unions
9. Pointers 06 Hrs.
Address operators, pointer type declaration, pointer assignment, pointer initialization, pointer
arithmetic, functions and pointers, Arrays and Pointers, pointer arrays, pointers and structures,
dynamic memory allocation.
10. Self Referential Structures and Linked Lists 04 Hrs.
Creation of a singly connected linked list, Traversing a linked list, Insertion into a linked list, Deletion
from a linked list
11. File Processing 04 Hrs.
Concept of Files, File opening in various modes and closing of a file, Reading from a file, Writing onto
a file
3
'O' Level Module M3:R4 C-Language
Introduction to
Programming
1.1 THE BASIC MODEL OF COMPUTATION
The Basic model of Computation can be considered as a program
executed step by step following with the instructions given by the user to solve a problem or
program at end. We formally give a set instruction for a program to be executed and it made executed
the program within a certain procedure. Consider a real time event or program i.e. cooking tea where
you need all the prerequisites for making that possible like Tea leaves, sugar, milk or water; after
boiling the tea leaves in the water or milk along with certain amount of sugar you can have tea to be
served in the same way you need all the necessary things for a program like variable to store value,
operators to perform operation following with instructions you can be able to solve a problem at end.
fdlh Hkh ç‚Cye ;k çksxzke dks laiw.kZr% lqy>kus ds fy, gesa LVsi ckbZ LVsi funs'Z kksa dks fØ;kfUor djrs jguk gksxk
rRi'pkr gh ge fdlh leL;k dks lqy>k ikrs gSaA ge fdlh çksxzke dks lksYo djus ds fy, ,d fu;r funs'Z k nsrs gSaA
vkSj ml fu;r funs'Z k ds vuqlkj gh ml çksxzke dks Øeokj rjhds ls lqy>krs gSaA tSls dh fj;y Vkbe bosVa dks gh
mngkj.k ds rkSj ij ysa rks ik,axs dh mu lHkh dk;Z dks fØ;kfUor djus ds fy, gesa ,d fu;r funs'Z k ds vuqlkj gh
fdlh dk;Z dks vatke nsrs gSa pkgs oks funs'Z k Lo;a }kjk gh çsf"kr D;ksa u gksA ;gk¡ uhps daI;wVj çksxzke ls lEcaf/kr dqN
phtsa lanfHkZr dh x;h gS &
We consider the following things while or before computing a program…
Make sure the output of the program then define the prerequisites for that program
Declare the variables for that program and import necessary resources
Form proper syntax of the program as per the procedure
Use necessary functions and methods to get the desired result at end.
1.2 PROCEDURE FOR PROBLEM SOLVING
While solving a problem, a certain procedure is followed as the phases for the program executing and
debugging. There is number of levels involved what they play their role from starting to code a
program to finish a program by executing.
çksxzke dkalsIV dk eryc ;g gS dh fdlh çksxzke dks lksYo djus ds fy,
fu;r rjhds ,oa çkslhtj dh t#jr iM+rh gSA ,slk djus ij ge fdlh
çksxzke dks vklkuh ls fØ;kfUor djus ds lkFk lkFk mls fMcx Hkh dj
ldrs gSaA çksxzke dkalIs V ds varxZr dbZ pj.k gksrs gSa ftuds vius Lo;a ds
fdjnkj gksrs gSa ftudh enn ls ge fdlh çksxkz e dks vklkuh ls fØ;kfUor
djrs gSaA
Step 1: Understanding the Problem
Step 2: Design the Program and Make declarations
Step 3: Write the Code
Step 4: Compile
Step 5: Run the Program
Step 6: Test and Debug the Program
4
Chapter 1 Introduction to programming
ri
5
Algorithm
2.1 INTRODUCTION
An algorithm is any well-defined computational procedure that takes some value, or set of values, as
input and produces some value, or set of values, as output. An algorithm is thus a sequence of
computational steps that transform the input into the output. We can also view an algorithm as a tool
for solving a well-specified computational problem. The statement of the problem specifies in general
terms the desired input/output relationship. The algorithm describes a specific computational
procedure for achieving that input/output relationship.
,YxksfjFke fdlh çksxzke dks iw.kZ djus ;k ç‚Cye dks l‚Yo djus djus ds fy, fu;r funsZ'kksa dk ,d Øe gksrk gSA
,YxksfjFke dks ifjHkkf"kr ;k ç;ksx djus ds fy, fdlh fo'ks"k çdkj dh ySaXost dh vko';drk ugha gksrh cfYd vki bls
lk/kkj.k cksy pky dh Hkk"kk esa gh fMtkbZu dj ldrs gSaA ;g LofuHkZj gksrk gS blfy, bls ç;ksx djus ds fy, fdlh
fo'ks"k daI;wVj ySaXost dh vko';drk ugha gksrhA
2.2 CHARACTERISTICS OF ALGORITHM
Finiteness: In an algorithm each step must be executable in finite amount of time that it terminates
on all allowed inputs. In order to establish a sequence of steps as an algorithm, it should be
established with good fitness.
Definiteness (no ambiguity): Each step of an algorithm means the action to be carried out rigorously
and unambiguously specified for each case.
Inputs: An algorithm has zero or more but only finite, number of inputs.
Output: The requirement of at least one output is obviously essential, because, otherwise
Effectiveness cannot know the solution provided by the algorithm. An algorithm has one or more
outputs.
Finally our target is an algorithm should be effective. This means that each of the operation to be
performed in an algorithm must be sufficiently basic that it can, in principle, be done exactly and in a
finite length of time, by person using pencil and paper. It may be noted that the ‘FINITENESS’
condition is a special case of ‘EFFECTIVENESS’. If a sequence of steps is not finite, then it cannot be
effective also.
fdlh çksxzke esa ,YxksfjFke dk egRo blh ckr ls le> ldrs gSa dh ;g ,d Øeokj ,oa pj.kc) rjhds ls lk/kkj.k Hkk"kk
esa fdlh çksxzke ;k ç‚Cye dks l‚Yo djrk gS ftlls ge çksxzke ds y‚ftd ,oa mls lgh rjhds ls fMtkbZu fd;k tk
ldsA fdlh çksxzke dks dksM djus ls igys dk ;g mldk Vªk;y ekuk tkrk gSA uhps ,YxksfjFke dh fo'ks"krk fMVsy esa Mh
x;h gS &
Chapter 12 File Processing
7
'O' Level M3:R4 C-LANGUAGE
8
Chapter 12 File Processing
djSDVj lsV fdlh çksxzkfeax ySaXost dh Hkk"kk i)fr }kjk igpku djk;k x;k ,d lewg gksrk gS tgk¡ dbZ djSDVj gksrs gSa
ftuds vius vius ek;us ,oa ç;ksx gksrs gSaA fdlh çksxzkfeax ySaXost esa djSDVj lsV ds dbZ ,fyesVa gksrs gSa tSls vYQkcsV
¼yksoj dsl ,oa vij dsl½] fo'ks"k djSDVj] la[;k,¡ vkSj Hkh cgqr dqNA çksxzkfeax ySaXost esa dqN ,sls [kkl djSDVj gksrs gSa
tks djSDVj ds lfeJ.k ls curs gSa tSls ,Ldsi lhDosla djSDVj bR;kfnA
Character: It denotes any alphabet, digit or special symbol used to represent information.
Use: These characters can be combined to form variables. C uses constants, variables, operators,
keywords and expressions as building blocks to form a basic C program.
Character set: The character set is the fundamental raw material of any language and they are used to
represent information. Like natural languages, computer language will also have well defined
character set, which is useful to build the programs.
The characters in C are grouped into the following two categories:
9
'O' Level M3:R4 C-LANGUAGE
Decision making falls into the following forms as per discussed in the above diagram. We see
Decision making is considered into two stated forms – Conditional branching and Looping. The
Conditional branching is the conditional statements which allows or facilitates to execute a certain
block of code to be executed as per the condition, if the condition remains true then
tSlk dh Åij ds Mk;xzke esa çnf'kZr gS dh fMlhtu esfdax nks rjg ds gksrs gSa igyk daMh'kuy czkafpax ,oa nwljk ywfiaxA
daMh'kuy czkafpax ds varxZr fdlh LVsVesVa dks ,d ;k ,d ls vf/kd daMh'ku ds Vªw¼lgh½ ;k QkYl ¼xyr½ gksus ds fdlh
,d fLFkfr esa ,XthD;wV djuk tcfd ywfiax dk eryc fdlh ,d LVsVesVa dks ,d ;k ,d ls vf/kd daMh'ku ds fglkc
ls ckj ckj ,XthD;wV djuk gksrk gS tc rd og daMh'ku Vªw ¼lgh½ gksrh gSA
4.2 DECISION MAKING WITHIN A PROGRAM
Decision making within a program is just like making decisions as per the condition. Sometimes we
see there is a situation where action or decision has to be taken on the basis of a certain condition
then we condition statements where we provide options through we can pick a specific one
10
Chapter 12 File Processing
depending on the condition, if the condition returns true then do this else do that. For this kind of
things we are facilitated to use various conditional statements to place conditions like if statement, if-
else statement, Multiple if-else, else-if ladder, Switch-case statement, conditional operators etc.
fdlh ,d çksxzke ds varxZr fMlhtu esfdax dk eryc ;g gksrk gS dh vki ,d fu;r daMh'kuy LVsVesVa tSls if, if-
else, Multiple if, elseif ladder bR;kfn esa LFkkfir daMh'ku ds lgh ;k xyr gksus dh fLFkfr esa d.Vªksy dh czkafpax
gksrh gS eryc daMh'ku Vªw ¼lgh½ gksus ij if Cykd dk LVsVesVa ,oa QkYl ¼xyr½ gksus else Cykd dk LVsVesVa ,XthD;wV
gksrk gSA
In general language whatever conditions we place in oral communication to do an event as per the
condition and situation like “if I will stand first in the class then I will give
the party to everyone”. This is a conditional statement in that the action or event will take
place only if the condition and situation satisfies true in that if the person will become or stand first
then only he will give the party to everyone otherwise not.
lk/kkj.k cksy pky dh Hkk"kk esa ge fdlh ckr dh 'krZ yxkrs gSa dh ;fn ,slk gqvk rks eS ;s d:¡xk vU;Fkk oks d:¡xk Bhd
mlh rjg lh çksxzkfeax esa Hkh fMlhtu esfdax ds rgr fdlh daMh'ku ls Rofjr fdlh ,d LVsVesVa dks ,XthD;wV djus dh
lqfo/kk nsrk gS ftles ;fn oks nh gqbZ daMh'ku lgh ik;h tkrh gS rks ;s LVsVesVa vU;Fkk oks LVsVesVa ,XthD;wV gksrk gSA
This kind of action or event can be constructed using the conditional statement using different
conditional statements like…
if I will stand first
I will give the party
else
I cannot give the party
We can even construct multiple conditions to be placed for the same event.
Conditions
Conditions are the expressions which are used to evaluate statements as per the condition.
Conditions are the comparison statements to execute the statements condition wise and provide at
least two options to execute the statements means there will be two options in between one has to be
executed, if the condition is true then execute this otherwise execute that. We place different
operators and conditional statements to establish condition in the program to execute the program
statements.
daMh'ku ,d cgqr gh [kkl ?kVd gS tks daMh'kuy czkafpax ,oa ywfiax esa ç;ksx gksrk gSA daMh'ku dk eryc lk/kkj.k Hkk"kk
esa 'krZ gksrk gS tks czkafpax ,oa ywfiax esa d.Vªksy dks eksfuVj djus ds fy, ç;ksx fd;k tkrk gSA daMh'ku esa fdUgh nks
v‚ijsaM ds chp T;knkrj fjys'kuy v‚ijsVj dk ç;ksx dj daMh'ku cukrs gSa ftlds lgh ;k xyr gksus dh fLFkfr esa
d.Vªksy dk czkafpax ,oa ywfiax fuHkZj djrk gSA
Here we see…
2<3
Relational Operators: As we have already studied about relational operators that this very operator is
used to establish comparisons between two variables that yield the result in the form of true of false
for example if you compare two variable’s values let’s take 5 and 6 to find which one is greater or
whether 5 is greater to 6 or not then the result will be returned as false.
tSlk dh geus bl v‚ijsVj ds ckjs esa igys Hkh i<+k vkSj ns[kk dh ;g v‚ijsVj dSls fdUgh nks osfj,cy ds e/; rqyuk dj
,d daMh'ku fØ,V djus esa enn djrk gSA bl v‚ijsVj ds ç;ksx ls vki ,d daMh'ku ns ikrs gSaA bl v‚ijsVj V‚fid
dks ;gk¡ blfy, mYysf[kr fd;k tk jgk gS D;ksfa d fdlh Hkh çdkj ds daMh'kuy LVsVesVa dks bEIyhesVa djus ds fy,
vkidks fjys'kuy v‚ijsVj dks bEIyhesaV djus vkuk pkfg,A ;gk¡ uhps fjys'kuy v‚ijsVj lewg ds lHkh v‚ijsVj dh fyLV
nh x;h gSA
11
'O' Level M3:R4 C-LANGUAGE
Arrays
Array comes with the following kinds…
One dimensional array
Two dimensional array
Multi dimensional array
5.1 INTRODUCTION TO ONE DIMENSIONAL ARRAYS
An array is a collective name given to a group of ‘similar quantities’. An array is a collection of similar
elements or data types. Whenever you need to collect
and store more than one value of same data types in a ,sjs lh çksxzkfeax esa ,d rjg dk osfj,cy gksrk gS
bulk quantity then you go better declare an array tks ,d le; esa ,d ls T;knk ,d gh MkVk
instead of declaring a number of variables. It asks a Vkbi ds oSY;w dks vyx vyx LVksj dj ldrk
name as the rest of the variables and a size in numeric gS ;k lk/kkj.k 'kCnksa esa dgsa rks ,sjs flfeyj¼,d
placed in a subscript [ ]. leku½ MkVk oSY;w dk ,d lewg gksrk gS ftles
vki ,d le; esa ,d ls T;knk oSY;w LVksj dj
Up till this Module we were introduced with simple data ldrs gSa ,oa mUgsa fdlh Hkh le; ,Dlsl djus ds
types that suit to simple applications. For aggregated lkFk lkFk mls eSfuiqysV Hkh dj ldrs gSaA ,sjs
data, with same type of element we can use Array. An dks vki fdlh ,d MkVk Vkbi ls fMDysvj dj
array in C / C++ is a collection of related data elements ldrs gSa ysfdu bls fMDysvj djus ds fy,
of the same type that are referenced by a common vkidks bldk lkbtHkh mYysf[kr djuk iM+x s k
name. Generally, it is just another data type, aggregate tks ;g r; djsxk dh ,sjs ml MkVk Vkbi dh
data type. All the elements of an array occupy a set of fdruh oSY;w dks LVksj djsxkA
contiguous memory locations and by using an index or
subscript we can identify each element. For example, instead of declaring mark1, mark2, ..., markN to
store and manipulate a set of marks obtained by the students in certain courses, we could declare a
single array variable named mark and use an index, such as j, to refer to each element in mark. This
absolutely has simplified our declaration of the variables.
Hence, mark[ j ] would refer to the jth element in the array mark. Thus by changing the
value of j, we could refer to any element in the array, so it simplifies our declaration.
For example, if we have 100 list of marks of integer type, we will declare it as follows:
int mark1, mark2, mark3, ..., mark100;
If we have 100 marks to be stored, you can imagine how long we have to write the
declaration part by using normal variable declaration?
By using an array, we just declare like this:
int mark[100];
12
Chapter 12 File Processing
This will reserve 100 contiguous/sequential memory locations for storing the integer data
type.
Graphically can be depicted as follows:
‘I’
In this statement, the array character can store up to 10 characters with the first character occupying
location character [0] and the last character occupying character[9]. Note that the index runs from 0
to 9. In C an index always starts from 0 and ends with (array size-1). So, notice the difference
between the array size and subscript/index terms. An array may be initialized at the time of its
declaration, which means to give initial values to an array. Initialization of an array may take the
following form:
type array_name[size] = {value_list};
For example:
int id[7] = {1, 2, 3, 4, 5, 6, 7};
13
'O' Level M3:R4 C-LANGUAGE
Functions
In this very chapter we will be learning the functioning of functions as well as creating and
manipulating them. Functions are nothing but self contained block of code with certain definition. A
function may be system defined or user defined. A system defined function is called library function
where a user defined function is needed to be declared and defined with a prototype. A function
made programming easy because it yields the facility to split the program code in modules that can
anytime separately defined, tested and manipulated and can be called number of times in the
program code anytime without writing the program code again.
bl v/;k; ds varxZr ge QaD'ku ds ckjs esa foLr`r v/;;u djsaxsA QaD'ku tSlk dh geus blds ckjs esa laf{kIr tkudkjh
yh dh ;g ,d vyx Cykd v‚QdksM gksrk gS tks [kqn dks esu QaD'ku ls vyx gksrk gS ftls d‚y djus ij gh ;g
,XthD;wV gksrk gS ,d fu;r çfrQy ykSVrk gSA QaD'ku nks rjg ds gksrs gSa & igyk flLVe ifjHkkf"kr ,oa nwljk ;wtj
}kjk ifjHkkf"krA flLVe }kjk ifjHkkf"kr QaD'ku dks gh ykbczsjh QaD'ku dgjrs gSa tcfd ;wtj fMQkbaM¼ifjHkkf"kr½ QaD'ku
dks ç;ksx djus ls igys bls çksVksVkbi djuk iM+rk gS ,oa bldh MsfQfu'ku dks vyx dksM djuk iM+rk gS ftls vki
esu QaD'ku esa d‚y djds ç;ksx dj ldrs gSaA
6.1 Top-down approach of problem solving
A top-down approach (also known as stepwise design and in some cases used as a synonym
of decomposition) is essentially the breaking down of a system to gain insight into its compositional
sub-systems. In a top-down approach an overview of the system is formulated, specifying but not
detailing any first-level subsystems. Each subsystem is then refined in yet greater detail, sometimes
in many additional subsystem levels, until the entire specification is reduced to base elements. A top-
down model is often specified with the assistance of "black boxes", these make it easier to
manipulate. However, black boxes may fail to elucidate elementary mechanisms or be detailed
enough to realistically validate the model. It breaks down from there into smaller segments.
gj çksxzke dk ,d ,çksp gksrk gS dh ;g fdl çdkj ,oa fdl fn'kk esa ,XthD;wV gksrk gSA lk/kkj.kr% ,d çksxzke dks
,XthD;wV djus ds nks ,çksp gksrs gSa & igyk V‚i&Vw&c‚Ve ,oa nwljk c‚Ve&viA V‚i&Vw&c‚Ve ,çksp dk eryc çksxzke
Åij ls uhps dh rjQ ,XthD;wV gksxk tcfd c‚Ve&vi ,çksp dk eryc çksxkz e uhps ls Åij dh rjQ ,XthD;wV
gksxkA fdlh QaD'ku dk ,fXtD;qlu ,çksp lk/kkjr% V‚i&Vw&c‚Ve gksrk gSA
Top-Down Design:
If we look at a problem as a whole, it may seem impossible to solve because it is so complex.
Examples: writing a tax computation program
writing a word processor
14
Chapter 12 File Processing
Complex problems can be solved using top-down design, also known as step wise refinement,
where
We break the problem into parts
Then break the parts into parts
Soon, each of the parts will be easy to do
Advantages of Top-Down Design:
Breaking the problem into parts helps us to clarify what needs to be done.
At each step of refinement, the new parts become less complicated and, therefore, easier to
figure out.
Parts of the solution may turn out to be reusable.
Breaking the problem into parts allows more than one person to work on the solution.
Increased comprehensive of problem.
Unnecessary lower-level details are removed.
Reduced debugging time.
An Example of Top-Down Design:
Problem:
We own a home improvement company.
We do painting, roofing, and basement waterproofing.
A section of town has recently flooded (zip code 21222).
We want to send out pamphlets to our customers in that area.
The Top Level
Get the customer list from a file.
Sort the list according to zip code.
Make a new file of only the customers with the zip code 21222 from the sorted customer list.
Print an envelope for each of these customers.
Another Level?
Should any of these steps be broken down further? Possibly.
How do I know? Ask yourself whether or not you could easily write the algorithm for the
step. If not, break it down again.
When you are comfortable with the breakdown, write the pseudo code for each of the steps
(modules) in the hierarchy.
Typically, each module will be coded as a separate function.
Structured Programs
15
'O' Level M3:R4 C-LANGUAGE
Storage Classes
7.0 INTRODUCTION
Storage classes are the pattern of memory allocating to the variables whether in the memory or in
the CPU registers. To fully define a variable one needs to mention not only its ‘type’ but also its
‘storage class’. In other words, not only do all variables have a data type, they also have a ‘storage
class’. If we don’t specify the storage class of a variable in its declaration, the compiler will assume a
storage class depending on the context in which the variable is used. Thus, variables have certain
default storage classes.
LVksjst Dykl ,d çdkj dk eseksjh yksds'ku gS tks lk/kkj.k eseksjh yksds'ku esa u gksdj ds cfYd lhih;w jftLVj esa ik;k
tkrk gSA fdlh osfj,cy dks iwjh rjg ls fMQkbu djus ds fy, vkidks LVksjst Dykl MkVk Vkbi dk ç;ksx djuk iM+rk
gSA vki vius çksxkz e esa tc Hkh fdlh osfj,cy dks fMDysvj djrs gSa rks vki mldk MkVk Vkbi mlh le; fu/kkZfjr dj
nsrs gSa tgk¡ ij ml osfj,cy dk LVksjst Dykl Hkh fMQkbu dj ldrs gSa ;|fi vki fdlh osfj,cy dk LVksjst Dykl
ml oä ugha Hkh bafxr djrs gSa rc Hkh ml osfj,cy ds oSY;w LVksj djus ds ç—fr ds fglkc ls mldks ,d LVksjst
Dykl Lor% çnku dj fn;k tkrk gSA
From C compiler’s point of view, a variable name identifies some physical location within the
computer where the string of bits representing the variable’s value is stored. There are basically two
kinds of locations in a computer where such a value may be kept—Memory and CPU registers. It is
the variable’s storage class that determines in which of these two locations the value is stored.
lh dEikbyj ds –f"Vdks.k ls fdl Hkh osfj,cy dk ,d daI;wVj flLVe esa ,d HkkSfrd LFkku gksrk gS tgk¡ ij ml
osfj,cy ds oSY;w fcV ds J`a[kykvksa ds :i esa LVksj gksrh gSA bls vuqlkj fdlh flLVe esa oSY;w LVksj djus ds fy, nks
LFkku gksrs gSa igyk eseksjh ,oa nwljk lhih;w jftLVj-,oa LVksjst Dykl ds varxZr osfj,cy fMDysvj djus dh fLFkfr esa
oks osfj,cy lhih;w jftLVj esa LVksj gks tkrk gSA
Over view: In c there are four types of storage class. They are:
1. auto
2. register
3. static
4. extern
Storage class is modifier or qualifier of data types which decides:
1. In which area of memory a particular variable will 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)
16
Chapter 12 File Processing
3. What is the scope of the variable; i.e. in which functions the value of the variable would be
available.
4. What is the life of the variable; i.e. how long would the variable exist.
Visibility of a variable in c: Visibility means accessibility. Up to witch part or area of a program, we
can access a variable, that area or part is known as visibility of that variable. For example: In the
following figure yellow color represents visibility of variable a.
7.1 SCOPE AND EXTENT
The scope of storage classes are sometimes local and for some storage class it is global. For e.g. we
see extern storage class which defines a variable global and accessible to all the functions and
modules remaining its original value.
fdlh LVksjst Dykl dk Ldksi bls ,Dlsl djus ,oa ,Dlsl gksus dh gn dks dgrs gSaA dqN osfj,cy dks ge yksdy
fMDysvj djrs gSa ,oa dqN dks Xykscy ifj.kke Lo:i oks Xykscy osfj,cy gj txg eryc gj QaD'ku esa ,Dlsl fd;k
tk ldrk gS ysfdu oks yksdy osfj,cy dsoy ogh rd flfer gksrk gS tgk¡ og fMDysvj fd;k x;k gksrk gSA
Scope: The scope of a declaration is the region of C program text over which that declaration is active.
Top-level identifiers – Extends from declaration point to end of file.
Formal parameters in functions – Extends from declaration point to end of function body.
Block/function (local) identifiers – Extends from declaration point to end of block/function.
Extent: The extent of an object is the period of time that its storage is allocated.
An object is said to have static extent when it is allocated storage at or before the beginning of
program execution and the storage remains allocated until program termination. All functions have
static extent, as do all variables declared in top-level declarations and variables declared with
the static qualifier. Formal parameters and variables declared at the beginning of a block or function
have local extent (dynamic, de allocated on block/function exit).
External variable or function:
A top-level identifier is treated just like a static extent object in the file containing its definition, but is
also exported to the linker, and if the same identifier is declared in another file, the linker will ensure
the two files reference the same object (variable or function). Thus, top-level identifiers and
functions are external by default. The convention is to use to use
the extern qualifier in all places that are simply declaring an identifier
that is defined (allocated) in another file, and to omit the qualifier at
the single point where the variable is actually defined (allocated
space).
Thus external is the same as “global” or “public”. A static variable or
function: has only file scope, is not external. Thus static is the same as
“private.”
7.1.1 Types of Scope
Generally Scopes of the programming entities are as follows…
Block Scope
Function Scope
17
'O' Level M3:R4 C-LANGUAGE
Pointers
8.1 INTRODUCTION
A Pointer is a specific type of variable that holds the address or location of other variable, structure
and functions that are used in a program. Pointers point to these locations by keeping a record of the
spot at which they were stored. Pointers to variables are found by recording the address at which a
variable is stored. It is always possible to find the address of a piece of storage in C using the special
‘&’ operator. Which feature of C do beginners find most difficult to understand? The answer is easy:
pointers. Other languages have pointers but few use them as frequently as C does. It is C’s clever use
of pointers that makes it the excellent language it is.
i‚baVj ,d rjg dk v‚ijsVj gksrk gS tks fdlh ,d lk/kkj.k osfj,cy ds ,Mªls dks LVksj dj ldus ds {kerk j[krk gSA
geus avc rd fdlh osfj,cy ds oSY;w dks ç;ksx fd;k ysfdu ;gk¡ ij ge fdlh oSY;w dks NksM+ cfYd mlds ,Mªl s dks
ç;ksx dj mlds oSY;w dks çkIr djrs gSa ,oa mls çksxzke ds mís'; vuqlkj bEIyhesaV djrs gSaA i‚baVj ds nks rjg ds
v‚ijsVj gksrs gSa tks fuEufyf[kr gSaA
Benefit of using pointers
Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as arguments
to other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.
,sjst dks cgqr gh vklkuh ls eSuhiqysV fd;k tk ldrk gS D;ksafd ,sjst dk ewo u djds dsoy ikWbaVlZ dks ,sjst rd ys
tkuk gksrk gSA fyaDM fyLV ,oa ckbujh Vªh tSls dEIysDl MkVk LVªDpj cuk;s tk ldrs gSa tgk¡ ,d MkVk LVªDpj esa
nwljs MkVk LVªDplZ ds fy, jsQjsalst j[ks gksrs gSaA मह C को डामनामभ भेभोयी भैनेजभें ट की सहामता हेतु अनभ
ु तत प्रदान कयता
हैA
Concept of Pointer: Whenever a variable is declared, system will allocate a location to that variable in
the memory, to hold value. This location will have its own address number. Let us assume that
system has allocated memory location 2025 for a variable a.
int val = 100;
18
Chapter 12 File Processing
We can access the value 100 by either using the variable name ‘val’ or the address 2025. Since the
memory addresses are simply numbers they can be assigned to some other variable. The variable
that holds memory address are called pointer variables. A pointer variable is therefore nothing but a
variable that contains an address, which is a location of another variable. Value of pointer
variable will be stored in another memory location.
Pointers are an extremely powerful programming tool. They can make some things much easier, help
improve your program's efficiency, and even allow you to handle unlimited amounts of data. For
example, using pointers is one way to have a function modify a variable passed to it. It is also possible
to use pointers to dynamically allocate memory, which means that you can write programs that can
handle nearly unlimited amounts of data on the fly--you don't need to know, when you write the
program, how much memory you need. Wow, that's kind of cool. Actually, it's very cool, as we'll see
in some of the next tutorials. For now, let's just get a basic handle on what pointers are and how you
use them.
8.2 WHAT IS A POINTER?
C Pointer is a variable that stores/points the address of another variable. C Pointer is used to allocate
memory dynamically i.e. at run time. To declare and refer to a pointer type variable C provides two
special unary operators * and &. The pointer variable might be belonging to any of the data type
such as int, float, char, double, short etc.,
s j[krk gS जजसका iz;ksx djds MkVk dks LVksj djuk ,oa fjVªho
ikWbaVj ,d oSfj,cy gS tks nwljs oSfj,cy dk eseksjh ,sMªl
djuk vf/kd rsth ls fd;k tk ldrk gS] tcfd oSfj,cy dk iz;ksx djus ls ;gh dke /kheh xfr ls gksrk gSA
Syntax : data_type *var_name;
Example : int *p; char *q;
Where, * is used to denote that “p” and “q” are pointer variables and not a normal variables.
8.2.1 Why use Pointers?
We use pointer for the following reasons:
pointers increase the execution speed.
a pointers enable us to access a variable that is defined outside the function.
pointres are more efficient in handling the data tables.
pointers reduce the length and complexity of a program.
The use of pointer array to character strings results in saving of data storage space in
memory.
Look up dynamic memory: The most common use of pointers is probably dynamic arrays
(arrays in which the size is determined at run time).
Linked lists and binary tree, where one data structure must contain references to other data
structures.
Pointers are useful for referencing things in memory when the location of those things
cannot be known at the time the program is compiled. For example, when memory is
allocated dynamically at run time, pointers are needed to reference the memory.
19
'O' Level M3:R4 C-LANGUAGE
20
Chapter 12 File Processing
information such as Roll, name, Percent which may be of different data types. Ideally Structure is
collection of different variables under single name. Basically Structure is for storing the complicated
data. A structure is a convenient way of grouping several pieces of related information together.
Keyword struct is used for creating a structure.
Syntax of Structure: Alternate Syntax of structure:
struct tag struct structure_name
{ {
data_type1 member1; data_type member1;
data_type2 member2; data_type member2;
data_type3 member3; data_type memeber;
}; };
9.2.1 Graphical Representation of Structure
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
A structure contains a number of data types grouped together. These data types may or may not be of
the same type. The following example illustrates the use of this data type. Here we see…
9.2.2 Declaring Structure Variable
In our example program, the following statement declares the structure type:
fdlh LVªDpj osfj,cy dks fMDysvj djus dk rjhdk ,oa flaVsDl fuEufyf[kr gS&
struct book
{
char name;
float price;
int pages ;
};
Structure variables are those variables which are declared with the structure name following
with the struct keyword. These variables are used to access the structure members declared
inside. Structures variable can be named any as you do for the normal variables.
21
'O' Level M3:R4 C-LANGUAGE
22
Chapter 12 File Processing
Graph: Graph is used to represent data that has relationship between pair of elements not necessarily
hierarchical in nature. For example electrical and communication networks, airline routes, flow
chart, graphs for planning projects.
Data Structures Examples - Video:
10.2 SELF REFERENTIAL STRUCTURE
In the context of language, self-reference is used to denote a statement that refers to itself or its own
referent. The most famous example of a self-referential sentence is the liar sentence: "This sentence
is not true." Self-reference is often used in a broader context as well. For instance, a picture could be
considered self-referential if it contains a copy of itself (see the animated image above); and a piece
of literature could be considered self-referential if it includes a reference to the work itself. In
philosophy, self-reference is primarily studied in the context of language. Self-reference within
language is not only a subject of philosophy, but also a field of individual interest in mathematics and
computer science, in particular in relation to the foundations of these sciences.
A self-referential structure is used to create data structures like linked lists, stacks, etc. Following is
an example of this kind of structure:
struct struct_name
{
datatype datatype_name;
struct_name * pointer_name;
};
A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type. For example, a linked list is supposed to be a self-referential data
structure. The next node of a node is being pointed, which is of the same struct type. For example,
typedef struct listnode {
void *data;
struct listnode *next;
}linked_list;
In the above example, the ‘listnode’ is a self-referential structure – because the *next is of the type
sturct ‘listnode’. Where ‘listnode’ is a structure that consists of two members one is the data item,
second one is the pointer variable.
10.3 INTRODUCTION TO LINKED LISTS
In computer science, a linked list is a data structure consisting of a group of nodes which
together represent a sequence. Under the simplest form, each node is composed of data and
a reference (in other words, a link) to the next node in the sequence; more complex variants
add additional links. This structure allows for efficient insertion or removal of elements from
any position in the sequence.
23
'O' Level M3:R4 C-LANGUAGE
24
Chapter 12 File Processing
LVSDl ,d yhfu;j MkVk LVªDpj gSA ysfdu bl MkVk LVªDpj es]a fyLV ds dsoy ,d ,aM ls gh ,yhesVa l ~ tksM+s ;k gVk,
tk ldrs gSa vFkkZr~ LVSd ds VkWi esa lsA bl rjg ls LVSd ,aVªh vkWMZj ds foijhr Øe esa lwpuk iznku djrk gS] blfy,
bls ykLV&bu&QLVZ&vkmV fyLV dgk tkrk gSA
Stacks are data structures that allow us to insert and remove items. The operate like a stack of papers
or books on our desk - we add new things to the top of the stack to make the stack bigger, and
remove items from the top as well to make the stack smaller. This makes stacks a LIFO (Last In First
Out) data structure – the data we have put in last is what we will get out first. Before we consider the
implementation to a data structure it is helpful to consider the interface. We then program against
the specified interface. Based on the description above, we require the following functions:
push() is the term used to insert/add an element into a stack.
pop() is the term used to delete/remove an element from a stack.
Other names for stacks are piles and push-down lists. There are two ways to represent Stack in
memory. One is using array and other is using linked list.
11.3 IMPLEMENTATION OF STACK
A stack can be implemented using either an array or a singly linked list. Thus there are two methods
of stack implementation. They are: Static implementation and Dynamic implementation.
Static implementation can be achieved using arrays. Though array implementation is a simple
technique, it provides less flexibility and is not very efficient with respect to memory organization.
This is because once a size of an array is declared; its size cannot be modified during program
execution. If the number of elements to be stored in a stack is less than the allocated memory, then
memory is wasted and if we want to store more elements than declared, array cannot be expanded. It
is suitable only when we exactly know the number of elements to be stored.
A stack can be implemented using pointers, as a form of a linked list. Dynamic implementation can be
achieved using linked list as it is a dynamic data structure. The limitations of static implementation
can be removed using dynamic implementation. The memory is efficiently utilized with pointers.
Memory is allocated only after element is inserted to the stack. The stack can grow or shrink as the
program demands it to. However, if a small and/or fixed amount of data is being deal with, it is often
simpler to implement the stack as an array.
LVSd के इम्प्रीभें टेशन की चचाड हभ महाॉ कये गे इसका इम्प्रीभें टेशन array or a singly linked list के प्रमोग से ककमा जा
सकता हैA LVSd ,d yhfu;j fyLV gS vkSj blfy, fyLV esa mi;ksx dh tkus okyh dksbZ Hkh bEIyhesVa 's ku rduhd LVSd
esa Hkh bEIyhesaV dh tk ldrh gSA LVSd ds bEIyhesaVs'ku स्ट्टै दटक एवॊ डैनामभक इम्प्रीभेंटेशन rjhds से ककमा जा सकता
gSaA ,sjst LVSfVd MkVk LVªDpj gSa] vkSj muds }kjk vko';d Lisl iwoZ fu/kkZfjr gksuh pkfg, vFkkZr~ ;g igys ls irk jguk
pkfg, fd fdlh Hkh le; dqy fdrus ,yhesaV~l ,d lkFk ekStwn jgsaxsA blfy,] ,sjs ds :i esa LVSd dks cukus ds fy,
,yhesaV~l dh la[;k igys ls irk gksuh pkfg,A ;fn LVSd dks ,sjs ds iz;ksx }kjk bEIyhesaV fd;k tkrk gS] rks ,yhesaV~l dh
vf/kdre la[;k ftUgsa blesa j[kk tk ldrk gS og ,sjs ds Mk;es'a kUl }kjk fu/kkZfjr dh tkrh gSA LVSd dh vf/kdre
{kerk ls ckgj ,yhesVa l
~ dks iq'k djus dk iz;kl gh LVSd vksoj ¶yks dgykrk gSA
25
'O' Level M3:R4 C-LANGUAGE
12
File Processing
12.0 INTRODUCTION
File handling means storing a kind of data permanent in a file rather than taking input again and
again. The data you enter while running a program get lost when program terminates but when you
will be using files creating and manipulating then the data you entered or manipulated will be
permanent saved to the computer disk. Often it is not enough to just display the data on the screen.
This is because if the data is large, only a limited amount of it can be stored in memory and only a
limited amount of it can be displayed on the screen. It would be in appropriate to store this data in
memory for one more reason. Memory is volatile and its contents would be lost once the program is
terminated. So if we need the same data again it would have to be either entered through the
keyboard again or would have to be regenerated programmatically.
Qkby gSaMfyax dk eryc lh çksxkz feax dh enn ls dksbZ Qkby fØ,V djuk ftles vki dksbZ MkVk fy[k lds] mldk
MkVk i<+ lds bR;kfnA pqdh vc rd ds buiqV ,oa vkmViqV çnf'kZr djus ds LVS.MMZ ,aM dalksy QaD'ku dk ç;ksx
fd;k tkrk Fkk tks dsoy çksxzke ds pyrs jgus rd gh oSY;w eseksjh esa jgrh gS vkSj çksxzke ds VfeZuVs gksrs gh oSY;w Hkh
eseksjh ls xk;c gks tkrh gS D;ksfa d ;g ijekusVa ugha gksrk gSA fdlh Hkh buiqV ,oa vkmViqV oSY;w dks ijekusaV daI;wVj
fMLd esa LVksj djus ds fy, gesa Qkby gSaMfyax dk ç;ksx djuk iM+rk gSA
12.1 CONCEPT OF FILE
When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created, this information
can be accessed using few commands. There are large numbers of functions to handle file I/O in C
language. In this study material, you will learn to handle standard I/O (High level file I/O functions)
in C.
High level file I/O functions can be categorized as:
Text file
Binary file
File Operations
There are different operations that can be carried out on a file. fdlh Qkby gSaMfyax ls lanfHkZr laHkkfor Qkby
v‚ijs'ku gSa &
These are:
Creation of a new file
Opening an existing file
26
Chapter 12 File Processing
FILE *fp;
Now we see the syntax of opening a file in the program…
fp = fopen("Hello.txt", "r");
Now you can run a loop to read each character from the file to the EOF (End of file).
12.2 FILE OPENING MODES
In our first program on disk I/O we have opened the file in read (“r”) mode. However, “r” is but one
of the several modes in which we can open a file. Following is a list of all possible modes in which a
file can be opened. The tasks performed by fopen( ) when a file is opened in each of these modes are
also mentioned.
27