Vous êtes sur la page 1sur 89

1|Page

Unit-I
Chapter 1.1: Computer Systems

Computer is an advanced electronic device that takes raw data as input from the user
and processes it under the control of set of instructions (called program), gives the
result (output), and saves it for the future use.

Functionalities of a computer

Any digital computer carries out five functions in gross terms:


 Takes data as input.
 Stores the data/instructions in its memory and use them when required.
 Processes the data and converts it into useful information.
 Generates the output
 Controls all the above four steps.
Advantages

Following list demonstrates the advantages of computers in today's arena.


High Speed

 Computer is a very fast device.


 It is capable of performing calculation of very large amount of data.
 The computer has units of speed in microsecond (1/10 6), nanosecond (1/109),
and even the picosecond (1/1012).
 It can perform millions of calculations in a few seconds as compared to man
who will spend many months for doing the same task.
Accuracy

 In addition to being very fast, computers are very accurate.


 The calculations are 100% error free.
 Computers perform all jobs with 100% accuracy provided that correct input
has been given.
Storage Capability

 Memory is a very important characteristic of computers.


 A computer has much more storage capacity than human beings.
 It can store large amount of data.
 It can store any type of data such as images, videos, text, audio and many
others.
Diligence

 Unlike human beings, a computer is free from monotony, tiredness and lack of
concentration.
 It can work continuously without any error and boredom.
 It can do repeated work with same speed and accuracy.
Versatility

 A computer is a very versatile machine.


 A computer is very flexible in performing the jobs to be done.
 This machine can be used to solve the problems related to various fields.
2|Page
 At one instance, it may be solving a complex scientific problem and the very
next moment it may be playing a card game.
Reliability

 A computer is a reliable machine.


 Modern electronic components have long lives.
 Computers are designed to make maintenance easy.
Automation

 Computer is an automatic machine.


 Automation means ability to perform the given task automatically.
 Once a program is given to computer i.e., stored in computer memory, the
program and instruction can control the program execution without human
interaction.
Reduction in Paper Work

 The use of computers for data processing in an organization leads to reduction


in paper work and results in speeding up a process.
 As data in electronic files can be retrieved as and when required, the problem
of maintenance of large number of paper files gets reduced.
Reduction in Cost

 Though the initial investment for installing a computer is high but it


substantially reduces the cost of each of its transaction.

Types of Computers:
Computers can be broadly classified by their speed and computing power.

S. No. Type Specifications

1 Micro It is a single user computer system having moderately


computer powerful microprocessor

2 Mini Computer It is a multi-user computer system which is capable of


supporting hundreds of users simultaneously.

3 Main Frame It is a multi-user computer system which is capable of


supporting hundreds of users simultaneously. Software
technology is different from minicomputer.

4 Supercomputer It is an extremely fast computer which can execute


hundreds of millions of instructions per second.

Super computers

The most powerful computers in terms of performance and data processing are the
supercomputers. These are specialized and task specific computers used by large
organizations. These computers are used for research and exploration purposes,
like NASA uses supercomputers for launching space shuttles, controlling them and
for space exploration purpose. The supercomputers are very expensive and very
large in size. It can be accommodated in large air-conditioned rooms; some super
computers can span an entire building. In 1964, Seymour cray designed the first
supercomputer CDC 6600.
3|Page
Mainframe Computers
Mainframe computers can also process data at very high speeds vi.e., hundreds of
million instructions per second and they are also quite expensive. Normally, they are
used in banking, airlines and railways etc., for their applications.
Mini Computers
Mini computers are lower to mainframe computers in terms of speed and storage
capacity. They are also less expensive than mainframe computers. Some of the
features of mainframes will not be available in mini computers. Hence, their
performance also will be less than that of mainframes.
Micro Computers
The invention of microprocessor (single chip CPU) gave birth to the much cheaper
microcomputers. They are further classified into

 Desktop Computers
 Laptop Computers
 Handheld Computers(PDAs)

Desktop Computers

Today the Desktop computers are the most popular computer


systems. These desktop computers are also known as personal
computers or simply PCs. They are usually easier to use and more
affordable. They are normally intended for individual users for their
word processing and other small application requirements.

Laptop Computers

Laptop computers are portable computers. They are lightweight


computers with a thin screen. They are also called as notebook
computers because of their small size. They can operate on batteries
and hence are very popular with travellers. The screen folds down
onto the keyboard when not in use.

Handheld Computers

Handheld computers or Personal Digital Assistants (PDAs) are pen-


based and also battery-powered. They are small and can be carried
anywhere. They use a pen like stylus and accept handwritten input
directly on the screen. They are not as powerful as desktops or
laptops but they are used for scheduling appointments, storing
addresses and playing games. They have touch screens which we use with a finger or
a stylus.

HARDWARE:
All types of computers follow a same basic logical structure and perform the
following five basic operations for converting raw input data into information useful
to their users.
4|Page

Secondary
Memory

Input Unit
This unit contains devices with the help of which we enter data into computer. This
unit makes link between user and computer. The input devices translate the
information into the form understandable by computer.
CPU (Central Processing Unit)
CPU is considered as the brain of the computer. CPU performs all types of data
processing operations. It stores data, intermediate results and instructions
(program). It controls the operation of all parts of computer. The processor performs
all the fundamental computation of the computer system.
CPU itself has following three components

 ALU(Arithmetic Logic Unit)


 Memory Unit
 Control Unit

ALU: It performs all the arithmetic and logical operations

Memory unit:

A processor chip has relatively little memory. It has only enough memory to hold a
few instructions of a program and the data they process. Complete programs and
data sets are held in memory external to the processor. This memory is of two
fundamental types: main memory, and secondary memory.

Main memory is sometimes called volatile because it loses its information when
power is removed. Main memory is within CPU and secondary memory is outside the
CPU. Secondary memory is usually nonvolatile because it retains its information when
power is removed.

Control unit: Control unit manages all the devices and synchronize the computer
instructions.

Output Unit
5|Page
Output unit consists of devices with the help of which we get the information from
computer. This unit is a link between computer and users. Output devices translate
the computer's output into the form understandable by users.
Hardware represents the physical and tangible components of a computer i.e. the
components that can be seen and touched.

Examples of Hardware are following:

 Input devices -- keyboard, mouse, scanner, etc.


 Output devices -- printer, monitor etc.
 Secondary storage devices -- Hard disk, CD, DVD etc.
 Internal components -- CPU, motherboard, RAM etc.

SOFTWARE
Software is a set of programs, which is designed to perform a well-defined function.
A program is a sequence of instructions written to solve a particular problem.
There are two types of software

 System Software and Application Software

System software:
The system software is collection of programs designed to operate, control, and
extend the processing capabilities of the computer itself. System software is
generally prepared by computer manufactures. These software products comprise of
programs written in low-level languages which interact with the hardware at a very
basic level. System software serves as the interface between hardware and the end
users.
Some examples of system software are Operating System, Compilers, Interpreter,
and Assemblers etc.

Examples :
1) Microsoft Windows
2) Linux 3) Unix
4) Mac OSX
5) DOS
6) BIOS Software
7) HD Sector Boot Software
8) Device Driver Software i.e Graphics Driver etc
9) Linker Software
10) Assembler and Compiler Software

Applications Software:

Application software products are designed to satisfy a particular need of a particular


environment. Application software run under System Software, and are made to do
a .specific task i.e (Word Processing etc), which have indirect access to the
hardware.
Application software may consist of a single program, such as a Microsoft's notepad
for writing and editing simple text. It may also consist of a collection of programs,
often called a software package, which work together to accomplish a task, such as
a spreadsheet package.
6|Page
General purpose application software Examples :
Google Chrome (Web Browser)
Microsoft Word (Word Processing)
Microsoft Excel (Spreadsheet software)
MySQL (Database Software)
Microsoft Powerpoint (Presentation Software)
iTunes (Music / Sound Software)
VLC Media Player (Audio / Video Software )
World of Warcraft (Game Software)
Adobe Photoshop (Graphics Software)

Specific application software:


Payroll Software
Student Record Software
Inventory Management Software
Income Tax Software and Railways Reservation Software

Chapter 1.2: Problem Solving

Algorithm :

An Algorithm is a step by step procedure to solve a given problem.


An algorithm consists of a set of explicit and unambiguous finite steps which, when
carried out for a given set of initial conditions, produce the corresponding output and
terminate in a fixed amount of time. By unambiguity it is meant that each step
should be defined precisely i.e., it should have only one meaning. This definition is
further classified with some more features.

According to D.E.Knuth, a pioneer in the computer science discipline, an algorithm


has five important features.

i) Finiteness: An algorithm terminates after a fixed number of steps.


ii) Definiteness: Each step of the algorithm is precisely defined, i.e., the actions to
be carried out should be specified unambiguously.
iii) Effectiveness: All the operations used in the algorithm are basic (division,
multiplication, comparison, etc.) and can be performed exactly in
a fixed duration of time.
iv) Input: An algorithm has certain precise inputs, i.e. quantities, which are
specified to it initially, before the execution of the algorithm
begins.
v) Output: An algorithm has one or more outputs, that is, the results of
operations which have a specified relation to the inputs.

Let us take one example to illustrate all the features of an algorithm.

Example1: Suppose, we have to develop an algorithm to add two numbers


Step 1: Input Two numbers a, b
Step 2: sum = a + b
Step 3: Print sum
Step 4: Stop
7|Page
The algorithm terminates after 4 steps. This explains the features of finiteness.
Action of each step is precisely defined. Input of our algorithm is two integers and
output is the ‘sum’.

Example 2: Algorithm to find largest number from two numbers.

Step 1 : Read two numbers n1 and n2.


Step 2 : If n1 > n2 then
large = n1
else
large = n2
Step 3 : Print large
Step 4 : Stop

Example 3: Suppose, we have to develop an algorithm to convert an integer


numerical score (0 to 100) scored by a student in a particular test into letter grades
(A, B, C, D, E) using the following procedures.

Numerical Score Letter grade


Less than 40 E
40 to 54 D
55 to 69 C
70 to 85 B
More than 85 A

Algorithm is defined as follows:

Step1 Input the score of a student.


Step2 If the score <40 then print “E”: END
Step3 If the score is >= 40 and < 55,then print “D”:END.
Step4 If the score >= 55 and < 70 then print “C” :END
Step5 If the score is >= 70 and <= 85 then print “B”:END
Step6 If the score > 85 then print “A”
Step7 End of a program.

Example 4: Algorithm to find smallest number from two numbers.

Step 1 : Read two numbers n1 and n2.


Step 2 : If n1 < n2 then
Small = n1
else
Small = n2
Step 3 : Print Small
Step 4 : Stop
Example 5: Algorithm to find smallest number from N numbers.
Step 1 : Read N
Step 2: Read Num
Step 3 : Small = Num
Count = 1
Step 4 : Read Num
Step 5 : If Num < Small then
8|Page
Small = Num
Step 6 : Count = Count +1
Step 7 : If Count < N then Goto step 4
Step 8 : Print Small
Step 9 : Stop

Example 6: Algorithm to find factorial of a given Number


Step 1 : Read N
Step 2: Fact=1
Step 3 : Count = 1
Step 4 : Fact = Fact * Count
Step 5 : Count = Count +1
Step 7 : If Count < = N then Goto step 4
Step 8 : Print Fact
Step 9 : Stop

Example 7: Algorithm to find sum of N positive integer numbers


Step 1 : Read N
Step 2: Sum = 0,
Step 3 : Count = 0
Step 4 : Read Num
Step 5 : Sum=Sum + Num
Step 6 : count = count +1
Step 7 : If Count < N then goto step 4
Step 8 : Print Sum
Step 9 : Stop

Example 8: Algorithm to find GCD of two given numbers


Step 1 : Read M,N
Step 2: temp = Remainder of M / N i.e. temp = M%N
Step 3 : M=N
Step 4 : N=temp
Step 5 : if N > 0 then goto Step 2
Step 6 : GCD = M
Step 7 : Print GCD
Step 8 : Stop
Example 9: Algorithm to find whether the given number is Prime Number or
not
Step 1 : Read Num
Step 2: Prime = True
Step 3 : I = 2
Step 4 : Rem = Num % I
Step 5 : If Rem = 0 then Prime =False
Step 6 : I = I + 1
Step 7 : If I < N then Goto step 4
Step 8 : If Prime = True then
Print Num is a prime number
Else
Print Num is not a prime number
Step 9 : Stop
9|Page
Example 10: Algorithm to print Fibonacci series upto 15 terms
Step 1 : f1=0
f2 = 1
Step 2: Print f1,f2
Step 3 : Count = 2
Step 4 : f3 = f1 + f2
Step 5 : Print f3
Step 6 : Count = Count + 1
Step 7 : f1 = f2
Step 8 : f2 = f3
Step 9 : If Count < 15 then Goto step 4
Step 10 : Stop

