Based on NIELIT (DOEACC) 'O' Level Revised Syllabus, 2014 ... · Based on NIELIT (DOEACC) 'O' Level...

27
Based on NIELIT (DOEACC) 'O' Level Revised Syllabus, 2014 (Module M3:R4) 'O' Level Module-3 PROGRAMMING & PROBLEM SOLVING THROUGH ‘C’ LANGUAGE Based on Latest syllabus of NIELIT TBALAJI PUBLICATION Triloki Complex, Infront of A.N. Jha Hostel, Allahabad- 211002 Uttar Pradesh Opposite A N Jha Hostel, University Road Allahabad 09412631990, 9450976411, 05322460211 E-Mail [email protected], [email protected]

Transcript of Based on NIELIT (DOEACC) 'O' Level Revised Syllabus, 2014 ... · Based on NIELIT (DOEACC) 'O' Level...

Based on NIELIT (DOEACC) 'O' Level Revised Syllabus, 2014

(Module M3:R4)

'O' Level Module-3 PROGRAMMING & PROBLEM SOLVING

THROUGH

‘C’ LANGUAGE

Based on

Latest syllabus of NIELIT

TBALAJI PUBLICATION

Triloki Complex, Infront of A.N. Jha Hostel, Allahabad- 211002

Uttar Pradesh

Opposite A N Jha Hostel, University Road Allahabad

09412631990, 9450976411, 05322460211

E-Mail [email protected], [email protected]

'O' Level Module M3:R4 C-Language

2

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH ‘C’ LANGUAGE

Objective of the Course The objectives of this course are to make the student understand programming language, programming, concepts of Loops, reading a set of Data, stepwise refinement, Functions, Control structure, Arrays. After completion of this course the student is expected to analyze the real life problem and write a program in ‘C’ language to solve the problem. The main emphasis of the course will be on problem solving aspect i.e. developing proper algorithms. After completion of the course the student will be able to…

Develop efficient algorithms for solving a problem. Use the various constructs of a programming language viz. conditional, iteration and recursion. Implement the algorithms in “C” language. Use simple data structures like arrays, stacks and linked list in solving problems. Handling File in “C”.

Outline of Course

S. No. Topic Minimum number of

hours

1. Introduction to Programming 04

2. Algorithms for Problem Solving 10

3. Introduction to ‘C’ Language 04

4. Conditional Statements and Loops 07

5. Arrays 06

6. Functions 06

7. Storage Classes 03

8. Structures and Unions 06

9. Pointers 06

10. Self Referential Structures and Linked Lists 04

11. File Processing 04

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

Chapter 1 Introduction to programming ri

3

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

'O' Level Module M3:R4 C-Language

4

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 funsZ'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 funsZ'k nsrs gSaA

vkSj ml fu;r funsZ'k ds vuqlkj gh ml çksxzke dks Øeokj rjhds ls lqy>krs gSaA tSls dh fj;y Vkbe bosaV 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 funsZ'k ds vuqlkj gh

fdlh dk;Z dks vatke nsrs gSa pkgs oks funsZ'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 dkalsIV ds varxZr dbZ pj.k gksrs gSa ftuds vius Lo;a ds

fdjnkj gksrs gSa ftudh enn ls ge fdlh çksxzke 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

Chapter 1 Introduction to programming ri

5

Step 7: Maintain and Modify the Program

1.2.1 Step 1: Understanding the Problem

We need to first fetch the problem what you have to solve or make that execute. For solving a problem first you need to understand the things or problem that how and what manner it may be solved or executed then write an algorithm for that problem step by step that will make the things more clearly or make a diagram or flow chart of the problem that is considered more clear to form a program before coding it.

çksxzke dkalsIV ds rgr lcls igys gesa çksxzke ds mís'; ,oa lEcaf/kr leL;k dks le>uk gksxkA ;g çksxzke dkalsIV dh

lcls igyh ,oa vge~ dM+h gSA çksxzke ds mís'; ,oa lEcaf/kr leL;k dks iq.kZ~;rk le>us ds rRi'pkr ge ml çksxzke dh