FLOWCHART

Flowcharts often facilitate communication between programmers and business


people. These flowcharts play a vital role in the programming of a problem and are
quite helpful in understanding the logic of complicated and lengthy problems. Once
the flowchart is drawn, it becomes easy to write the program in any high level
language.
Advantages of Using Flowcharts:
The benefits of flowcharts are as follows:
 Communication: Flowcharts are better way of communicating the logic of a
system to all concerned.
 Effective analysis: With the help of flowchart, problem can be analysed in more
effective way.
 Proper documentation: Program flowcharts serve as a good program
documentation, which is needed for various purposes.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part.

Flowchart Symbols

Flowcharts are usually drawn using some standard symbols; however, some special
symbols can also be developed when required. Some standard symbols, which are
frequently required for flowcharting many computer programs are shown.

Terminator: An oval flow chart shape indicates the start or end of the process,
usually containing the word “Start” or “End”.

Process: A rectangular flow chart shape indicates a normal/generic process flow


step. For example, “M = M*F” or similar.
10 | P a g e
Decision: A diamond flow chart shape indicates a branch in the process flow. This
symbol is used when a decision needs to be made, commonly a Yes/No question or
True/False test.

Connector: A small, labelled, circular flow chart shape used to indicate a jump in the
process flow. Connectors are generally used in complex or multi-sheet diagrams.

Input/Output: A parallelogram that indicates data input or output (I/O) for a


process. Examples: Read X from the user, Print X. or Display sum.

Direction: used to show the flow of control in a process. An arrow coming from one
symbol and ending at another symbol represents that control passes to the symbol
the arrow points to.

These are the basic symbols used generally. Now, the basic guidelines for drawing
a flowchart with the above symbols are that: _ In drawing a proper flowchart, all
necessary requirements should be listed out in logical order.

 The flowchart should be neat, clear and easy to follow. There should not be
any room for ambiguity in understanding the flowchart.
 The flowchart is to be read left to right or top to bottom.
 A process symbol can have only one flow line coming out of it.

Example: Flow Chart for Adding 3 numbers:


11 | P a g e
Example: Flow chart to find largest of two numbers

PROGRAM DEVELOPMENT STEPS:

The following steps are used in sequence for developing an efficient program:
 Specifying the problem statement
 Analyse the problem
 Designing an algorithm to solve the problem
 Implementing the algorithm (Coding)
 Testing and Validating
 Documentation and Maintenance.
Specifying the Problem:
The Problem which has to be implemented into a program must be
thoroughly understood before the program is written. Problem must be analyzed to
determine the input and output requirements of the program. A problem is created
with these specifications.
Analyse the problem:
Analyzing the problem involves identifying the problem (a) inputs, that is, the data
you have to work with; (b) outputs, that is, the desired results; and (c) any
additional requirements or constraints on the solution. At this stage, you should also
determine the required format in which the results should be displayed (for example,
as a table with specific column headings) and develop a list of problem variables and
their relationships. These relationships may be expressed as formulas.

Designing an Algorithm:
Designing an algorithm requires to develop a list of steps called an algorithm
to solve the problem and to then verify that the algorithm solves the problem as
intended. Writing the algorithm is often the most difficult part of the problem-solving
process.
To improve clarity and understandability of the program flow charts are
drawn using the algorithms.

Implementing(Coding):
The actual program is written in the required programming language with
the help of information depicted in flow charts and algorithms. You must convert
each algorithm step into one or more statements in a programming language.
12 | P a g e
Testing and Validating:
Testing and verifying the program requires testing the completed program to
verify that it works as desired. Run the program several times using different sets of
data to make sure that it works correctly for every situation provided for in the
algorithm.

Documentation and Maintenance:


Documentation is the process of collecting, organizing and maintaining, in
written the complete information of the program for future references. Maintenance
is the process of upgrading the program according to the changing requirements.
For writing up the instructions as a program in the way that a computer can
understand, we use programming languages.

Creating and Running Programs:

Developing a program in a compiled language such as C requires at least four steps:

1. editing (or writing) the program


2. compiling it
3. debugging it
4. linking it
5. Executing it.

The below flow chart shows the steps diagrammatically.


13 | P a g e

Run the executable


object code

we will now cover each step


separately.
14 | P a g e
Editing

You write a computer program with words and symbols that are understandable to
human beings. This is the editing part of the development cycle. You type the
program directly into a window on the screen and save the resulting text as a
separate file. This is often referred to as the source file. C program is stored in a file
with the extension .c . To create a program login in as user in unix system. Use text
editor vi to create your program.

The syntax for opening a file is

vi filename.c

Where filename is the name of your C program. When editing is over, the file is
saved on disk which can be referred later by its name. To save the file press ESC key
and then : wq.

Compiling
You cannot directly execute the source file. To run on any computer system, the
source file must be translated into binary numbers understandable to the computer's
Central Processing Unit. This process produces an intermediate object file - with the
extension .obj, the .obj stands for Object. To compile c program , the command used
is ‘cc’. Syntax of the command is
$ cc filename.c

There are lots and lots of options for cc. One of it is –o. To generate output in the
specified file, option –o is used. The syntax is

-o filename
For example $ cc filename.c –o filename.out
Will generate output in the file called filename.out. If you do not use this
option, cc will produce an executable called a.out.

Debugging:
There is a possibility of occurrence of errors in programs. These errors must
be removed to ensure proper working of programs. Hence error check is made. This
process is known as “Debugging”.
Types of errors that may occur in the program are:
 Syntactic Errors: These errors occur due to the usage of wrong syntax for
the statements. Syntax means rules of writing the program.
Example: x=z*/b;
There is syntax error in this statement. The rules of binary operators state that there
cannot be more than one operator between two operands.
 Runtime Errors: These Errors are determined at the execution time of the
program.
Example: Divide by zero, Range out of bounds
Square root of a negative number
 Logical Errors: These Errors occur due to incorrect usage of the instruction in
the program. These errors are neither displayed during compilation or
execution nor cause any obstruction to the program execution. They only
cause incorrect outputs. Logical Errors are determined by analyzing the
15 | P a g e
outputs for different possible inputs that can be applied to the program. By this
way the program is validated.

Linking

Many compiled languages come with library routines which can be added to your
program. Theses routines are written by the manufacturer of the compiler to perform
a variety of tasks, from input/output to complicated mathematical functions. In the
case of C the standard input and output functions are contained in a library (stdio.h)
so even the most basic program will require a library function. After linking the
executable file is generated with the extension .exe.

Executing program

Thus the text editor produces .c source files, which go to the compiler, which
produces .obj object files, which go to the linker, which produces .exe executable file.
You can then run .exe files as you can other applications,

The command to execute the file and see the out put is
./a.out

Some times the program may request for some data to be entered through the
keyboard. When there is wrong with the program logic or data, then it is necessary to
correct the source program or data.
Computer languages: Languages are used for Communication with the System.
There are so many Languages developed to establish communication between
computers and humans. Like this way when a user wants to perform any operation
then a user must have to use some Program or some Request. And the System will
then respond to the Request of the user.
All the Programming Languages also developed in the form of some Generations
those are as Explained below:-
1) 1 GL or Machine Language: This is also called as the First
Generation Computer Languages. And in these Machine Languages has developed.
The Machine Language Programs contains all the instructions in the Binary Form and
we know that the Program which has written into the Machine Language is easily
understandable to the computer System. So that it is very difficult to understand for
the user because all the instructions are written into the Form of 0 and 1.
Basically this Language was used for writing the Machine Instructions. But the main
Advantage is that this is very easy for the computer and this will also increase the
speed of processing of the computer system. And the Main Limitation is that this will
consume lots of time of user, if a user wants to understand any Program and this is
very difficult to learn.
2) 2 GL or Assembly Language: As we know that the Program which is written into
the Machine Language are very difficult to understand for the user. So that, there is
the Development of the new Programming Language, which is also known as the
second Generation Language. It is also known as the Assembly Language. In the
Assembly Language there are many mnemonics those are also called as the reserve
Words those are easy to understand to the users and those have some specific
meaning. Ex ADD A
16 | P a g e
But the Words are not Machine Language Oriented means the words are Just the
English Language Forms so that they are not easily understand by the Machine and
we must have to convert the Words of the Assembly Language into the Machine
Language. For converting the Assembly Language into the Machine Language we
must uses the Assembler. This converts the whole program which is written in the
Assembly Language into the Machine Language.

3) 3 GL or Some High Level Languages: Due to the Development of the Assembly


Language and the Mnemonics there is also the new development of some High Level
Languages those are used for making the Programs. Important third generation
languages are FORTRAN, COBOL, C, BASIC ,Pascal and Java etc., A high level
language is easier to learn and program than an assembler language.
All the High Level Programming Languages are user friendly means the syntax of
theses Languages is quite simple because they contains all the words those are in the
form of English Language but the main problem is that they are not machine
oriented. Means the program which is written into the High Level Languages is not
understand by the Computer, so that the Program must be converted into the
machine Language and the program which is written into the human Language will
cause the Computer in slow of processing.

4) 4 GL Program: And the Programs those will be written into the 4GL will also be
easier to understand and also contains some Language Translator for converting the
High Level Languages into the Machine Languages. Most fourth generation languages
are non-procedural languages that encourage users and programmers to specify the
results they want.
Fourth generation language consists of a variety of software tools and they
tend to be non-procedural than conventional programming languages. Non
procedural languages need only specify what has to be accomplished. Some of these
non-procedural languages are natural languages. There are seven categories of
fourth generation languages Query languages, report generation, graphic languages,
application generation, very high-level programming languages, application software
packages and PC tools. Ex. SQL, PL/SQL, Oracle reports, SPSS, SAS, Informix, R etc.,
17 | P a g e

UNIT-2

SELECTION-MAKING DECISIONS: TWO-WAYS SELECTION:if-else,null else,nested if,


examples,Multi-way Selection:Switch,else-if,example.

Decision making with ‘if’ statements:

The if Statement is a powerful decision making statement and is used to control the flow of
execution of statements.it is basically a two-way decision statement and is used in conjunction
with an expression.
They are 3 syntax of if statements

 Simple if
 If else
 And nested

Simple if:
If(test expression)
{
Statement-block;
}
The statement-block may be a single statement or a group of statements. If the expression is true
the statement-block will be executed. Otherwise the statement-block will be skipped and the
execution will jump after the closing brace.

Test True
Expression

False Statement
Block
18 | P a g e

End

Ex: if(a<5)
Printf(“%d”,a);
//program to grade of mark//

#include<stdio.h>
int main()
{
int marks;
printf(“\n enter marks”);
scanf(“%d”,&marks”);
if(marks>=90)
printf(“Grade A”);
return 0;
}
Syntax of if else:

The general form of if-else statement:

if(expression)
{
Statement_block(1);
}
else
{
Statement_block(2);
}

Test True
Expression

False Statement
Block1

Statement
Block2

End

If the expression is true statement-block1 will be executed. Otherwise statement block2 will
Be executed. In both cases control is transferred subsequent o statements after if statement.
19 | P a g e
//program to find leap year

#include<stdio.h>
int main()
{
int year;
printf(“enter year”);
scanf(“%d”,&year);
if(year%4==0)
printf(“leap year”);
else
printf(“not leap year”);
return 0;
}

Nested of if-else
When a series of decision are involved, we may have to use more than one if-else statement in
nested form.
Syntax:

if(cond-1)
Stmt1;
else if(cond-2)
Stmt2;
else if(cond-3)
Stmt3;
else
Stmt4;

//Example program to print grades

#include<stdio.h>
int main()
{
int marks;
printf(“enter marks”);
scanf(“%d”,&marks);
if(marks>=90)
printf(“gradeA”);
else if(marks>=80)
printf(“Grade B);
else if(marks>=70)
printf(“Grade C”);
else
printf(“Fail”);
return 0;
}

//Example program to print Grades using logical operators &&

#include<stdio.h>
int main()
{
int marks;
printf(“enter marks”);
Scanf(“%d”,&marks);
20 | P a g e
if((marks>=90)&&(marks<=100)
Printf(“Grade A”);
if((marks>=80)&&(marks<90))
Printf(“Grade B”);
if((marks>=70)&&(mark<80)
printf(“Grade C”);
return 0;
}

//Exmple program to print Grades using logical operators ||

#include<stdio.h>
int main()
{
char op;
printf(“\n enter y for yes and n for No”);
scanf(“%c”,&op);
if(op==’Y’||op=’y’)
printf(“the selected option is ye”);
if(op==’N’||op=’n’)
printf(“The selected option is No”);
return 0;
}

The switch Statement:


When one of the many alternatives is to be selected, we can design a program using if
statements to control the selection. C has a built-in multi way decision statement known as
‘switch’. The Switch statement tests the value of a given variable or expression against a list of
case values and when a match is found, a block of statements associated with that case is executed.

Syntax:

switch(expression)
{
case value1:block-1;
break;
case value2:block-2;
break;
……….
default: default-block;
break;
}
The expression is an integer expression or characters value1, value2…… are constants and are
known as case labels. Each of these values should be unique within a switch statement. block1,
block2…. Are statements lists and may contain zero or more statements. There is no need to put
braces around these blocks .case labels end with colon (:). When the switch is executed, the value
of the expression is successively compared against the values value-1, Value-2….. if a case is
found whose value matches with the value of the expression, then the block of statements that
follow the case are executed.
The break statement at the end of each block signal the end of a particular case and causes an exit
from the witch statement, transferring the control to the statements following the switch. The
default is an optional case. when present, it will be executed if the value of the expression does not
match with any of these case values. if not present , no action takes place if all matches fail and
control goes to the next statement of switch.
21 | P a g e
/*Program to operate switch statement*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,sum,diff,product,division;
char op;
clrscr();
Printf(“enter two operands”);
Scanf(“%d%d”,&a,&b);
printf(“operator + - * / ? “);
fflush(stdin);
scanf(“%c”,&op);
switch(op)
{
case ‘+’:sum=a+b;
Printf(“sum=%d\n”,sum);
break;
case ‘-‘ : diff=a-b;
printf(“difference=%d\n”,diff);
break;
case ‘*’: product=a*b;
printf(“product=%\n”,product);
break;
case ‘/’: division=a/b;
printf(“division=%d\n”,product);
break;
default: printf(“error”);
break;
}
getch();
}

Goto Statement:
The goto statement is used to branch unconditionally from one point to another in the program.
The goto requires a label in order to identify the place where the branch is to be made. The label is
made immediately before the statement where the control is to be transferred.

goto label;

label: statement;
….. …
The label: can be anywhere in the program either or after the goto label.

Loops:

There may be a situation, when we need to execute a block of code several number of times. In
general, statements are executed sequentially. i.e., The first statement in a function is executed
first, followed by the second, and so on. Programming languages provide various control structures
that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of loop statements in most of the programming languages.

There are three forms of loop statements:

 for loop
22 | P a g e
 while loop
 do loop

The for loop

Syntax:

for(initialization; test condition; update expression)


{
statements ;
}

 initialization is an expression with side –effect that initializes a control variable (typically
an assignment), which can also be a declaration with initialization
 Condition is an expression of type Boolean
 Update is an expression with side –effect that typically consists in updating(i.e.,
increamenting or decrementing) the control variable
 Statement is a single statement (also called body of the loop)

Example : To print out integers up to 100.

for(i = 0 ;i< 100; i++)


printf(“%d”,i);

The while statement

It allows for the repetition of a statement.

Syntax:

While (Test condition )


{
Statement ;
}

 Condition is an expression of type Boolean


 Statement is a single statement (also called the body of the loop)

Since, by making use of a block, it is possible to group several statements into a single composite
statement, it is in fact possible to have more than one statement in the body of the loop.

Execution of loop:

 First, the condition is evaluated.


 If it is true, the statement is executed and the value of the condition is evaluated again ,
continuing in this way until the condition becomes false.
 At this point the statement immediately following the while loop is executed.

Hence , the body of the loop is executed as the condition says true . As soon as it becomes false we
exit the loop and continue with the following statement.

Example : print 100 stars.

int i =0;
while (i<100)
{
23 | P a g e
printf(“*”);
i++;
}

The do loop

In a while loop, the condition of end of loop is checked at the beginning of each iteration.
A do loop is similar to a while loop, with the only difference that the condition of end of loop is
checked at the end of each iteration.

Syntax :

do
{
statement
}while (condition);

 condition is an expression of type bollean


 statement is a single statement (also called the body of the loop)

Execution:

 First the statement is executed.


 Then the condition is evaluated, and if it is true , the statement is executed again,
continuing in this way until the condition becomes false.
 At this point the statement immediately following the do loop is executed.

Example: To print out integers up to 100.

int = 0;
do {
printf (“%d”, i);
i++;
}while(i< 100);

/* program to find factorial of a given integer using WHILE LOOP*/


#include<stdio.h>
int main ()
{
int n, fact, i;
printf(“enter an integer”);
scanf(“%d”, &n);
fact=1;
i=1;
while(i<=n)
{
fact =fact*i;
i++;
}
printf(“factorial of %d is %d\n”,n,fact);
return 0;
}
24 | P a g e
/*program to find sum n natural numbers using for loop*/
#include<stdio.h>
int main()
{
int n, sum,i;
printf(“enter an integer “);
scanf(“%d”,&n);
sum=0;
for(i=1;i<=n;i++)
{
sum =sum+i;
}
printf(“\n the sum of %d numbers is %d\n”, n,sum);
return 0;
}

/*program to find sum 1+1/2+1/3+1/4…….+1/n using for loop*/


#include<stdio.h>
int main()
{
int n, i;
float sum=0.0;
printf(“enter an integer”);
scanf(“%d”,&);
for (i=1;i<=n;i++)
{
Sum=sum+1.0/i;
}
printf(“\n The sum of series is %f\n”,sum);
return 0;
}

Chapter 5

ARRAY: An array is a group of related data items that share a common name and stored in
contiguous memory locations.
Arrays offer a convenient means of grouping together several related variables, in one
dimension or more dimensions. An array is also known as subscripted variable. Before using an
array its type and dimension must be declared. The elements are always stored in contiguous
memory locations. First element is at position ‘0’, so the last element is at position 1 less than the
size of the array.

Examples:
product part numbers:
int part_numbers[ ] = {123, 326, 178, 1209};
student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general form of a one-dimensional array
declaration is:

type variable_name [size]

type : base type of the array, determines the data type of each element in the array
size: how many elements the array will hold
variable_name : the name of the array
25 | P a g e

Examples:
int sample[10];
float float_numbers[100];
char last_name[40];

Initialization of arrays:
We can initialize the elements of an array in the same way as the ordinary variables when they are
declared.
type array-name [size] = {list of values};
The values in the list are separated by commas. If the number of values in the list is less than the
size, then only that many elements will be initialized. The remaining elements will be set to zero
automatically.

Ex.
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

ACCESSING ELEMENTS OF AN ARRAY:


Once an array is declared, the individual elements of the array can be referred by the use of
subscript. Subscript specifies the element position in the array. Subscript starts at 0. i.e. first
number is started at position 0, second number is started at position 1 etc.

Entering data into an array


int num[10];
for (i=0; i<10; i++)
{
printf (“enter a number”);
scanf (“%d”, & num [i]);
}
Reading data from an array
To add the elements of an array to variable sum
sum=0;
for (i=0; i<10; i++)
sum = sum + a [i];

TWO-DIMENSIONAL ARRAYS
So far we have looked at arrays with only one dimension. It is also possible for arrays to have two
or more dimensions. The two dimensional array is also called a matrix.
Consider the following data table
Sub1 sub2 sub3 sub4
Student1 10 20 30 40
Student2 5 7 8 15
Student3 3 2 4 50

The table contains a total of 12 values, i.e in each line. We can think of this table as a matrix
consisting of 3 rows and 4 columns. Each row represents the marks obtained in 4 subjects by a
particular student. Each column represents the marks obtained in a particular subject.
In mathematics, we represent a particular value in a matrix by using two subscripts, such as vij.
Here v denotes the entire matrix and vij refers to the value in the ith row and jth column.
For example in the above table v23 refers to the value 50. C allows us to define such tables of
items by using two-dimensional arrays, the above table can be defined in C as
int v[3][4];

Declaring Two dimensional array:

type array_name [row-size] [col-size];


26 | P a g e

ex: int A[3][2];

This array A consists of 3 rows and 2 columns and 6 elements altogether.


Initilization:
Like Single dimensional arrays the initialization can be done in two dimensional arrays. The
general form is
Syntax:
Type Arrayname [row size][col size]={list of values};
Ex. int A[3][2]={{1,2},{3,4},{5,6}};

This declares an Array with 3 rows and 2 columns.


Array looks like the below matrix
12
34
56

If the values are missing in an initializer, they are automatically set to zero. For instance the
statement static int num[2][3] = {{1,1},{2}};
will initialize the first two elements of the first row to one, the first element of the second row to
two. And all other elements to zero.

Array elements in Memory:

Consider the following array declaration


int a[3][3];
12 22 23
a= 33 11 13
14 15 11
This declaration allots 18 bytes in memory as each integer occupies 2 bytes. i.e 9* 2=18. The
elements are stored in contiguous memory locations in the order of row. That means all the
elements in first row and then next row elements follows. The arrangement of memory for the
above examples.

a[0][0] a[0][1] A[0][2] a[[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2]


12 22 23 33 11 13 14 15 11
1002 1004 1006 1008 1010 1012 1014 1016 1018

.Ex: Matrix Addition Program

/* program to add two matrices */


#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,i,j;
printf("enter a size of the array :" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
27 | P a g e
scanf("%d",&a[i][j]);
printf("enter the elements of matrix B\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&b[i][j]);
for (i=0;i<m;i++)
for (j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The two dimensional array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",c[i][j]);
printf("\n");
}
return 0;
}

Ex: Matrix Multiplication Program


#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("enter a size of the array A:" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");

for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter a size of the array B:" );
scanf("%d%d",&p,&q);
printf("enter the elements of matrix B\n");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
scanf("%d",&b[i][j]);
if (n==p)
{
for (i=0;i<m;i++) /*initialisation of C*/
for (j=0;j<q;j++)
c[i][j]=0;

for (i=0;i<m;i++)
for (j=0;j<q;j++)
for (k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
printf("The Resultant array\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
else
printf("Matrix multiplication is not possible\n");
28 | P a g e
}

Chapter 6: Strings:
A string is an array of characters. Any group of characters defined between double quotation marks
is a constant string.
Ex.
“c programming”
“Rama is a good boy”
Declaration:
char string_name[size];
A string variable is any valid C variable and is always declared as an array. The size determines the
number of characters in the string.
char city[10];
char name[20];
When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore the size should be equal to the maximum number
of character in the string plus one. Character array may be initialized when they are declared. C
permits a character array to be initialized in either of the following two forms.

static char city [7] = {‘g’,’u’,’n’,’t’,’u’,’r’,’\0’};


city[7] = “guntur”;

The reason that city had to be 7 elements long is that the string ‘guntur’ contains 6 characters and
one element space is provided for the null terminator.
C also permits us to initialize a character array without specifying the number of elements. In such
cases, the size of the array will be determined automatically based on the number of elements
initialized. For example
static char string [] = {‘g’,’o’,’o’,’d’,’\0’}
defines the array string as a five element array.

Reading strings from terminal:


The input function scanf() can be used with %s format specification to read in a string of
characters.
char address[15];
scanf(“%s”,address);

Note that unlike previous scanf() calls, in the case of character arrays, the ampersand (&) is not
required before the variable name.
The scanf() function automatically terminates the string that is read with a null character and
therefore the character
29 | P a g e

STRING HANDLING FUNCTIONS:

strcat() -- concatenates two strings.


strcmp() -- compares two strings.
strcpy() -- copies one string over another.
strlen() -- finds the length of the string.
strlwr()-Converts string to lower case
strupr()-Converts string to uppercase

STRCAT():

strcat(str1, str2)
The strcat() function joins two strings together. Str1 and str2 are character arrays.
When the function strcat() is executed, str2 is appended to str1. It removes the ‘\0’ at the end of the
string, and places str2 from there.

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
printf("strings before concatenation\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
strcat(str1,str2);
printf("strings After concatenation\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
getch();
}

STRCMP():

The strcmp() function compares two strings identified by the arguments and has a value 0 if they
are equal. If they are not equal, it has the numeric difference between the first non-matching
characters in the strings.

strcmp(str1, str2)

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"ezra"};
char str[20];
30 | P a g e
clrscr();
printf("strings before comparision\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
if (strcmp(str1,str2)==0)
printf("strings are same\n");
else
printf("strings are different\n");
getch();
}

STRCPY():

strcpy(str1, str2);
Assigns the content of str2 to str1.

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
printf("strings before copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
strcpy(str1,str2);
printf("strings after copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
getch();
}

STRLEN():

Counts and returns the number of characters in string.


n = strlen(str);

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
int n;
clrscr();
n=strlen(str1);
printf("length of string %s is %d\n",str1,n);
n=strlen(str2);
printf("length of string %s is %d\n",str2,n);
getch();
}
31 | P a g e

Ex: Program to check whether a given string is palindrome or not using character array.
#include<stdio.h>
int main()
{
char a[20],b[20];
int i,n=0,flag=0;
printf(“\n Enter a string”);
scanf(“%s”,a);
n=strlen(a);
for (i=0;i<n;i++)
{
b[i]=a[n-(i+1)];
}
for (i=0;i<n;i++)
{
if (b[i]!=a[i])
flag=1;
}
if (flag==1)
printf(“\n %s is not palindrome”,a);
else
printf(“\n %s is palindrome”,a);
}
32 | P a g e

UNIT-III FUNCTIONS
C function can be classified into two categories
1) Library functions.
2) User defined functions.
main( ) is an example of user defined function. printf(), scanf(), sqrt(), cos(), strcat() belong to the
category of library functions.

Every program must have a main() function to indicate where the program has to begin its
execution. If a program was coded as a single function, the program may become too large and
complex and as a result the task of debugging, testing and maintaining becomes difficult.

If a program is divided into functional parts then each part may be independently coded and later
combined into a single unit. These sub programs called functions are must easier to understand,
debug and test. A function is a self-contained block of code that performs a particular task.

type function_name (argument list);


{
local variable declarations;
stmt1;
stmt2;
-
-
return (expression);
}

All parts are not essential, some may be absent. For example, the argument list and its associated
argument declaration parts are optional.

The return statement is the mechanism for returning a value to the calling function. This is also an
optional statement. Its absence indicates that no value is being returned to the calling function.

The argument list contains valid variable names separated by commas. The list must be surrounded
by parenthesis. All argument variables must be declared for their types after the function header
and before the opening brace of the function box.

A function may or may not send back any value to the calling function. If it does, it is done
through the return statement. Function can return at most one value per call. A function name can
be called by simply using the function name in a statement.

A function can be declared with

1. Return value and arguments


2. Only arguments without return value
3. With return value and without arguments
33 | P a g e
4. Without return value and without arguments:

1. Example for Defining function with return value and arguments:

Example
#include <stdio.h>

int mul(a,b)
int a,b;
{
int m;
m=a*b;
return(m);
}
void main( )
{
int m,n,p; clrscr();
printf(“enter two numbers “); scanf(“%d
%d”,&m,&n);
p=mul(m,n); /*------- function call */
printf(“%d\n”,p);
}

When the compiler encounters a function call, the control is transferred to the function mul(x,y).
This function is then executed line by line and a value is returned when a return statement is
encountered. This value is assigned to p.

Points to remember:
1. A function may or may not return a value if it does, it can return only one value.
2. Functions return integer value by default.
3. When a function is supposed to return a non-integer value, its type must be explicitly specified
in the function header. Such a function should be declared at the start of the calling function.

2. Example: Function with arguments and without return value

/*program to add two numbers using a function*/


#include<stdio.h>
Void sum(x,y)
{
int res;
res = x+y;
printf(“\nSum of %d %d is %d “,x,y,res);
}
void main()
{
int a,b;
printf("enter a,b"); scanf("%d
%d",&a,&b);
sum(a,b); /* Function Call */
34 | P a g e
return 0;
}

3. Example: Function with return value without arguments.


/*program to find factorial of a given number using a function */
#include<stdio.h>
int factorial()
{
printf(“\n Enter a number”);
scanf(“%d”,&x);
int i,f;
f=1;
for(i=1;i<=x;i++)
f=f*i;
return(f);
}
void main()
{
int n,fn;
fn=factorial(); /* Function Call */
printf("the factorial %d is%d\n",n,fn);
}

4. Example: Function without return value without arguments.

#include <stdio.h>
void sum()
{
int a,b,c;
printf(“enter two numbers “); scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum is %d”,c);
}

void main( )
{
sum(); /*------- function call */
}

Example: Write a program to find Largest Element in an array

/*program to find largest element from an array using a function*/


#include<stdio.h>
#include<conio.h>

int largest(x,m) int x[],m;


{
int i,l=0;
for (i=0;i<m;i++) if(x[i]>l)
35 | P a g e
l=x[i];
return (l);
}

void main()
{
int a[10],i,n,large;
clrscr();
printf("enter size" ); scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("enter array element "); scanf("%d",&a[i]);
}
large=largest(a,n);
printf("the largest = %d\n",large);
getch();
}

Example: Write a program to sort an array of elements:

/*program to arrange array elements of a single dimensional array in sorted order using a
function*/
#include<stdio.h>
#include<conio.h>
sorting(a,n)
int a[],n;
{
int i,j,temp;
for (i=0;i<n-1;i++)
for (j=0;j<n-i-1;j++)
if (a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
void main()
{
int a[10],i,j,n,temp;
printf("enter size" ); scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("enter array element "); scanf("%d",&a[i]);
}

sorting(a,n); /* function call */

printf("the sorted array elements are\n");


for (i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
36 | P a g e

Call by value call by reference


There are two ways in which we can pass arguments to the functions a) call by value and b) call by
reference.
A) Call by value:
In this type, the value of actual arguments are passed to the formal arguments and the operation is
done on the formal arguments. Any change in the formal arguments does not affect the actual
arguments. Both the formal and actual arguments are allocated memory separately. Hence when
the function is called by the call by value method, it does not affect the actual arguments.
Example:
main()
{
int x,y, interchange(int,int);
printf(“Enter values of x and y”);
scanf(“%d %d”,&x,&y);
interchange(x,y);
printf(“\n In main prg x and y values are %d %d”,x,y);
return 0;
}
void interchange(int a, int b)
{
int t;
t=a;
a=b;
b=t;
printf(“\n In the function x and y values are %d %d”,a,b);
}
Output:
Enter values of x and y 5 6
In the function x and y values are 6 5
In main prg x and y values are 5 6.

Explanation:
In the above program we are passing values of actual parameters x and y to the function
interchange(). The formal arguments a, and b of the function receives these values. These values
are interchanges and printed. When the control return to the main again we are printing the values
of x, y . These are printed as they read from the keyboard. The change done in the function is not
affected actual arguments.
37 | P a g e

B) Call by reference:

In this type instead of passing values, address are passed as argument. Function operates on
address. Here the formal arguments are the pointers to the actual arguments. Only one storage
location is used here i.e for actual arguments only. Hence the changes made in the formal
arguments will remain with actual arguments also.

Example:
main()
{
int x,y, interchange(int*,int*);
printf(“Enter values of x and y”);
scanf(“%d %d”,&x,&y);
interchange(&x,&y);
printf(“\n In main prg x and y values are %d %d”,x,y);
return 0;
}

void interchange(int *a, int *b)


{
int t;
t=*a;
*a=*b;
*b=t;
printf(“\n In the function x and y values are %d %d”,*a,*b);
}
Output:

Enter values of x and y 5 6


In the function x and y values are 6 5
In main prg x and y values are 6 5.

3.2 RECURSION
Recursion is a special case of process, where a function calls itself.

A function is called recursive if a statement within the body of a function calls the same
function.

int factorial(x) int


x;
{
if (x ==1)
return(1);
else
return(x * factorial(x-1));
}

When writing recursive functions, you must have an if statement somewhere in the
recursive function to force the function to return without recursive call being executed. If you do
not do this and you call the function, you will fall in an indefinite loop, and will never return from
the called function.
38 | P a g e

/*program to find factorial of a number using a Recursive function*/


#include<stdio.h>
#include<conio.h>
int factorial(x) int x;
{
if (x<=1) return(1);
else return(x*factorial(x-1));
}
void main()
{
int n,fn;

clrscr();

printf("enter n");
scanf("%d",&n);

fn=factorial(n); /* Function Call */

printf("the factorial of %d is %d\n",n,fn);


getch();
}

In case the value of n is 4, main() would call factorial() with 4 as its actual argument, and
factorial() will send back the computed value. But before sending the computed value, factorial()
calls factorial() and waits for a value to be returned.

factorial(4) returns 4*factorial(3) 4*6 = 24


factorial(3) returns 3*factorial(2) 3*2 = 6
factorial(2) returns 2*factorial(1) 2*1 = 2
factorial(1) returns 1 Back

substitution
/* Program to find GCD of two numbers using a Recursive function */

#include<stdio.h>
#include<conio.h>
int gcd(int u,int v)
{
if (v==0) return(u);
else return(gcd(v,u%v));
}
int main()
{
int m,n,g;
clrscr();
printf("enter m and n"); scanf("%d
%d",&m,&n);
g=gcd(m,n); /*---------- Function Call */
printf("the gcd of %d and %d is %d\n",m,n,g);
return 0;
}
39 | P a g e
/* Program to find nth Fibonacci number using a Recursive function*/
#include<stdio.h>
#include <math.h>
int fib(n)
int n;
{
if (n==1) return(0);
else
if (n==2) return(1);
else return(fib(n-1)+fib(n-2));
}
void main()
{
int n,f;
clrscr();
printf("which term you want");
scanf("%d",&n);
f=fib(n);
printf("The %d th Fibonacci term is %d \n",n,f); getch();
}

Towers of Hanoi Problem


The Towers of Hanoi problem is a game, which comprises of three towers with discs stacked
around the first tower initially. The game involves shifting the disks across the adjoining
towers. There are some conditions that need to be adhered during the shifting.
1) A larger disk cannot be placed on a smaller disk.
2) Only one disk can be shifted at a time.
3) The end object is to replicate the initial stack of disks into another tower.