:i js[kk dks ,YxksfjFke ,oa ¶yks pkVZ dh enn ls js[kkafdr djrs gSaA

1.2.2 Step 2: Design the Program and Make Declarations

Draw or prepare Algorithm or Flow chart or both to draw the architecture of the program so that it can be formed into program code easily and accurately. Algorithm is something what, is written or constructed step by step in a concise and clear way to solve a problem at end Whereas Flow chart is a graphical notation or representation with a certain definition demonstrate the program flow and control along with the given instructions.

;g çksxzke dkalsIV dh nwljh dM+h gS ftles fdlh çksxzke ds mís'; ,oa leL;k ds rgr ge ,d ,YxksfjFke ;k ¶ykspkVZ

cukrs gSaA ,YxksfjFke ,d çkphu çksxzkfeax rduhd gS ftles ge fdlh çksxzke dks Øeokj rjhds ls lqy>krs gSa tcfd ¶yks

pkVZ ,d xzkfQdy fjçtsaVs'ku gS ftlds rgr ge fdlh çksxzke ds ,DthD;wlu ds ¶yks dks fu;r fp=ksa ds ek/;e ls

çLrqr djrs gSa A

Declare the necessary variables or functions for that problem you understood at the first level. Declarations may be local or global within a scope you can use as per the requirement. Variable declaration is something what you assign a data type definition on that kind of value only it can perform. Variables are the containers what contains a certain kind of value and are used in an operation.

çksxzke ds mís'; ,oa leL;k dks le>us vkSj mldk ,YxksfjFke ,oa ¶yks pkVZ dks cukus ds i'pkr ges vius çksxzke esa

t:jh fMDysjs'ku djus dh vko';drk iM+rh gSA tSls dh osfj,cy fMDysvj djuk] QaD'ku fMDysvj djuk bR;kfnA

1.2.3 Step 3: Write the Code

It is the section where we write the code as per the program objective and Algorithms/Flowchart drawn. Now you can begin to implement it by writing the code. That is, you translate your program design into the C language. Here is where you really have to put your knowledge of C to work. You can sketch your ideas on paper, but eventually you have to get your code into the computer. The mechanics of this process depend on your programming environment. We'll present the details for some common environments soon. In general, you use a text editor to create what is called a source code file.

1.2.4 Step 4: Compile

The next step is to compile the source code. Again, the details depend on your programming environment. The compiler is a program whose job is to convert source code into executable code. Executable code is code in the native language, or machine language, of your computer. Different computers have different machine languages, and a C compiler translates C into a particular

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

2.3 DIFFERENT TYPES OF ALGORITHMS Basically everybody and every programmer know… it is very famous … they are …

Brute force algorithm: Brute force implies using the definition to solve the problem in a straightforward manner. Brute force algorithms are usually the easiest to implement, but the disadvantage of solving a problem by brute force is that it is usually very slow and can be applied only to problems where input size is small.

Divide and conquer algorithm: In this method, we divide the size of a problem by a constant factor in each step. This means we have to process lesser and lesser part of the original problem in each step. Divide and conquer algorithms have logarithmic runtime.

Decrease and conquer algorithm: This kind of problem is same as divide and conquer, except, here we are decreasing the problem in each step by a constant size instead of constant factor.

Dynamic programming: The word 'dynamic' refers to the method in which the algorithm computes the result means sometimes, a solution to the given instance of problem depends on the solution to smaller instance of sub-problems. It exhibits the property of overlapping sub-problems. Hence, to solve a problem we may have to re-compute same values again and again for smaller sub-problems. Hence, computing cycles are wasted. In this case, we can use dynamic programming technique. Basically, in dynamic programming, we “remember” the result of each sub-problem. Whenever we need it, we will use that value instead of re-computing it again and again.

Greedy algorithm: In a greedy algorithm, in each step, we will make a locally optimum solution such that it will lead to a globally optimal solution. Once a choice is made, we cannot retract it in later stages. Proving the correctness of a greedy algorithm is very important, since not all greedy algorithms lead to globally optimum solution. Means For many problems, making greedy choices leads to an optimal solution. These algorithms are applicable to optimization problems.

Transform and conquer: Sometimes it is very hard or not as apparent as to how to arrive at a solution for a particular problem. In this case, it is easier to transform the problem into something that we recognize, and then try to solve that problem to arrive at the solution.

Backtracking algorithm: Backtracking approach is very similar to brute force approach. But the difference between backtracking and brute force is that, in brute force approach, we are generating every possible combination of solution and testing if it is a valid solution. Whereas, in backtracking, each time you generate a solution, you are testing if it satisfies all condition, and only then we continue generating subsequent solutions, else we will backtrack and go on a different path of finding solution.

2.4 ADVANTAGES OF ALGORITHM Here we will discuss about advantages of Algorithm

It is easy to understand and it facilitates step-by-step solution to a given problem.

It has got a definite procedure.

It easy to first developer an algorithm, & then convert it into a flow chart & then into a computer program.

It is independent of programming language.

It is easy to debug as every step is got its own logical sequence.

,sYxkWfjn~e leL;k ds fy, LVsi ckbZ LVsi lek/kku एवॊ bls vklkuh ls le>k tk ldrk gSA इसका Mhcfxax vklku gS एवॊ izksxzkfeax ySaXost ls Lora= gksrk gS साथ ही इस led{k gkbZ ySaXost esa dksM fd;k tk ldrk gSA

'O' Level M3:R4 C-LANGUAGE

8

Introduction to ‘C’ Language 3.0 INTRODUCTION

C is a programming language based on high level language but with low level feature. It had been developed at AT&T’s bell laboratory in 1972 by Dennis Ritchie. It had been developed on UNIX operating system but after it has become as able to develop the UNIX OS entirely. C programming language is derived from BCPL (Basic Combined Programming Language). C programming language is basically used for system programming and developing system utilities. C is a programmer’s language. C is a computer language and a programming tool which has grown popular because programmers like it! It is a tricky language but a masterful one.

C ,d çksxzkfeax ySaXost gS tks gkbZ ysoy ySaXost ij vk/kkfjr gksrk gS ysfdu Qhpj yks ysoy dk gksrk gSA bldk eryc

gS bl çksxzkfeax ySaXost esa ç;qä Hkk"kk gkbZ ysoy dh gksrh gS ysfdax bldh fo'ks"krk yks ysoy dk gksrk gSA bl çksxzkfeax

ySaXost dks ,Vh ,aM Vh csy yscksjsVjh esa 1972 esa Msful fjph }kjk Msosyi fd;k x;k FkkA bl çksxzkfeax ySaXost dk fuekZ.k

;wfuDl v‚ijsfVax flLVe ij ,oa chlhih,y ySaXost dh enn ls fd;k x;k Fkk tks ckn esa bruk yksdfç; ,oa lcy

lkfcr gqvk dh bldh enn ls ckn esa iqjs ;wfuDl v‚ijsfVax flLVe dk gh fuekZ.k dj fn;k x;kA

C is one of a large number of high level languages which can be used for general purpose programming, that is, anything from writing small programs for personal amusement to writing complex applications.

Basic ideas about C: Using a compiler language is not the same as using an interpreted language. It differs in a number of ways. A ‘C’ program has to be created in two stages…

Firstly, the program is written in the form of a number of text files using a screen editor. This form of the program is called the source program. It is not possible to execute this file directly.

Secondly, the completed source file is passed to a compiler; a program which generates a new file containing a machine code translation of the source text. This file is called an object file or executable file. The executable file is said to have been compiled from the source text.

3.1 CHARACTER SET

Character set is something what is used and recognized by a language pattern where a group of characters are used representing a certain definition. There is number of character element in a character set like alphabet (lower case, upper case), special characters, digits and many more. In ‘C’ programming the character set is used and recognized as the characters what this used directly and some as escape sequences.

Chapter 12 File Processing

9

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 ,fyesaV 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 lhDosal 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:

1. Source character set Alphabets Digits Special Characters White Spaces

2. Execution character set

Escape Sequence

3.1.1 Source Character Set

ALPHABETS

Uppercase letters A-Z

Lowercase letters a-z

DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

SPECIAL CHARACTERS

~tilde %percent sign |vertical bar @atsymbol

_underscore - Minussign < less than >greater than

#number sign =equal to & ampersand $dollar sign

( left parenthesis ) right parenthesis ′ apostrophe * asterisk

: colon [ left bracket ] right bracket " quotation mark

! exclamation mark , comma { left flower brace ? Question mark

} right flower brace +plus sign ^caret /slash

\ back slash ; semicolon . dot operator

WHITESPACE CHARACTERS

\b = blank space \t = horizontal tab \v = vertical tab \r = carriage return

\f = form feed \n = new line \\ = Back slash \’ = Single quote

\" = Double quote \? = Question mark \0 = Null \a = Alarm (bell)

'O' Level M3:R4 C-LANGUAGE

10

Conditional Statements and Loops 4.1 INTRODUCTION

Decision making is all about to let the statements to be executed as per the decision made to jump and branch to execute block of codes. Basically we need these kind of statements only to execute the block of code as per the condition, if the condition will be true then the block of code will be executed else not. The Decision making or control statements can be considered as Control statements which is directed by a control placed in the program.

fMlhtu esfdax dk otwn fdlh Hkh çksxzkfeax ySaXost esa tfEiax ,oa czkafpax dk gksrk gS ftlls ,d daMh'ku ds vuqlkj

d.Vªksy dks ,d LFkku ls nqljs LFkku ij fLop djrs gSaA lk/kkj.kr% fdlh daMh'ku ¼'krZ½ ds vuqlkj ;fn daMh'ku Vªw gksrh

gS rks ;g vU;Fkk og LVsVesaV ,XthD;wV gksrk gSA fMlhtu esfdax ds varxZr vkus okys daMh'kuy LVsVesaV dqN bl çdkj

gSa &

Decision making or the control structure can be considered as following…

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 LVsVesaV 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 LVsVesaV 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

Chapter 12 File Processing

11

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 LVsVesaV 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 LVsVesaV ,oa QkYl ¼xyr½ gksus else Cykd dk LVsVesaV ,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 LVsVesaV dks ,XthD;wV djus dh

lqfo/kk nsrk gS ftles ;fn oks nh gqbZ daMh'ku lgh ik;h tkrh gS rks ;s LVsVesaV vU;Fkk oks LVsVesaV ,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;ksafd fdlh Hkh çdkj ds daMh'kuy LVsVesaV dks bEIyhesaV 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

'O' Level M3:R4 C-LANGUAGE

12

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 bulk quantity then you go better declare an array instead of declaring a number of variables. It asks a name as the rest of the variables and a size in numeric placed in a subscript [ ].

Up till this Module we were introduced with simple data types that suit to simple applications. For aggregated data, with same type of element we can use Array. An array in C / C++ is a collection of related data elements of the same type that are referenced by a common name. Generally, it is just another data type, aggregate data type. All the elements of an array occupy a set of 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];