#include <stdio.h>
#include <conio.h>
void towers_hanoi(n,t1,t2,t3)
{
if (n==1)
{
printf("shift upper disk from tower %c to tower %c\n",t1,t2);
return;
}
towers_hanoi(n-1,t1,t3,t2);
printf("shift upper disk from tower %c to tower %c\n",t1,t2);
towers_hanoi(n-1,t3,t2,t1);
}
void main()
{
int n;
printf("enter the number of disks :");
scanf("%d",&n);
towers_hanoi(n,'A','B','C' );
printf("The %d disks in tower A are shifted to tower B\n",n);
}
3.3 SCOPE AND LIFETIME OF VARIABLES:
Variables in C differ in behavior from those in most other languages.
40 | P a g e
A variable in C can have any one of the four storage classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

SCOPE: The scope of a variable determines over what part(s) of the program a variable is
actually available for use.

LIFETIME: Lifetime refers to the period during which a variable retains a given value
during execution of a program (alive).

A variable may also be broadly categorized depending on the place of their declaration as
internal (local) or external (global). Internal variables are those which are declared within a
particular function, while external variables are declared outside of any function.

1. AUTOMATIC VARIABLES:
Automatic variables are declared inside a function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is
exited; hence the name automatic variables are also referred to as local or internal variables.
A variable declared inside a function without storage class specification is, by default, an
automatic variable. We may also use the keyword auto to declare automatic variables
explicitly.
main( )
{
int num; auto int num;
- -
-} }
The value of automatic variable can not be changed accidentally by what happens in some
other function in the program. This assures that we may declare and use the same variable
name in different functions in the same program without causing any confusion to the
compiler.
void main( )
{
int m=1000;
function2( );
printf(“%d\n”,m);
}

function1( )
{
int m=10;
printf(“%d\n”,m);
}
Output
function2( ) 10
{
100
int m=100;
1000
function1( );

printf(“%d\n”,m);
41 | P a g e
}

A program with two sub programs function1( ) and function2( ) is shown. m is an automatic
variable and it is declared at the beginning of the each function. m is initialized to 10, 100,
1000 in function1, function2 and main( ) respectively.
When executed, main( ) calls function2, which in turn calls function1. When main is
active m=1000, but when f2 is called the main’s m is temporarily put on the shelf and the new
local m=100 becomes active. Similarly when function1 is called both the previous values of
m are put on the shelf and the latest value of m=10 becomes active. As soon as function1 is
finished, function2 takes over again. As soon it is done, main takes over the output clearly.
Shows that the value assigned to m is one function does not effect its value in the other
functions, and the local value of m is destroyed when its leaves a function.

2. EXTERNAL VARIABLES:
Variables that are both alive and active through out the entire program are known as external
variables. They are also known as global variables. Unlike local variables, global variables
can be accessed by any function in the program. External variables are declared out side a
function
Ex:
int a; int b;
main( );
{
-
-
}
Fun1()
{

}
Fun2()
{

}
The variables a and b are available for use in all the three functions. In case a local variable
and global variable have the same name, the local variable will have precedence over the
global one in the function where it is declared.
Once a variable has been declared as global, any function can use it and change its value.
Then subsequent functions can reference only that new value.
One other aspect of a global variable is that it is visible only from the point of declaration to
the end of the program. Consider a program segment as shown below.
void main()
{
y=5;
.
.}
int y;
fun1()
{
y=y+1; .
.
}
As far as main() is concerned, y is not defined. So, the compiler will issue an error message.
Unlike local variables global variables are initialized to zero by default.
In the above program segment, the main() can not access the variable y as it has been
declared after the main() function. Declaring the variable with the storage class extern can
42 | P a g e
solve this problem.
main( )
{
extern int y;
-
-
}
function1( )
{
extern int y;
-
-
}
int y;