,sjs lh çksxzkfeax esa ,d rjg dk osfj,cy gksrk gS

tks ,d le; esa ,d ls T;knk ,d gh MkVk

Vkbi ds oSY;w dks vyx vyx LVksj dj ldrk

gS ;k lk/kkj.k 'kCnksa esa dgsa rks ,sjs flfeyj¼,d

leku½ MkVk oSY;w dk ,d lewg gksrk gS ftles

vki ,d le; esa ,d ls T;knk oSY;w LVksj dj

ldrs gSa ,oa mUgsa fdlh Hkh le; ,Dlsl djus ds

lkFk lkFk mls eSfuiqysV Hkh dj ldrs gSaA ,sjs

dks vki fdlh ,d MkVk Vkbi ls fMDysvj dj

ldrs gSa ysfdu bls fMDysvj djus ds fy,

vkidks bldk lkbtHkh mYysf[kr djuk iM+sxk

tks ;g r; djsxk dh ,sjs ml MkVk Vkbi dh

fdruh oSY;w dks LVksj djsxkA

Chapter 12 File Processing

13

This will reserve 100 contiguous/sequential memory locations for storing the integer data type.

Graphically can be depicted as follows:

5.2 ARRAY DECLARATION

Here we see the declaration of array…

uhps fdlh ,sjs dks ,d MkVk Vkbi ds rgr fMDysvj djus ds ckjs esa mYysf[kr fd;k x;k gSA

Dimension refers to the array size that is how big the array is. A single dimensional array declaration has the following form:

data_type array_name[array_size];

Here, data_type declares the base type of the array, which is the type of each element in the array. array_size defines how many elements the array will hold. array_name is any valid C / C++ identifier name that obeys the same rule for the identifier naming. For example, to declare an array of 10 characters, named character, we could use: char character[10]; Can be depicted as follows:

‘b’ Character [0] Character [1] Character [2] Character [3] … Character [10]

‘a’

‘l’

‘a’

‘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};

'O' Level M3:R4 C-LANGUAGE

14

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 foLrr 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 çksxzke 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

Chapter 12 File Processing

15

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

'O' Level M3:R4 C-LANGUAGE

16

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 çksxzke 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 Ja[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)

Chapter 12 File Processing

17

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

'O' Level M3:R4 C-LANGUAGE

18

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ªsl 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ªsl 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;

Chapter 12 File Processing

19

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.,

ikWbaVj ,d oSfj,cy gS tks nwljs oSfj,cy dk eseksjh ,sMªsl j[krk gS जजसका iz;ksx djds MkVk dks LVksj djuk ,oa fjVªho

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.

'O' Level M3:R4 C-LANGUAGE

20

Structures and Unions

9.1 INTRODUCTION

As we have studies that array is the collection of similar data types, in the same way structure is the

collection different data types. It wouldn’t have been so popular had it been able to handle only all

ints, or all floats or all chars at a time. In fact when we handle real world data, we don’t usually deal

with little atoms of information by themselves—things like integers, characters and such. Instead we

deal with entities that are collections of things, each thing having its own attributes, just as the entity

we call a ‘book’ is a collection of things such as title, author, call number, publisher, number of pages,

date of publication, etc. As you can see all this data is dissimilar, for example author is a string,

whereas number of pages is an integer.

A variable holds data of one type at one time but Arrays holds the collection of similar data types, but

when we want to process different data values of different types together as a group we need a

different tool. For example, just as the entity we call a ‘book’ is a collection of things such as title,

author, call number, publisher, number of pages, date of publication, etc. As you can see all this data

is dissimilar, means author is a string, whereas number of pages is an integer

vHkh rd geus ns[kk dh ,d ,sjs ,d çdkj ds MkVk Vkbi ds oSY;w dk lewg gksrk gS tcfd LVªDpj dbZ vyx vyx

rjg ds MkVk Vkbi ds oSY;w dk dysD'ku gksrk gS tks eseksjh esa ,d txg cukrk gS tgk¡ ij lHkh MkVk Vkbi ds vyx

vyx oSY;w tks dh ,d ;wtj ls buiqV fy, x, gSa dks LVksj djrk gSA fdlh ,d çdkj ds oSY;w dks buiqV ysdj mls

eSfuiqysV djuk ,oa fçaV djuk rks geus dbZ ckj ns[kk ,oa ç;ksx fd;k vc ge okLrfod rF;ksa ds vuqlkj lwpukvksa dks

LVksj djus dk ç;kl djsaxs tks ,d LVªDpj }kjk laHko gSa tSls ,d iqLrd dk lEiw.kZ fooj.k gks vxj laxzfgr djuk gS rks

blds laHkkfor xq.k /keZ gks ldrs gSa & bldk uke] bldk eqY;] bldh i"B la[;k rFkk ys[kd dk uke bR;kfnA lh

çksxzkfeax ds MkVk Vkbi ds vuqlkj iqLrd ds uke dks djSDVj ,sjs ;k djSDVj i‚baVj ds enn ls LVksj dj ldrs gSa

vcdh eqY; dks ¶yksV MkVk Vkbi ls] i`"B la[;k dks bfUVtj MkVk Vkbi ls ,oa ys[kd dk uke iqu% djSDVj ,sjs ls ;k

djSDVj i‚baVj lsA

9.2 STRUCTURE DEFINITION

Structure is a user-defined data type in C which allows you to combine different data types to store a

particular type of record. Structure helps to construct a complex data type in more meaningful way. It

is somewhat similar to an Array. The only difference is that array is used to store collection of similar

datatypes while structure can store collection of any type of data. As we know that Array is collection

of the elements of same type, but many time we have to store the elements of the different data types.

Suppose Student record is to be stored, then for storing the record we have to group together all the

Chapter 12 File Processing

21

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: struct tag { data_type1 member1; data_type2 member2; data_type3 member3; };

Alternate Syntax of structure: struct structure_name { data_type member1; data_type member2; 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.

'O' Level M3:R4 C-LANGUAGE

22

Self Referential Structures and Linked Lists 10.1 WHAT IS A DATA STRUCTURE? A data structure is a specialized format for organizing and storing data. General data structure types include the array, the file, the record, the table, the tree, and so on. Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and worked with in appropriate ways.

डाटा सटरकचय डाटा को सही तयीक स यखन एवॊ छाटन हत एक ववशष पोभट ह साभानम डाटा सटरकचय भ ,sjs पाइर, रयकॉडड, टफर एवॊ री इतमादद होत हA 10.1.1 Classification of Data Structures If the data contains a single value this can be organized using primitive data type. If the data contains set of values they can be represented using non-primitive data types.

Data structures can be classified into two types:

Linear data structures Non-linear data structures

Linear Data Structures

In linear data structure the elements are stored in sequential order. The linear data structures are

Array: Array is a collection of data of same data type stored in consecutive memory location and is referred by common name

Linked list: Linked list is a collection of data of same data type but the data items need not be stored in consecutive memory locations.

Stack: A stack is a Last-In-First-Out linear data structure in which insertion and deletion takes place at only one end called the top of the stack.

Queue: A Queue is a First in First-Out Linear data structure in which insertions takes place one end called the rear and the deletions takes place at one end called the Front.

Non-Linear Data Structure: Elements are stored based on the hierarchical relationship among the data. The following are some of the Non-Linear data structure

Trees: Trees are used to represent data that has some hierarchical relationship among the data elements.

Chapter 12 File Processing

23

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.

'O' Level M3:R4 C-LANGUAGE

24

Stack and Queues 11.1 INTRODUCTION

In this chapter we introduce queues and stacks as data structures, e.g., for managing tasks. They follow similar principles of organizing the data. Each provides simple functions for adding and removing elements. But they differ in terms of the order in which the elements are removed. They can be implemented easily as an abstract data type in C, like the abstract arr type of arrays that we discussed in the previous chapters.

While studying linked list we have seen insertion and deletion of element is possible at any place in the list. There are certain situations in which items may be inserted or removed only at one end. Stacks and Queues are data structures.

Stack is a special type of data structure where elements are inserted from one end and elements are deleted from the same end. The position from where elements an inserted and from where elements are deleted is termed as top of the stack. Thus stack is a homogeneous collection of elements of any one type, arranged linearly with access at one end only.

In order to clarify the idea of a stack let us consider some real life examples of stack. A stack of book is a good analogy: we can’t read any book in the stack without first removing the books that are stacked on top of it. In the same way, plates in a hotel are kept one on top of each other. When a plate is taken it is usually taken from the top of the stack. Using this approach, the last element inserted is the first element to be deleted out, and hence, stack is also called Last In First Out (LIFO) data structure. Although the stack may seem to be a very restricted type of data structure, it has many important applications in computer science.

इस अधमाम भ हभ डाटा सटरकचय क सटवरऩ भ कसस एवॊ सटटक स ऩरयचम कयामगA म डाटा orgnaise कयन क साभानम मसधानत को पारो कयत हA म ककसी बी ततव को ऐड एवॊ रयभव कयन भ सहामक होत हA LVSd vkSj D;w nks blh rjg ds MkVk LVªDplZ

gSa tks dsoy fyLV ds 'kq: ;k var esa gh dksbZ Hkh dk;Z dj ldrs gSaA LVSDl esa ,yhesaV~l dk bUl'kZu vkSj fMyh'ku VkWi

,aM ij laHko gSA tcfd D;wt esa bUl'kZu dsoy ,d ,aM ij gh laHko gksrk gS ftls jh;j dgk tkrk gS ,oa fMyh'ku nwljs

,aM ij laHko gksrk gS ftls ÝaV dgk tkrk gSA

11.2 REPRESENTATION OF STACKS

It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). The last element to be added is the first to be removed (LIFO: Last In, First Out).

Chapter 12 File Processing

25

LVSDl ,d yhfu;j MkVk LVªDpj gSA ysfdu bl MkVk LVªDpj esa] fyLV ds dsoy ,d ,aM ls gh ,yhesaV~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 bEIyhesaVs'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;esa'kUl }kjk fu/kkZfjr dh tkrh gSA LVSd dh vf/kdre

{kerk ls ckgj ,yhesaV~l dks iq'k djus dk iz;kl gh LVSd vksoj ¶yks dgykrk gSA

'O' Level M3:R4 C-LANGUAGE

26

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 çksxzkfeax 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 VfeZusV gksrs gh oSY;w Hkh

eseksjh ls xk;c gks tkrh gS D;ksafd ;g ijekusaV 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 gS a &

These are:

Creation of a new file Opening an existing file

12

Chapter 12 File Processing

27

Reading from a file Writing to a file Moving to a specific location in a file (seeking) Closing a file

Here we write a program to read a file and display its contention the screen. We will first list the program and show what it does, and then dissect it line by line. Here we come with a sample program displaying just content of a file…

/* Display contents of a file on screen. */ # include "stdio.h" void main( ) {

FILE *fp; char ch; fp = fopen ( "Hello.txt", "r" ); while (1) {

ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf ( "%c", ch ) ;

} fclose ( fp ) ;

}

On execution of this program it displays the contents of the file ‘Hello.txt’ on the screen. To use file handling function we need to #include stdio.h header file into the program then only you can be able to use these. Now we see them in detail about the functioning of these.

Opening a file Before we can read (or write) information from (to) a file on a diskwe must open the file. To open the file we have called the functionfopen( ). It would open a file “Hello.txt” in ‘read’ mode, which

tellsthe C compiler that we would be reading the contents of the file.Note that “r” is a string and not a character; hence the doublequotes and not single quotes. In fact fopen( ) performs threeimportant tasks when you open the file in “r” mode: fdlh Hkh Qkby dks jhM ;k jkbZV djus ds fy, igys gesa ,d Qkby i‚baVj osfj,cy fMDysvj dj mles dfFkr Qkby

dks LVªhe djuk iM+rk gS QyLo:i vki mles fdlh Hkh çdkj dk v|ru dj ldrs gSaA fdlh Hkh Qkby esa D;k

v‚ijs'ku fd;k tk ldrk gS blds fy, vkidks lqfuf'pr djuk iM+sxk dh vki ml Qkby dks fdl Qkby eksM esa vksiu

dj jgs gSaA Firstly it searches on the disk the file to be opened and then It loads the file from the disk into a place in memory called buffer. It sets up a character pointer that point to the first character of the buffer. To make sure opening a file you need to declare a file pointer variable first then you can use fopen() to buffer a file in the program. Here we see…

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.