Although the variable y has been defined after both the functions, the external declaration of
y inside the functions informs the compiler that y is an integer type defined some where else
in the program.

num=2; OUTPUT
printf(“num=%s\n”,num); num= 2
fun1(); num= 7
printf(“num=%s\n”,num); num=17
fun2();
printf(“num=%s\n”,num);

fun1()
{
num=num+5;
}
fun2()
{
} num=num+10;

Example 1) Global variable declaration before the functions


#include<stdio.h>
int n; /* Global Declaration */
main()
{
}
Example 2) Global variable declaration after the functions
#include<stdio.h>
main()
{
extern int num;
num=2;
OUTPUT
printf(“num=%s\n”,num); num= 2
fun1(); num= 7
printf(“num=%s\n”,num); num=17
fun2();
printf(“num=%s\n”,num);
}
fun1()
{
extern int num;
num=num+5;
}
fun2()
{
extern int num;
num=num+10;
}
int num; /* Global Declaration */

3. STATIC VARIABLES:
As the name suggests, the value of static variables persists until the end of the program. A
variable can be declared static using the key word static like
static int x; static
float y;
A static variable may be either an internal type or an external type, depending on the place of
declaration. Internal static variables are those which are declared inside a function. The scope of
internal static variables extends up to the end of the function, in which they are defined. Therefore,
internal static variables are similar to auto variables, except that they remains in existence (alive)
throughout the remainder of the program. Therefore internal static variables can be used to retain
values between function calls.
Example for static variable Example for Auto variable

void main( ) void main( )


{ {
int i; int i;
for(i=1; i<=3; i++) for(i=1; i<=3; i++)
fun( ); afun( );
} }
fun( ) afun( )
{ {
static int x=0; int x=0;
x=x+1; x=x+1;
printf(“x=%d\n”,x); printf(“x=%d\n”,x);
} }
out put out put
x=1 x=1
x=2 x=1
x=3 x=1

43 | P a g e
A static variable is initialized only once, when the program is compiled it is never initialized
again. During the first call to fun( ) function x is incremented to 1. Because x is static, this value
persists and therefore, the next call adds another 1 to x giving it a value of 2. The value of x
becomes 3 when the third call is made.

4. REGISTER VARIABLES:
We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of
keeping in the memory. Since a register access is much faster than a memory access, keeping the
frequently accessed variables in the register will lead to the faster execution.
register int count;
Most compilers allow only int or char variables to be placed in the register

3.3 PREPROCESSOR COMMANDS


As the name suggests the preprocessor commands are the instructions that are executed before the
source code passes through the compiler. The program that processes the preprocessor command lines
or directives is called a preprocessor.

Preprocessor directives are placed in the source program before the main() line. Preprocessor
directives begins with the symbol # and do not require a semicolon at the end.

Directive Function
#define defines a macro substitution
#undef undefines a macro
#include specifies the files to be included
#ifdef Returns true if macro is defined
#endif specifies end of #if
#if test a compile time condition
#else specifies alternatives when #if test fails

Examples #define COUNT 100


#define TRUE 1
#define FALSE 0
#define PI 3.1415
#define AREA 5*12.46
#define SIZE sizeof(int)*4
#define M 5
#define N M+1
#define SQUARE(x) ((x)*(x))

Example Program:

#include <stdio.h>

#define pi 3.147

#define square(x) x*x

void main()

float r,area;

printf(“\nenter radius of circle”);

44 | P a g e
scanf(“%f”,&r);

#ifdef pi

area =pi*square(r );

printf(“\the area of circle is %f”,area);

#else

printf(“\n pi is not defined”);

#endif;

45 | P a g e
UNIT IV
POINTERS
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before you can use it to
store any variable address. The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer.
Pointers can be used to pass information back and forth between a function and its reference
point. In particular, pointers provide a way to return multiple data items from a function via function
arguments.
Pointers are also closely associated with arrays and therefore provide an alternative way to
access individual array elements. The computer memory is a sequential collection of storage cells.
Each cell commonly known as a byte, has a number called address associated with it.
Typically the addresses are numbered consecutively starting from zero. The last address
depends on memory size.

int num=50;
This statement instructs the system to find a location for the integer variable ‘num’ and puts the value
50 in that location.

Let us assume that the system has chosen the address location 2000 for num.

printf(“num=%d address=%u\n”,num,&num);

Output:

num=50 address=2000

Declaring Pointer Variables

 Since addresses are numeric values, they can be stored in variables, just like any other kind of data.
 Pointer variables must specify what kind of data they point to, i.e. the type of data for which they
hold the address. This becomes very important when the pointer variables are used.
 When declaring variables, the asterisk, *, indicates that a particular variable is a pointer type as
opposed to a basic type.
 So for example, in the following declaration:

int i, j, *iptr, k, *numPtr, *next;

variables i, j,and k are of type ( int ), and variables iptr, numPtr, and next are of type ( pointer to int )

Assigning Pointer Variables

Pointers can be assigned values as the program runs, just like any other variable type. For example:

int i = 42, j = 100;


int *p1 = NULL, *p2 = NULL; // pointers are initially point nowhere.

46 | P a g e
P1 = &i; // Now p1 points to i.

p2 = p1; // Now both pointers point to i. Note no & operator


p1 = &j; // p1 changed to point to j.

p2 = NULL; // p2 back to pointing nowhere.

Accessing a variable using Pointer - The Indirection Operator

 As discussed above, the asterisk,*, in a variable declaration statement indicates that a


particular variable is a pointer type.
 In executable statements, however, the asterisk is the indirection operator, and has a totally
different meaning.
 In particular, the indirection operator refers to the data pointed to by the pointer, as opposed to
the pointer itself. (i.e. the * in an executable statement says to follow the pointer to its
destination.)

For example:

int i, , j;
int *iptr = &i, *jptr = &j; // These * indicates variables of type ( pointer to int )

i = 42; // changes i to 42
*iptr = 100; // changes i from 42 to 100
j = *iptr; // Now j is 100 also

/* Note carefully the distinction between the following two lines */


*jptr = *iptr; // Equivalent to j = i. jptr and iptr still point to different places
jptr = iptr; // Makes jptr point to the same location as iptr. Both now point to i

Another example:

#include <stdio.h>
int main ()
{
int var = 20; /* variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
clrscr();
printf("Address of var variable: %u\n", &var ); /* address stored in pointer variable */
printf("Address stored in ip variable: %u\n", ip ); /* access the address using the pointer */
printf("Value of *ip variable: %d\n", *ip ); /* access value through pointer */
return 0;
}

Output:
Address of var variable: 65492
Address stored in ip variable: 65492
Value of *ip variable: 20
Hint:
In the above program…
ip is points to address of variable.
*ip is known as ‘value at pointer’.

Pointer dereferencing

47 | P a g e
Once a pointer is declared, you can refer to the thing it points to, known as the target of the
pointer, by "dereferencing the pointer". To do this, use the unary * operator:

int * ptr; // ptr is now a pointer-to-int


// Notation:
// ptr refers to the pointer itself
// *ptr the dereferenced pointer -- refers now to the TARGET

Suppose that ptr is the above pointer. Suppose it stores the address 1234. Also suppose that the
integer stored at address 1234 has the value 99.

printf( "The pointer is: %u", ptr);// prints the pointer


printf "The target is: %d”, *ptr); // prints the target

// Output:
// The pointer is: 1234 // exact printout here may vary
// The target is: 99

Pointer Arithmetic

 There are a few very limit mathematical operations that may be performed on address data types,
i.e. pointer variables.
 Most commonly, integers may be added to or subtracted from addresses.
 Note that increment and decrement operations are really just special cases of addition and
subtraction.

In other words, if a pointer is incremented, it is actually increased sufficiently to point to the


next adjacent "thing" in memory, where "thing" corresponds to the type of data that the pointer is
declared as pointing to.

For example

int a[10], *p;


p=a;
p points to starting address of array a.
p++ points next element in array. p is increased by the size of int. In the same manner when p
is decreased it decreases by the size of int.

Combinations of * and ++

 *p++ accesses the thing pointed to by p and increments p


 (*p)++ accesses the thing pointed to by p and increments the thing pointed to by p
 *++p increments p first, and then accesses the thing pointed to by p
 ++*p increments the thing pointed to by p first, and then uses it in a larger expression.

Pointer to pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that contains the actual value
as shown below.

48 | P a g e
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a pointer to
a pointer of type int:

int **var;
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:

Example program:

#include <stdio.h>
void main ()
{
int var;
int *ptr;
int **pptr;

var = 3000;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
}
Output:

Value of var = 3000


Value available at *ptr = 3000
Value available at **pptr = 3000
Pointers and Arrays
(Pointers to Array Elements)

 A pointer may be made to point to an element of an array by use of the address operator(*):

int n[10], *iptr = NULL;


iptr = & nums[ 3 ]; // iptr now points to the fourth element
*iptr = 42;
Ex) Program to access elements of a single dimensional array using a pointer variable
/*-------------------------------------------------------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[5] = { 1,2,3,4,5 };
int i,*p;
clrscr();
printf("The array elements are (normal accessing)\n");
for(i=0;i<5;i++)

49 | P a g e
printf("%d is stored at %u\n",a[i],&a[i]);
p=a; /*..pointer initialisation*/
printf("The array elements are (pointer accessing)\n");
for(i=0;i<5;i++)
printf("%d is stored at %u\n",*(p+i),(p+i));
}
Output:
The array elements are (normal accessing) The array elements are (pointer accessing)
1 is stored at 404 1 is stored at 404
2 is stored at 406 2 is stored at 406
3 is stored at 408 3 is stored at 408
4 is stored at 410 4 is stored at 410
5 is stored at 412 5 is stored at 412

Ex) Program using pointers to sum of all elements stored in an array


/*-------------------------------------------------------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],sum=0,i;
int *p;
float avg;
p=a; /*pointer assigning to base address of array i.e. to a[0] */
printf("\n Enter 10 numbers: ");
for(i=0;i<10;i++)
{
scanf("%d",p);
sum=sum+(*p);
p++;
}
avg=sum/10;
printf("\nSum is: %d & Average is: %f ",sum,avg);
getch();
}
Output:
Enter 10 numbers: 15
10 16
11 14
12 18
13 17
14 Sum is: 140 & Average is: 14.000000

Pointers and Character Strings


Note: there is no ‘string type’ in ‘C language’.
Strings are treated like ‘character arrays’ and therefore they are declared and initialized as follows:

char str [5] = ”good” ;


The compiler automatically inserts the null character ‘\0’ at the end of the string.
C supports an alternative method to create string using pointer variables of type char. Example:

char *str = “good” ;


This creates a string for the literal and then stores its address in the pointer variable str.
The pointer str now points to the first character of the string “good” as:

50 | P a g e
g o o d \
0

We can also use the run-time assignment for giving values to a string pointer. Example

char * string1;
string1 = “good” ;
We can print the content of the string1 using either printf or puts function as follows:

printf(“%s”,string1);
puts(string1);
Note: although string1 is a pointer to the string, it is also the name of the string. Therefore, we do not
need to use indirection operator * here.

Ex) Program using pointers to determine the length of a character string.


/*------------------------------------------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
char *name;
char *cptr;
int length;
name="DELHI";
cptr=name;
clrscr();
printf("%s",name);
while(*cptr!='\0')
{
printf("\n%c is stored at %u\n",*cptr,cptr);
cptr++;
}
length=cptr-name;
printf("\nThe Length of string = %d\n",length);
getch();
}
D E L H I \0

Name(404) cptr(409)

Output:
DELHI str H is stored at 407
D is stored at 404 I is stored at 408
E is stored at 405 The Length of string = 5
L is stored at 406
Arrays of Pointers

One important use of pointers is in handling of a table of strings. Consider the following array of
strings:
char name [3][25];

51 | P a g e
This says that the name is a table containing three names, each with a maximum length of 25
characters (including null character). The total storage requirements for the name table are 75 bytes
(3x25).

We know that rarely the individual strings will be of equal lengths. Therefore, instead of
making each row a fixed number of characters, we can make it a pointer to a string of varying length.
For example,
char *name[3]={“India”,“New Zealand”,”Australia”};
declares name to be an array of three pointers to characters, each pointer pointing to a particular name
as:
name[0] ------- India
name[1] ------- New Zealand
name[2] ------- Australia
this declaration allocates only 28 bytes, (75-28=47 bytes saving)

\
I n d i a 0

N e w z e a l a n d \0

A u s t r a l i a \0
Example program :
#include <stdio.h>
void main ()
{
int i;
char *name[3]={"India","New Zealand","Australia"};
for(i=0;i<=2;i++)
printf("%s\n",name[i]);
}
Output:
India
New Zealand
Australia

To access jth character in the ith name, we may write as

*(name[i]+j)

We can have arrays of pointers since pointers are variables.


Example 2:

#include <stdio.h>

void main()

52 | P a g e
{

char *p[3],s[10],r[10],t[10];

strcpy(s,"abc");

strcpy(r,"def");

strcpy(t,"wer");

p[0]=s;

p[1]=r;

p[2]=t;

printf("\n%s\n%s\n%s",p[0],p[1],p[2]);

Output:

abc

def

wer

In above example p is array of char pointers. Each pointer element is pointing one string. i.e
p[0] points to s, p[1] points to r and p[2] points to t. It is when you use array of pointers to deals with
strings.

Multidimensional arrays and pointers

We should think of multidimensional arrays in a different way in C:

A 2D array is really a 1D array, each of whose elements is itself an array

So we use the declaration like this

a[m][n] where a is 2D array with m rows and n columns.

Array elements are stored row by row. C needs to know how many columns in order that it can
jump from row to row in memory. Here is an example.

53 | P a g e
In the above figure, array is a pointer-to-pointer-to-int: at the first level, it points to a block of
pointers, one for each row.

That first-level pointer is the first one we allocate; it has nrows elements, with each element
big enough to hold a pointer-to-int, or int *. If we successfully allocate it, we then fill in the pointers
(all nrows of them) with a pointer (also obtained from malloc) to ncolumns number of ints, the storage
for that row of the array. If this isn't quite making sense, a picture should make everything clear:

Example program:

#include <stdlib.h>

#include <stdio.h>

main()

int **array; /* like array[][] & pointer-to-pointer-to-int */

int nrows,ncolumns,i,j;

clrscr();

printf("\nenter no of rows & columns:");

scanf("%d%d",&nrows,&ncolumns);

array = malloc(nrows * sizeof(int *)); /* Dynamically memory allocating to array*/

printf("Enter elements\n");

for(i=0;i<nrows;i++)

for(j=0;j<ncolumns;j++)

54 | P a g e
scanf("\n%d",&(*(*(array+i)+j)));

printf("output\n");

for(i=0;i<nrows;i++)

{ for(j=0;j<ncolumns;j++)

printf("\n%d", *(*(array+i)+j)); /* like array[i][j] */

getch();

Output:

Enter no of rows & columns :2 output


2
Enter elements 1
1 2
2 3
3 4
4

Pointers and Functions

Pointers as Function Arguments

Previously we pass values (call by value) to the function. Now using pointers we can pass
addresses (call by address) to the functions.

Ex) Write a function using pointers to exchange the values stored in two locations in memory.

/*------------------------------------------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>

void exchange(int *,int *); /* prototype */


void main()
{
int x,y;
x=100;
y=200;
printf("before exchange : x=%d y=%d \n\n",x,y);
55 | P a g e
exchange(&x,&y); /* function call & we passing addresses here*/
printf("after exchange : x=%d y=%d \n\n",x,y);
getch();
}
void exchange(int *a,int *b) /* pointers as function arguments*/
{
int t;
t=*a;
*a=*b;
*b=t;
}

Output:

before exchange : x=100 y=200

after exchange : x=200 y=100

Function Returning Pointers

We have seen so far that a function can return a single value by its name or return multiple
values through pointer parameters. Since pointers are a data type in C, we can also force a function to
return a pointer to the calling function. Consider the following code:

#include<stdio.h>

#include<conio.h>

void *large(int *,int *); /* prototype */

void main()

int x,y;

int *p;

x=100;

y=20;

p=large(&x,&y); /*assigning return address(from function large() function) to pointer p */

printf("%d\n",*p);

getch();

void *large(int *a,int *b)

56 | P a g e
if(*a>*b)

return(a); /* returning address of a*/

else

return(b); /* returning address of b */

Output:

before exchange : x=100 y=200

after exchange : x=200 y=100

Pointers to Functions

A function, like a variable, has a type and an address location in memory. It is therefore,
possible to declare a pointer to a function, which can then be used as an argument in another function.
A pointer to a function is declared as follows:

type (*ptr) ();

This tells the compiler that ptr is a pointer to a function, which returns type value.

/*calling a function through ‘function pointer’ */

#include<stdio.h>

#include<conio.h>

int add(int,int); /* prototype */

int sub(int,int); /* prototype */

void main()

int (*fp)(); /*pointer fp to function */

int x;

fp=add; /* initially pointer points to add() function */

x=(*fp)(2,3); /* calling function add() through pointer */

printf("\n sum is %d\n\n",x);

printf("\n The sum is %d\n\n",x);


57 | P a g e
fp=sub; /* now pointer points to sub() function */

x=(*fp)(5,2); /* calling function sub() through pointer */

printf("The sub is %d",x);

getch();

int add(int a,int b)

int c=a+b;

return c;

int sub(int a,int b)

return a-b;

Output:

The sum is 5

The sub is 3

Pointers and Structures


We can access structure through pointers

Example:

/*pointers and structures */


#include <stdio.h>
#include<conio.h>
#include <string.h>
struct invent
{
char *name[20];
int number;
int price;
};
void main()
{

58 | P a g e
struct invent product[3],*ptr;
clrscr();
ptr=product;
printf("\n INPUT \n name number price \n\n");
for(ptr=product;ptr<product+3;ptr++)
scanf("%s %d %d",ptr->name,&ptr->number,&ptr->price);
printf("\n OUTPUT \n\n");
for(ptr=product;ptr<product+3;ptr++)
printf("%-10s %5d %10d\n",ptr->name,ptr->number,ptr->price);
getch();
}

Output:

INPUT
name number price OUTPUT

cooler 10 15000 cooler 10 15000


ac 5 30000 ac 5 30000
fan 15 20000 fan 15 20000

In the above example structure variable product is accessed through ptr (pointer variable to structure)

Constant Pointers

Let’s first understand what a constant pointer is. A constant pointer is a pointer that cannot
change the address its holding. In other words, we can say that once a constant pointer points to a
variable then it cannot point to any other variable.

A constant pointer is declared as follows:

Syntax:

Pointer_type * const pointer_name;

An example declaration would look like :

int * const ptr;

Lets take a small code to illustrate these type of pointers :

#include<stdio.h>

int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);

return 0;
}

In the above example :

59 | P a g e
 We declared two variables var1 and var2
 A constant pointer ‘ptr’ was declared and made to point var1
 Next, ptr is made to point var2.
 Finally, we try to print the value ptr is pointing to.

So, in a nutshell, we assigned an address to a constant pointer and then tried to change the address by
assigning the address of some other variable to the same constant pointer.

Lets now compile the program :

$ gcc -Wall constptr.c -o constptr


constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only variable ‘ptr’

So we see that while compiling the compiler complains about ‘ptr’ being a read only variable. This
means that we cannot change the value ptr holds. Hence we conclude that a constant pointer which
points to a variable cannot be made to point to any other variable.

Pointer to Constant

As evident from the name, a pointer through which one cannot change the value of variable it
points is known as a pointer to constant. These type of pointers can change the address they point to
but cannot change the value kept at those address.

A pointer to constant is defined as :

Syntax:

const pointer_type* pointer_name;

An example of definition could be:

const int* ptr;

Lets take a small code to illustrate a pointer to a constant:

#include<stdio.h>

int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}

In the code above :

 We defined a variable var1 with value 0


 we defined a pointer to a constant which points to variable var1
 Now, through this pointer we tried to change the value of var1
 Used printf to print the new value.

Now, when the above program is compiled :

$ gcc -Wall constptr.c -o constptr


60 | P a g e
constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location ‘*ptr’

So we see that the compiler complains about ‘*ptr’ being read-only. This means that we cannot change
the value using pointer ‘ptr’ since it is defined a pointer to a constant.

Constant Pointer to a Constant

If you have understood the above two types then this one is very easy to understand as its a
mixture of the above two types of pointers. A constant pointer to constant is a pointer that can neither
change the address its pointing to and nor it can change the value kept at that address.

A constant pointer to constant is defined as :

const <type of pointer>* const <name of pointer>

for example :

const int* const ptr;

Lets look at a piece of code to understand this :

#include<stdio.h>

int main(void)
{
int var1 = 0,var2 = 0;
const int* const ptr = &var1;
*ptr = 1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}

In the code above :

 We declared two variables var1 and var2.


 We declared a constant pointer to a constant and made it to point to var1
 Now in the next two lines we tried to change the address and value pointed by the pointer.

When the code was compiled :

$ gcc -Wall constptr.c -o constptr


constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location ‘*ptr’
constptr.c:8: error: assignment of read-only variable ‘ptr’

So we see that the compiler complained about both the value and address being changed. Hence we
conclude that a constant pointer to a constant cannot change the address and value pointed by it.

No Pointer to Constant Constant Pointers


*ptr = 20 Statement is Invalid in Pointer to *ptr = 20 is Absolutely Valid in Constant Pointers
1
Constant i.e Assigning Value is Illegal i.e Assigning Value is Perfectly legal
ptr ++ Statement is Valid in Pointer to
2 ptr ++ Statement is invalid in Constant Pointers
Constant
3 Pointer Can be Incremented and Decremented Pointer Cannot be Incremented and Decremented
61 | P a g e
4 Pointer is Pointing to Constant Data Object Constant Pointer is Pointing to Data Objects
5 Declaration : const int *ptr ; Declaration : int * const ptr ;

Allocating memory
There are two ways that memory gets allocated for data storage:

1. Compile Time (or static) Allocation


o Memory for named variables is allocated by the compiler
o Exact size and type of storage must be known at compile time
o For standard array declarations, this is why the size has to be constant
2. Dynamic Memory Allocation
o Memory allocated "on the fly" during run time
o dynamically allocated space usually placed in a program segment known as the heap or
the free store
o Exact amount of space or number of items does not have to be known by the compiler
in advance.
o For dynamic memory allocation, pointers are crucial

Function Use of Function


malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() De-llocate the previously allocated space
realloc() Change the size of previously allocated space

Dynamic memory management functions:

Dynamic memory allocation is the practice of assigning memory locations to variables during
execution of the program by explicit request of the programmer. Dynamic allocation is a unique
feature to C (amongst high level languages). It enables us to create data types and structures of any
size and length to suit our programs need within the program.
For example, for arrays, dynamic memory allocation eliminates the need to determine the size
of the array at declaration time. Dynamically allocated memory is freed when we are not using it.
The functions malloc (), realloc (), calloc () and free (), the Library functions stdlib.h, malloc.h or are
responsible for this task.
The C programming language provides several functions for memory allocation and
management. These functions can be found in the<stdlib.h> header file.
S.N. Function and Description
void *calloc(int num, int size);
1
This function allocates an array of num elements each of which size in bytes will be size.
void free(void *address);
2
This function release a block of memory block specified by address.
void *malloc(int num);
3
This function allocates an array of num bytes and leave them initialized.
void *realloc(void *address, int newsize);
4
This function re-allocates memory extending it upto newsize.

62 | P a g e
malloc()

The malloc() function dynamically allocates memory when required. This function allocates
‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error
Format is as follows.
void * malloc (size_t size);

Specifies in bytes the size of the area you want to reserve the argument. It returns the address
as the return value of the dynamically allocated area. In addition, returns NULL if it fails to secure the
area. The failure to ensure that the situation is usually that is out of memory.
The return type is of type void *, also receive the address of any type. The fact is used as
follows.
double * p = (double *) malloc (sizeof (double));
Example:

int * p;
p = (int *) malloc (sizeof (int));
* p = 5;

Program

#include <stdio.h> #include <conio.h>


#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); /*memory allocated using malloc*/
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum=sum+*(ptr+i); /*sum+=*(ptr+i);*/
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
calloc()

The calloc function is used to allocate storage to a variable while the program is running. This
library function is invoked by writing calloc(num,size).This function takes two arguments that specify

63 | P a g e
the number of elements to be reserved, and the size of each element in bytes and it allocates memory
block equivalent to num * size . The function returns a pointer to the beginning of the allocated
storage area in memory. The important difference between malloc and calloc function is that calloc
initializes all bytes in the allocation block to zero and the allocated memory may/may not be
contiguous.
calloc function is used to reserve space for dynamic arrays. Has the following form.

void * calloc (size_t n, size_t size);

Number of elements in the first argument specifies the size in bytes of one element to the second
argument. A successful partitioning, that address is returned, NULL is returned on failure.

For example, an int array of 10 elements can be allocated as follows.


int * array = (int *) calloc (10, sizeof (int));
Note that this function can also malloc, written as follows.
int * array = (int *) malloc (sizeof (int) * 10);

Program ……refer in notes

realloc()

With the function realloc, you can change the size of the allocated area once. Has the following
form.
void * realloc (void * ptr, size_t size);

The first argument specifies the address of an area that is currently allocated to the size in bytes
of the modified second argument. Change the size, the return value is returned in re-allocated address
space. Otherwise it returns NULL.
Size may be smaller but larger than the original. If you have small, reduced what was written
in part will be inaccessible. If you increase the portion of the region will remain an indefinite increase.
The address of the source address changed, but the same could possibly be different, even if the
different areas of the old style, because it is automatically released in the function realloc, for the older
areas it is not necessary to call the free function.
However, if the function fails and returns NULL, realloc, the older area is to remain still
valid. Therefore, the first pointer argument of the function realloc, both can be NULL pointer return
value is not returned.

Example program:

int main (void)


{
int * p1, * p2;
p1 = (int *) calloc (5, sizeof (int)); /* number of elements in an array of type 5 int */
p2 = (int *) realloc (p1, sizeof (int)); * / re-acquire the space of one type / * int
if (p2 == NULL) * / check if successful * /

64 | P a g e
{
free (p1); / *, the region remains valid since the original to free myself * /
return 0;
}
p1 = NULL;
free (p2);
return 0;
}
The realloc function is a very feature-rich functions.
free()

Free function is used to release the reserved area .It has also been declared in stdlib.h, which
has the following form.
void free (void * ptr);
The argument specifies the address of a dynamically allocated area. You can then free up the space.
Example:
int * p;
p = (int *) malloc (sizeof (int));
* p = 150;
printf ("% d \ n", * p);
free (p)

Command line arguments:


It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important for
your program especially when you want to control your program from outside instead of hard coding
those values inside the code.
The command line arguments are handled using main() function arguments where argc refers
to the number of arguments passed, and argv[] is a pointer array which points to each argument passed
to the program. Argv is called as argument vector and argc is called as argument counter.
Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly:

#include <stdio.h>

int main( int argc, char *argv[] )


{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
65 | P a g e
When the above code is compiled and executed with a single argument, it produces the following
result.

Output:
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.

$./a.out testing1 testing2


Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.

$./a.out
One argument expected

argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line
argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one,
otherwise and if you pass one argument then argc is set at 2.

UNIT V
Enum:

66 | P a g e
Enumeration data type in C:

 Enumeration data type consists of named integer constants as a list.


 It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in
the list.

Enum syntax in C:

enum identifier l{ enumerator-list };

Enum example in C:

enum month { Jan, Feb, Mar }; or


/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */

Example:

#include <stdio.h>
int main()
{
enum MONTH { Jan , Feb, Mar }; /* initializing data type MONTH *I/
enum MONTH mm= Mar;
if(mm == 0)
printf(“Month is January”);
else if(mm == 1)
printf(“Month is February”);
else if(mm == 2)
printf(“Month is March”);
else
printf(“Other month”);
}

Output:

Month is March

Structures
Arrays can be used to represent a group of data items that belong to the same type, such as int
or float. However if we want to represent a collection of data items of different types using a single
67 | P a g e
name, then we cannot use array. C supports a constructed data type known as structure, which is a
method of packing data of different data types.
A structure is a convenient tool for handling a group of logically related data items.
Consider a student database consisting of student rno, name, author, and marks we can define a
structure to hold this information as follows.

struct student
{
int rno;
char name[20];
int marks;
};
The keyword struct declares a structure to hold the details of three fields, namely rno, name
and marks. These fields are called structure elements or members. Each member may belong to a
different type of data.
Note that the above declaration has not declared any variables. It simply describes a format.
The general format of a structure:

struct structure_name
{
data_type member1;
data_type member2;
-
-
-
};
We can declare structure variables using the structure name anywhere in the program for example the
statement

struct student s1, s2;


declares s1 and s2 as variables of type “struct student”. Each one of these variables has three
members. Remember that the members of a structure themselves are not variables. They do not
occupy any memory until they are associated with the structure.

Assigning values to members:


We can assign values to the members of a structure in a number of ways. As mentioned earlier
the members themselves are not variables. They should be linked to the structure variables in order to
make them meaningful members.
The link between a number and a variable is established using the member operator “.”, which
is also known as ‘dot operator’ or ‘period operator’.

Ex .s1.marks is the variable representing the marks of s1 and can be treated like any other ordinary
variables.

Assigning values to members using assignment operator.


s1.rno = 1;
s1.marks = 100;
Assigning values to structure members using scanf() statement:
scanf(“%s”,s1.name);
scanf(“%d”,&s1.rno);
scanf(“%d”,&s1.marks);

Structure Initialization:

68 | P a g e
Like any other data type, a structure variable can be initialized. (However a structure must be
declared as static if it is to be initialized inside a function).

struct student
{
int rno;
int marks
};
struct student st1={1,50};

Accessing structure members.


One way of accessing structure members using dot(.) operator.

/*sample structure program*/


#include<stdio.h>
#include<conio.h>
struct personal
{
char name[20];
int day;
char month[20];
int year;
float salary;
};
void main()
{
struct personal person;
clrscr();
printf("input values:\n");
scanf("%s%d%s%d%f",person.name,&person.day,person.month,&person.year,&person.salary);
printf("%s\n%d\n%s\n%d\n%f\n",person.name,person.day,person.month,person.year,person.salary);
getch();
}
Output:
Input values:
sastry sastry
12 12
march march
1990 1990
50000 50000

Structures and functions.


We know that the main philosophy of C language is the use of functions. Therefore it is natural
that C supports the passing of structure values as arguments to functions.
There are 3 methods by which the values of a structure can be transferred from one function to
another function.
The first method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are then treated independently like ordinary variables. This is the most
elementary method and becomes unmanageable and inefficient when the structure size is large.
The second method involves passing of a copy of the entire structure to the called function.
Since the function is working on a copy of the structure, any changes to structure members within the
function are not reflected in the original structure. It is therefore, necessary for the function to return
the entire structure back to the calling function.
The third approach employs a concept called pointers to pass the structure as an argument. In
this case, the address location of the structure is passed to the called function. The function can access

69 | P a g e
indirectly the entire structure and work on it. This is similar to the way arrays are passed to functions.
This method is more efficient as compared to the second.

Example:

struct complex
{
int real;
int img;
};
void add(struct complex,struct complex);
int main()
{
struct complex c1,c2;
printf(“\nenter complex no 1: ”);
scanf(“%d”,&c1.real);
scanf(“%d”,&c1.img);
printf(“\nenter complex no 2: ”);
scanf(“%d”,&c2.real);
scanf(“%d”,&c2.img);
add(c1,c2);
return 0;
}
void add(struct complex a,struct complex b)
{
struct complex c;
c.real=a.real+b.real;
c.img=a.img+b.img;
printf(“\the sum of two complex nos is “);
printf(“%d + %d i”,c.real,c.img);
}

Output:

enter complex no 1: 12 10
enter complex no 2: 13 14
the sum of two complex nos is 25 + 24 i

Nested structures (structures with in structures)


We can define another structure as member of Structure. Structures with in structures is
considered as nesting of structures. The inner structure is defined before using it. For example

Example:
/*structures within structures*/
#include<stdio.h>
#include<conio.h>
void main()
{
struct salary
{
int no;
char name;
70 | P a g e
char department;
struct
{
int dearness;
int house_rent;
int city;
}allowance;
}employee;

struct salary emp1;

emp1.no=1562;
strcpy(emp1.name,"sastry");
strcpy(emp1.department,"cse");
emp1.allowance.dearness=5000;
emp1.allowance.house_rent=5000;
emp1.allowance.city=3000;
clrscr();
printf("\n%s\n%s\n%d\n%d\n
%d",emp1.name,emp1.department,emp1.allowance.dearness,emp1.allowance.house_rent,emp1.all
owance.city);
getch();
}
Output:
sastry 5000
cse 3000Null pointer assignment
5000

Another Example:
struct student
{
int rno;
char name[10];
char course[10];
int jday;
int jmonth;
int jyear;
} s1;
This structure defines rno,name, course,and date of joining .
But we can define date of joing under a sub-structure as shown below.

struct date
{
int day;
int month
int year;
};
So now the strudent structure is like the below.
struct student
{
int rno;
char name[10];
char course[10];
struct date jod;
} s1;

71 | P a g e
The student structure contains a member named jod which itself is a structure with three members.
The members contained in the inner structure namely day, month and year can be referred as

s1.rno
s1.name
s1.course
s1.jod.day
s1.jod.month
s1.jod.year

Structure and pointers


We can pass a structure to a function as a pointer to a function. We use Arrow operator to
access members of structure using a pointer.
struct student *p,s1;

where p is pointer to structure student.

p=&s1;

We can access members of student using pointer as p->rno, p->name etc.

(*p).rno is same as p->rno

Example:

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float marks;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->marks);

return 0;
}
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000

72 | P a g e
Array of structures
We use structures to describe the format of a number of related variables. For example, in
analyzing the marks obtained by a class of students, we may use a template to describe student name,
marks obtained in various subjects and then declare all the students as structure variables. In such
cases, we may declare an array of structures, each element of the array representing a structure
variable.

struct student s[100];

Defines an array called s that consists of 100 elements. Each element is defined to be of the
type struct student. The individual members of the structure are:

s[0].stno, s[0].stname, s[0].m1, s[0].m2, s[0].m3


s[1].stno, s[1].stname, s[1].m1, s[1].m2, s[1].m3
.
.
s[99].stno, s[99].stname, s[99].m1, s[99].m2, s[99].m3

Example program:

/*arrays of structures*/
#include<stdio.h>
#include<conio.h>
struct marks
{
int sub1;
int sub2;
int total;
};
void main()
{
int i;
struct marks std[2]={{51,72,0},{52,90,0}}; /* arrays of structures */
clrscr();
for(i=0;i<2;i++)
std[i].total=std[i].sub1+std[i].sub2;
printf("student total\n");
for(i=0;i<2;i++)
printf("student[%d] %d\n",i+1,std[i].total);
getch();
}
Output:
student total
student[1] 123
student[2] 142

73 | P a g e
Array within structures
/*arrays within structures*/
#include<stdio.h>
#include<conio.h>
void main()
{
struct marks
{
int sub[6]; /* array within structure */
int total;
};
struct marks std[2]={51,72,52,90,75,85,0,52,62,72,82,92,83,0};
int i,j;
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<6;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
}
printf("student\t\t\t total\n\n");
for(i=0;i<2;i++)
printf("student[%d]total marks: \t%d\n",i+1,std[i].total);
getch();
}
Output:
student total
student[1]total marks: 425
student[2]total marks: 443

5.8 Self referential structures


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

Example with self-referential structure:

/*self referential structures */


#include <stdio.h> #include <string.h>
struct person
{
char name1[20];
int age;

74 | P a g e
char name2[10];
struct person *tPrev; /* self-referential structure */
struct person *tNext; /* self-referential structure */
};
void main()
{
long x;
struct person *person1,*person2,p1,p2;
person1 = &p1;
person2 = &p2;
person1->tNext = person2;
person1->tPrev = NULL;
person2->tPrev = person1;
person2->tNext = NULL;
person1->age = 40;
person2->age = 50;
clrscr();
printf("person1 & person2 ages: %d\t%d\n",(*person1).age,(*person2).age);/* using *(value at) */
printf("person1 & person2 ages: %d\t%d\n",person1->age,person2->age);/* using arrow */
getch();
}
NULL 40
50 NULL
Output:
person1 & person2 ages: 40 50
person1 & person2 ages: 40 50

Typedef:
The C programming language provides a keyword called typedef, which you can use to give a
type a new name. You can use typedef to give a name to user defined data type as well. For example
you can use typedef with structure to define a new data type and then use that data type to define
structure variables directly as follows:

struct date
{
int day;
int mm;
int yy;
};
typedef struct date d;

Example program:

/*typedef example */
#include <stdio.h>
void main()
{
struct date
{
int day;
int mm;

75 | P a g e
int yy;
};
typedef struct date d;
struct student
{
int rno;
char name[20];
d jod; /* usage of typedef */
}s;
printf("\nEnter roll no: ");
scanf("%d",&s.rno);
printf("\n Enter name: ");
scanf("%s",s.name);
printf("\n Enter date of joining dd mm yy: ");
scanf("%d%d%d", &s.jod.day,&s.jod.mm,&s.jod.yy);
printf("\nno is %d", s.rno);
printf("\nname is %s",s.name);
printf("\njoining date %d-%d-%d",s.jod.day,s.jod.mm,s.jod.yy);
getch();
}
Output:
Enter Roll no: 100 no is 100
Enter name: sastry name is sastry
Enter date of joining dd mm yy: 01 01 08 joining date 1-1-8

Bit Fields:

We have been using integer field of size 16 bits to store data. There are occasions where data
items require much less than 16 bits space. In such cases, we waste memory space.

A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A word can
therefore be divided into a number of bit fields. The name and size of bit fields are defined using a
structure. The general form of bit field is:

Struct tag-name
{
Data-type name1: bit-length;
Data-type name2: bit-length;
……
……
Data-type nameN: bit-length;
}
The data-type is either int or unsigned int or signed int and the bit-length is the number of bits used
for the specified name.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

76 | P a g e
nameN ………. name 2 name 1
Example:
#include<stdio.h>
#include<conio.h>
#define MALE 0;
#define FEMALE 1;
#define single 0;
#define married 1;
#define divorced 2;
#define widwored 3;

void main()
{
struct employee
{
unsigned gender:1;
unsigned mar_stat:6;
unsigned hobby:3;
unsigned scheme:4;
};
struct employee e;
e.gender=1;
e.mar_stat=3;
e.hobby=5;
e.scheme=9;
printf("\n Gender=%d",e.gender);
printf("\n marital status=%d",e.mar_stat);
printf("\n Bytes occupied by e=%d ",sizeof(e));
}

Output:

Gender=1
marital status=3
Bytes occupied by e=2

77 | P a g e
UNION

A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location for
multi-purpose.

union [union tag]


{
member definition;
...
member definition;
}

Ex:
union student
{
int rno;
float marks;
char name[20];
} s;
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in above example student type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by character string. To access any member of a
union, we use the member access operator (.)
The differences between structure and union are
Structure Union

1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.

2. When a variable is associated with a 2. When a variable is associated with a union,


structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So,
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with member.
unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.

4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.

6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.

7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.

78 | P a g e
UNIT VI:
FILE:

A file is a collection of bytes stored on a secondary storage device. The collection of bytes may
be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical image.
When accessing files through C, the first necessity is to have a way to access the files. For C
File I/O you need to use a FILE pointer, which will let the program keep track of the file being
accessed. For Example:
FILE *fp;
Text files: A text file can be a stream of characters that a computer can process sequentially.

FILE Functions
Reading from or writing to a file in C requires 3 basic steps:

1. Open the file.


2. Do all the reading or writing.
3. Close the file.

Defining and Opening a file:

If we want to store data in a file in the secondary memory, we must specify certain things about the
file, to the operating system. They include:

1. Filename
2. Data structure
3. Purpose

Filename is a string of characters that make up a valid filename for the operating system. It
may contain two parts, a primary name and an optional period with the extension. Examples:

Input.data
Store
Prog.c
Student.c
Text.out

Data structure of a file is defined as FILE in the library of standard I/O function definitions.
So all files should be declared as type FILE before they are used.

Following is general format for declaring and opening a file:

FILE *fp;

fp=open(“filename”,”mode”);

The first statement declares the variable fp as a “pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This
pointer which contains all the information about the file is subsequently used as a communication link
between the system and the program.

 filename is a string that holds the name of the file on disk


 mode is a string representing how you want to open the file.

79 | P a g e
Modes are

w - open for writing (file need not exist)


r - open the file for reading only.
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Here's a simple example of using fopen:
FILE *fp;
fp=fopen("test.txt", "r");
This code will open test.txt for reading in text mode. To open a file in a binary mode you must
add a b to the end of the mode string; for example, "rb" (for the reading and writing modes, you can
add the b either after the plus sign - "r+b" - or before - "rb+")

Important file handling functions that are available in the C library.

Function name Operation


fopen() Creates new file for use & Opens an existing file for use.
fclose() Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current passion in the file(in terms of bytes from the start)
rewind() Sets the position to the beginning of the file.
fgetc()
fputc()
getchar()
getch()

Reading from or writing to a file using Formatted I/O,

Once a file has been successfully opened, you can read from it using fscanf() or write to it
using fprintf(). These functions work just like scanf() and printf(), except they require an extra first
parameter, a FILE * for the file to be read/written.

fprintf(fp, "This is testing...\n");

The function fscanf(), like scanf(), normally returns the number of values it was able to read in.
fscanf(fp,"%s",&sent);

To test for end of file is with the library function feof(). It just takes a file pointer and returns a
true/false value based on whether we are at the end of the file.

To read the data from the file until end of file

while (!feof(fp))
{
fscanf(fp, "%s”, username)
printf(“\n %s”,username);
80 | P a g e
}

Note that, like testing != EOF, it might cause an infinite loop if the format of the input file was not as
expected.

Closing a file:

A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from from the buffers and all links to
the file are broken.

fclose(file_pointer);

Example: (file1.c)
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen(“test.txt", "w"); /* file(text.txt) opening in write mode*/
fprintf(fp, "This is testing...\n");
fclose(fp;);
}

This will create a file test.txt in and will write This is testing in that file.
Output at file(test.txt):
Hello, This is testing...

Example:
Program to create a data file containing student records*/

#include<stdio.h>
main()
{
FILE *fp;
int stno;
char stname[10];
int m1,m2,m3,n,i;
fp=fopen("stu.dat","w");
printf("enter no of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nstno: ");
scanf("%d",&stno);
printf("stname: ");
scanf("%s",stname);
printf("m1 m2 m3: ");
scanf("%d%d%d",&m1,&m2,&m3);
fprintf(fp,"%d %s %d %d %d\n",stno,stname,m1,m2,m3);
}
fclose(fp);
getch();
}
Output: m1 m2 m3: 90 80 95
enter no of students: 2 101 xyz 90 80 95
stno: 101 stno: 102
stname: xyz stname: pqr
81 | P a g e
m1 m2 m3: 88 87 89 102 pqr 88 87 89

Input / Output operations on Files

The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.

The routine getc(fp) is similar to getchar()


and putc(c,fp) is similar to putchar(c).

Thus the statement

c = getc(fp);

reads the next character from the file referenced by fp and the statement

putc(c,fp);

writes the character c into file referenced by fp.

/* file1.c: Display contents of a file on screen */

Example program:
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
fp = fopen( "file1.c", "r" );
c = getc( fp ) ;
while ( c != EOF )
{
putchar( c );
c = getc ( fp );
}
fclose( fp );
}
Output: (from file1.c)
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp,"Hello, This is testing...\n");
fclose(fp);
}
Another Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char c;
82 | P a g e
clrscr();
printf("input:\n");
f1 = fopen("file3","w"); /* open file input*/
while((c=getchar())!=EOF) /* get character from keyboard*/
putc(c,f1); /* write a character to file3*/
fclose(f1); /* close the file*/
f1=fopen("file3","r"); /* re open the file*/
printf("output:\n");
while((c=getc(f1))!=EOF) /* display character on screen*/
printf("%c",c);
fclose(f1);
getch();
}
Output:
input:
hai hello, this is nec....Ece.b students designed me..^Z
output:
hai hello, this is nec....Ece.b students designed me..

The getw and putw functions

The getw and putw are integer-oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These functions would be useful when we deal
with only integer data. The general form of getw and putw are:

putw(integer, fp);
getw(fp);

Example program:
/*usage of getw, putw functions....*/
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA file:\n\n");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
scanf("%d",&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);

f1=fopen("DATA","r");
f2=fopen("EVEN","w");
f3=fopen("ODD","w");
while((number=getw(f1))!=EOF)

83 | P a g e
{
if(number%2==0)
{
putw(number,f2);
}
else
putw(number,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);

f2=fopen("EVEN","r");
f3=fopen("ODD","r");

printf("\n contents of ODD file\n");


while((number=getw(f3))!=EOF)
printf("%4d",number);
printf("\n contents of EVEN file\n");
while((number=getw(f2))!=EOF)
printf("%4d",number);
fclose(f2);
fclose(f3);
getch();
}
Output:
Contents of DATA file:
1 2 3 4 5 6 7 8 9 10 11 -1

contents of ODD file


1 3 5 7 9 11
contents of EVEN file
2 4 6 8 10

84 | P a g e
85 | P a g e

The fprintf and fscanf Functions

The functions fprintf and fscanf perform I/O operations that are identical to the
familiar printf and fscanf functions, except of course that they work on files. The first
argument of these functions is a file pointer which specifies the file to be used. The general
form of fprintf is

fprintf(fp, “control strings”,list);

where fp is file pointer associated with a file that has been opened for writing.
The control strings contains output specifications for the items in the list. (%d,%f,%s,%u,%e,
etc)
The list may include variables, constants and strings.

example is fprintf(f1,”%s %d %f”, name, age, percentage);


here f1 is file pointer.
The general form of fprintf is

fscanf(fp, “control strings”,list);

example is fprintf(f1,”%s %d %f”, name, &age, &percentage);

Example program:
/*usage of fprintf,fscanf functions....*/
#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[10],filename[10];
printf("input file name:\n");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("Input inventary data\n");
printf("itemname number price quantity \n");
for(i=1;i<=3;i++)
{
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %f %d",item,number,price,quantity);
}
fclose(fp);

85 | P a g e
86 | P a g e

fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("itemname number price quantity value\n");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;
fprintf(stdout,"%-8s %7d %8.2f %8d
%11.2f\n",item,number,price,quantity,value);
}
fclose(fp);
getch();
}
Output:
Input file name:
sastry
Input inventary data
itemname number price quantity
soap 100 36 20
dettol 101 76 15
pen 102 25 50

itemname number price quantity value


soap 100 36.00 20 720.00
dettol 101 76.00 15 1140.00
pen 102 25.00 50 1250.00

Another example

/*usage of fprintf,fscanf functions....*/


#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
char name[20],filename[20];
clrscr();
printf("enter file name:");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("enter ur name: \n");
fscanf(stdin,"%s ",name); /* reading data from keyboard(stdin) */
fprintf(fp,"hai %s",name); /* printing data into file */
printf("hai %s",name); /* printing data into console(monitor)*/
fclose(fp);
86 | P a g e
87 | P a g e

getch();
}
Output:
enter file name: sastry.c
enter ur name:
ezrasastry ^Z
hai ezrasastry
hint: u can observe output in sastry.c file also

Error handling during I/O operations

Refer in nodes..
Refer all programs

fputs, fgets functions

Refer in notes…
Example profram:
#include <stdio.h>
int main ()
{
FILE *fp; char str[60];
clrscr();
fp = fopen("file.txt", "w");
fputs("This is c programming.", fp);
fclose(fp);

fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if(fgets (str,60,fp)!=NULL )
{
/* writing content to stdout */
printf("%s",str); /* we can write puts(str);*/
}
fclose(fp);

return(0);
}
Output:
This is c programming.

GETS, PUTS functions

Refer in notes…

87 | P a g e
88 | P a g e

Example program

#include<stdio.h>
#include<conio.h>
void main()
{
char n[10];
clrscr();
printf("enter some text: ");
gets(n); /this is used instead of scanf() function*/
printf("\n");
puts(n); /*this is used instead of printf() function*/

getch();
}
Output:
enter some text: hai this we are from nec, ece.b
hai this we are from nec, ece.b

Random access to files

Refer in nodes..
Refer all programs.

Binary files and Random Access files

You can jump instantly to any structure in the file in random access files.You can
change the contents of a structure anywhere in the file at any time.

Once one opens a file one can read, write, or seek any arbitrary structure in the file. C
maintains a "file pointer" to enable these functions. When the file is opened, the pointer
points to record 0 (the first record in the file). Any read operation reads the currently pointed-
to structure and moves the pointer to the next record or structure. A write is done at the
currently pointed-to structure and moves the pointer down one structure. Seek moves the
pointer to the specified record.
There are three new functions in the example code , i.e., fread, fwrite, fseek,
ftell,rewind
The fread function takes four arguments:
* A memory address
* The number of bytes to read per block
* The number of blocks to read
* The file variable

Syntax is

fread(&struct,sizeof(struct),no.of records,file pointer );

The fwrite function works the same way, but moves the block of bytes from memory to the
file.

fwrite(&structure,sizeof(struct),no of records ,filepointer)


88 | P a g e
89 | P a g e

The fseek function moves the file pointer to an arbitrary byte in the file. You can use three
options when seeking:
* SEEK_SET - moves the file pointer down from the beginning of the file, i.e. from byte
0.
* SEEK_CUR - moves the file pointer down from its current position.
* SEEK_END - moves the file pointer up from the end of file. Note you must use
negative offsets.
ftell() takes a file pointer and returns a number of type long, that corresponds to the current
position. This function is useful in saving the current position of a file.
n=ftell(fp);
n would give the relative offset of the current position. This means that ‘n’ bytes have already
been read.

rewind() takes file pointer and resets the position to the start of the file.
rewind(fp);
n=ftell(fp);
This would assign 0 to n because the file position has been set to the statement of the file by
rewind.

Example:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "this is sample file";
char buffer[20];
/* Open file for both reading and writing */
fp = fopen("file.txt", "wb+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, SEEK_SET, 0);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
return(0);
}
Output: this is sample file.

89 | P a g e

Vous aimerez peut-être aussi