Sei sulla pagina 1di 319

Computer Programming & Data Structures

INTRODUCTION TO COMPUTERS

UNIT - I

Introduction to Computers - Computer Systems, Computing


Environments, Computer Languages, Creating and running
programmes, Software Development Method, Algorithms, Pseudo
code, flow charts, applying the software development method.

INTRODUCTION

A computer is a device capable of performing computations and


making logical decisions at speeds of millions and even billions of
times faster than human beings can. For example, many of today’s
personal computers can perform hundreds of millions of arithmetic
and logical operations per second. Today’s fastest supercomputers
can perform hundreds of billions of additions per second.

Computers process data under the control of sets of


instructions called computer programs. These programs guide the
computer through orderly sets of actions specified by people called
computer programmers.

Block Diagram of Computer:

A computer can process data, pictures, sound and graphics. They


can solve highly complicated problems quickly and accurately.
1
Computer Programming & Data Structures

Input Unit:

Computers need to receive data and instruction in order to solve


any problem. Therefore we need to input the data and instructions
into the computers. The input unit consists of one or more input
devices. Keyboard is the one of the most commonly used input
device. Other commonly used input devices are the mouse, floppy
disk drive, magnetic tape, etc. All the input devices perform the
following functions.
 Accept the data and instructions from the outside world.
 Convert it to a form that the computer can understand.
 Supply the converted data to the computer system for further
processing.
Storage Unit:

The storage unit of the computer holds data and instructions that
are entered through the input unit, before they are processed. It
preserves the intermediate and final results before these are sent to
the output devices. It also saves the data for the later use. The
various storage devices of a computer system are divided into two
categories.

1. Primary Storage: Stores and provides very fast. This memory is


generally used to hold the program being currently executed in the
computer, the data being received from the input unit, the
intermediate and final results of the program. The primary memory
is temporary in nature. The data is lost, when the computer is
switched off. In order to store the data permanently, the data has
to be transferred to the secondary memory.

The cost of the primary storage is more compared to the secondary


storage. Therefore most computers have limited primary storage
capacity.

2. Secondary Storage: Secondary storage is used like an archive.


It stores several programs, documents, data bases etc. The
programs that you run on the computer are first transferred to the
primary memory before it is actually run. Whenever the results are
saved, again they get stored in the secondary memory. The
secondary memory is slower and cheaper than the primary
memory. Some of the commonly used secondary memory devices
are Hard disk, CD, etc.,

2
Computer Programming & Data Structures

Memory Size:

All digital computers use the binary system, i.e. 0’s and 1’s. Each
character or a number is represented by an 8 bit code.

The set of 8 bits is called a byte.

A character occupies 1 byte space.

A numeric occupies 2 byte space.

Byte is the space occupied in the memory.

The size of the primary storage is specified in KB (Kilobytes) or MB


(Megabyte). One KB is equal to 1024 bytes and one MB is equal to
1000KB. The size of the primary storage in a typical PC usually
starts at 16MB. PCs having 32 MB, 48MB, 128 MB, 256MB memory
are quite common.

Output Unit:

The output unit of a computer provides the information and results


of a computation to outside world. Printers, Visual Display Unit
(VDU) are the commonly used output devices. Other commonly
used output devices are floppy disk drive, hard disk drive, and
magnetic tape drive.

Arithmetic Logical Unit:

All calculations are performed in the Arithmetic Logic Unit (ALU) of


the computer. It also does comparison and takes decision. The ALU
can perform basic operations such as addition, subtraction,
multiplication, division, etc and does logic operations >, <, =, ‘etc.
Whenever calculations are required, the control unit transfers the
data from storage unit to ALU once the computations are done, the
results are transferred to the storage unit by the control unit and
then it is send to the output unit for displaying results.

Control Unit:

It controls all other units in the computer. The control unit instructs
the input unit, where to store the data after receiving it from the
user. It controls the flow of data and instructions from the storage
unit to ALU. It also controls the flow of results from the ALU to the
storage unit. The control unit is generally referred as the central

3
Computer Programming & Data Structures

nervous system of the computer that control and synchronizes it’s


working.

Central Processing Unit:

The control unit and ALU of the computer are together known as the
Central Processing Unit (CPU). The CPU is like brain performs the
following functions:

• It performs all calculations.

• It takes all decisions.

• It controls all units of the computer.

A PC may have CPU-IC such as Intel 8088, 80286, 80386, 80486,


Celeron, Pentium, Pentium Pro, Pentium II, Pentium III, Pentium IV,
Dual Core, and AMD etc.

1.1 COMPUTER SYSTEMS

A computer is a system made of two major components: hardware


and software. The computer hardware is the physical equipment.
The software is the collection of programs (instructions) that allow
the hardware to do its job.

Computer
System

Hardware Software

Fig. 1: Major Components of Computer System

1.1.1 Computer Hardware

4
Computer Programming & Data Structures

The hardware component of the computer system consists of five


parts: input devices, central processing unit (CPU), primary storage,
output devices, and auxiliary storage devices.

Fig. 2: Basic Hardware Components

The input device is usually a keyboard where programs and data


are entered into the computers. Examples of other input devices
include a mouse, a pen or stylus, a touch screen, or an audio input
unit.

The central processing unit (CPU) is responsible for executing


instructions such as arithmetic calculations, comparisons among
data, and movement of data inside the system. Today’s computers
may have one, two, or more CPUs.

Primary storage, also known as main memory, is a place where


the programs and data are stored temporarily during processing.
The data in primary storage are erased when we turn off a personal
computer or when we log off from a time-sharing system.

The output device is usually a monitor or a printer to show output.


If the output is shown on the monitor, we say we have a softcopy.
If it is printed on the printer, we say we have a hardcopy.

Auxiliary storage, also known as secondary storage, is used for


both input and output. It is the place where the programs and data
are stored permanently. When we turn off the computer, or
programs and data remain in the secondary storage, ready for the
next time we need them.

1.1.2 Computer Software

5
Computer Programming & Data Structures

Computer software is divided into two broad categories: system


software and application software .System software manages the
computer resources .It provides the interface between the hardware
and the users. Application software, on the other hand is directly
responsible for helping users solve their problems.

Software

System Application
software software

Operating System System General Application


Systems support Development Purpose Specific

Fig. 3: Types of Software

1. System Software

System software consists of programs that manage the hardware


resources of a computer and perform required information
processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.

The operating system provides services such as a user interface,


file and database access, and interfaces to communication systems
such as Internet protocols. The primary purpose of this software is
to keep the system operating in an efficient manner while allowing
the users access to the system.

System support software provides system utilities and other


operating services. Examples of system utilities are sort programs
and disk format programs. Operating services consists of programs
that provide performance statistics for the operational staff and
security monitors to protect the system and data.

6
Computer Programming & Data Structures

The last system software category, system development


software, includes the language translators that convert programs
into machine language for execution, debugging tools to ensure that
the programs are error free and computer–assisted software
engineering (CASE) systems.

2. Application software

Application software is broken in to two classes: general-purpose


software and application–specific software. General purpose
software is purchased from a software developer and can be used
for more than one application. Examples of general purpose
software include word processors, database management systems,
and computer aided design systems. They are labeled general
purpose because they can solve a variety of user computing
problems.

Application–specific software can be used only for its intended


purpose. A general ledger system used by accountants and a
material requirements planning system used by a manufacturing
organization are examples of application-specific software. They can
be used only for the task for which they were designed they cannot
be used for other generalized tasks.

The relationship between system and application software is shown


in fig-4.In this figure, each circle represents an interface point .The
inner core is hard ware. The user is represented by the out layer. To
work with the system, the typical user uses some form of
application software. The application software in turn interacts with
the operating system, which is apart of the system software layer.
The system software provides the direct interaction with the hard
ware. The opening at the bottom of the figure is the path followed
by the user who interacts directly with the operating system when
necessary.

7
Computer Programming & Data Structures

Fig. 4: Relationship between System and Application


Software

1.2 COMPUTING ENVIRONMENTS

In the early days of computers, there was only one environment:


the main frame computer hidden in a central computing
department. With the advent of mini computers and personal
computers, the environment changed, resulting in computers on
virtually every desktop.

1.2.1 Personal Computing Environment

In 1971, Marcian E.Hoff, working for Intel, combined the basic


elements of the central processing unit into the microprocessor. The
first computer on a chip was the Intel 4004 and was the
grandparent many times removed of Intel’s current system.

If we are using a personal computer, all of the computer


hardware components are tied together in our personal computer
(PC).

Fig. 5: Personal Computing Environment

1.2.2 Time-Sharing Environment

Employees in large companies often work in what is known as a


time-sharing environment. In the times-sharing environment,
many users are connected to one or more computers. These
computers may be minicomputers or central mainframes. The
terminals they use are often nonprogrammable, although today we
see more and more microcomputers being used to simulate
8
Computer Programming & Data Structures

terminals. Also, in the time-sharing environment, the output devices


and auxiliary storage devices are shared by all of the users. A
typical college lab in which a minicomputer is shared is shared by
many students is shown in fig.6.

Fig. 6: Time-sharing Environment

In the time-sharing environment, all computing must be done by


the central computer. The central computer has many duties: It
must control the shared resources; it must manage the shared data
and printing and it must do the computing.

1.2.3 Client/Server Environment

A client/server computing environment splits the computing


function between a central computer and users’ computers. The
users are given personal computers or work stations so that some
of the computation responsibility can be moved from the central
computer and assigned to the workstations. In the client-server
environment, the users’ micro computers or workstations are called
the client. The central computer, which may be a powerful
microcomputer, minicomputer, or central mainframe system, is
known as the server. Because the work is now shared between the
users’ computers and the central computer, response time and
monitor display are faster and the users are more productive.

9
Computer Programming & Data Structures

Fig. 7: The Client/Server Environment

1.2.4 Distributed Computing Environment

A Distributed Computing Environment provides a seamless


integration of computing functions between different servers and
clients. The internet provides connectivity to different servers
throughout the world. For example eBay uses several computers to
provide its auction services. This environment provides a reliable,
scalable, and highly available network.

Fig. 8: Distributed Computing

10
Computer Programming & Data Structures

1.3 COMPUTER LANGUAGES

To write a program for a computer, we must use a computer


language. Over the years computer languages have evolved from
machine languages to natural languages.

1.3.1 Machine Languages

In the earliest days of computers, the only programming languages


available were machine languages. Each computer has its own
machine language, which is made of streams of 0’s and 1’s.

Instructions in machine language must be in streams of 0’s


and 1’s because the internal circuits of a computer are made of
switches, transistors and other electronic devices that can be in one
of two states: off or on. The off state is represented by 0; the on
state is represented by 1.

The only language understood by computer hardware is


machine language.

a. Advantages:

i. Computer can understand directly.

b. Disadvantages:

i. It is very difficult to remember the codes and address of


memory locations.
ii. User can’t modify the program.
iii. User can’t debug the program.
iv. It is machine dependent.
v. It is suitable for simple applications.
11
Computer Programming & Data Structures

1.3.2 Symbolic Languages

In early 1950’s Admiral Grace Hopper, A mathematician and naval


officer developed the concept of a special computer program that
would convert programs into machine language. The early
programming languages simply mirror to the machine languages
using symbols of mnemonics to represent the various machine
language instructions because they used symbols, these languages
were known as symbolic languages.

Computer does not understand symbolic language it must be


translated to the machine language. A special program called
assembler translates symbolic code into machine language. Because
symbolic languages had to be assembled into machine language
they soon became known as assembly languages.

Symbolic language uses symbols or mnemonics to represent


the various machine language instructions.

a. Advantages:

i. User can remember the mnemonics.


ii. It is easy to understand and develop the programs.
iii. User can modify the program and debug.
iv. It is suitable for simple applications.

b. Disadvantages:
i. It is machine dependent.
ii. It requires the translator program called Assembler.

1.3.3 High Level Languages

Symbolic languages greatly improved programming efficiency; they


still required programmers to concentrate on the hardware that
they were using. Working with symbolic languages was also very
tedious because each machine instruction has to be individually
coded. The desire to improve programmer efficiency and to change
the focus from the computer to the problem being solved led to the
development of high-level language.

12
Computer Programming & Data Structures

High level languages are portable to many different


computers. High-level languages are designed to relieve the
programmer from the details of the assembly language. High level
languages share one thing with symbolic languages; they must be
converted into machine language. The process of converting them is
known as compilation.

The first widely used high-level languages, FORTRAN


(FORmula TRANslation) was created by John Backus and an IBM
team in 1957; it is still widely used today in scientific and
engineering applications. After FORTRAN was COBOL (Common
Business-Oriented Language). Admiral Hopper was played a key
role in the development of the COBOL Business language.

C is a high-level language used for system software and new


application code.

a. Advantages:

i. Easy to follow.
ii. Easy to understand
iii. Easy to modify and debug.
iv. Suitable for complex applications.

b. Disadvantages:

i. It requires the translator program called Compiler or


Interpreter.
ii. It runs programs slower with compare to low level
languages

13
Computer Programming & Data Structures

1.4 CREATING AND RUNNING PROGRAMS

Computer hardware understands a program only if it is coded in its


machine language. It is the job of the programmer to write and test
the program .There are four steps in this process:
1. Writing and editing the program
2. Compiliing the program
3. Linking the program with the required library modules
4. Executing the program.

14
Computer Programming & Data Structures

Fig. 9: Building a C Program

1.4.1 Writing and Editing Programs

The software used to write programs is known as a text editor. A


text editor helps us enter, change, and store character data.
Depending on the editor on our system, we could use it to write
letters, create reports, or write programs. The main difference
between text processing and program writing is that programs are
written using lines of code, while most text processing is done with
character and lines.

Text editor is a generalized word processor, but it is more


often a special editor included with the compiler. Some of the
features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements
from one part of a program to another, and formatting commands
that allow us to set tabs to align statements.

After completing a program, we save our file to disk. This file


will be input to the compiler; it is known as a source file.

1.4.2 Compiling Programs

The code in a source file stored on the disk must be translated into
machine language; this is the job of the compiler. The c compiler is
two separate programs. the preprocessor and the translator.

15
Computer Programming & Data Structures

The preprocessor reads the source code and prepares it for


the translator. While preparing the code, it scans for special
instructions known as preprocessor commands. These commands
tell the preprocessor to look for special code libraries, make
substitutions in the code, and in other ways prepare the code for
translation into machine language. The result of preprocessing is
called the translation unit.

After the preprocessor has prepared the code for compilation,


the translator does the actual work of converting the program into
machine language. The translator reads the translation unit and
writes the resulting object module to a file that can then be
combined with other precompiled units to form the final program.
An object module is the code in machine language. The output of
the compiler is machine language code, but it is not ready to run;
that is, it is not executable because it does not have the required C
and other functions included.

1.4.3 Linking Programs

A C program is made up of many functions. We write some of these


functions, and they are a part of our source program. There are
other functions, such as input/output processes and, mathematical
library functions that exist elsewhere and must be attached to our
program. The linker assembles all of these functions, ours and
systems into our final executable program.

1.4.4 Executing Programs

Once program has been linked, it is ready for execution. To execute


a program we use an operating system command, such as run
(CTRL+F9), to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating
system program known as the loader. It locates the executable
program and reads it into memory. When everything is loaded, the
program takes control and it begins execution.

In a typical program execution, the program reads data for


processing, either from the user or from a file. After the program
processes the data, it prepares the output. Data output can be to
the user’s monitor or to a file. When the program has finished its
job, it tells the operating system, which then removes the program
from memory.

16
Computer Programming & Data Structures

1.5 SOFTWARE DEVELOPMENT METHOD

A software development process is a structure imposed on the


development of a software product. This critical process determines
the overall quality and success of our program. If we carefully
design each program using good structured development
techniques, programs will be efficient, error-free, and easy to
maintain.

System Development Life Cycle

Today’s large-scale modern programming projects are built using a


series of interrelates phases commonly referred to as the system
development life cycle (SDLC). One very popular development life
cycle developed, this model consists of between 5 and 7 phases.

The waterfall model starts with systems requirements in


this phase the systems analyst defines requirements that specify
what the proposed system is to accomplish. The requirements are
usually stated in terms that the user understands. The analysis
phase looks at different alternatives from a systems point of view
while the design phase determined how the system will be built. In
the design phase the functions of the individual programs that will
make up the system are determined and the design of the files
and / or the databases is completed. Finally in the 4 th phase code,
we write the programs. After the programs have been written and
tested to the programmer’s satisfaction, the project proceeds to the
system test. All of the programs are tested together to make sure
of the system works as a whole. The final phase maintenance
keeps the system working once it has been put into production.

Although the implication of the waterfalls approach is that the


phases flow in a continuous stream from the first to the last, this is
not really the case. As each phase is developed, errors and
omissions will often be found in the previous work. When this
happens it is necessary to go back to the previous phase to rework
it for consistency and to analyze the impact caused by the changes.

17
Computer Programming & Data Structures

Fig. 10: Waterfall Model

1.6 ALGORITHMS

An algorithm (pronounced AL-go-rith-um) is a procedure or formula


for solving a problem.

A computer program can be viewed as an elaborate algorithm. In


mathematics and computer science, an algorithm usually means a
small procedure that solves a recurrent problem.

An algorithm is a step-by-step method of solving a problem.

An algorithm is an established mechanical procedure for solving


certain mathematical problems.

Algorithm can be defined as: “A sequence of activities to be


processed for getting
desired output from a given input.”

Properties:
1. Finiteness: An algorithm should have finite number of steps.
2. Definiteness: Any step of an algorithm should be definite and
unambiguous.
3. Effectiveness: An algorithm should be effective in solving the
problem that it's meant for.
4. Input: It should have zero or more inputs.
5. Output: It should have 1 or more outputs.

18
Computer Programming & Data Structures

Before writing an algorithm for a problem, one should find out what
is/are the inputs to the algorithm and what is/are expected output
after running the algorithm.

While writing algorithms we will use following symbol for different


operations:

‘+’ for Addition


‘-’ for Subtraction
‘*’ for Multiplication
‘/’ for Division and
‘←’ for assignment. For example A←X*3 means A will have a value
of X*3

Example1: Algorithm to add two numbers

Step 1: Start
Step 2: Read the two numbers into a, b
Step 3: c  a+b
Step 4: write/print c
Step 5: Stop.

Example2: Algorithm to find the sum of individual digits of a


given positive integer.

Step 1: start
Step 2: read a positive integer no
Step 3: sum←0 dig←0
Step 4: dig ← no mod 10
Step 5: sum ← sum + dig
Step 6: no ← no/10
Step 7: repeat steps 3, 4, 5 until no greater than zero
Step 8: print sum
Step 9: stop
Example3: Algorithm to find the roots of a quadratic
equation.

Step 1: start
Step 2: read a, b, c values
Step 3: compute d=b*b-4ac

19
Computer Programming & Data Structures

Step 4: if d > 0 then

r1← (-b+sqrt (d))/ (2*a)


r2← (-b-sqrt (d))/ (2*a)
Step 5: if d=0 then
r1← -b/ (2*a)
r2← -b/ (2*a)
Step 6: if d < 0
r1← -b/ (2*a)
r2← sqrt (-d)/ (2*a)
Step 7: write r1, r2
Step 8: stop
Example 4: Convert temperature Fahrenheit to Celsius

Inputs to the algorithm:


Temperature in Fahrenheit

Expected output:
Temperature in Celsius

Algorithm:

Step 1: Read Temperature in Fahrenheit F


Step 2: C← 5/9*(F-32)
Step 3: Print Temperature in Celsius: C

1.7 PSEUDO CODE

Pseudo code is an artificial programming language that allows


computer programmers to develop logic before executing a
particular code. It can be defined as the blueprint of a code, which
details a step of actions (or the procedure) and the order in which
the steps are to be executed. It can be thought of as a textual
representation of a flowchart, reflecting the structural concepts of
code.
Background
Pseudo code is a type of structured English that defines program
algorithms. It allows programs to focus on algorithms core logic
before setting it in formal programming syntax. Pseudocde is not

20
Computer Programming & Data Structures

executable on a computer. Instead, it helps a programmer design


code before its actual implementation.
Purpose

The main purpose of pseudo code is to describe clearly what a code


(or program) is supposed to do. It breaks down a code into steps
and highlights their sequence of action. Pseudo code allows coders
and programmers to dry-run a code to check for errors and
inconsistencies before writing it in a programming language.
Rules

Pseudo code is composed of sentences, clauses and words. It


follows a structured pattern, with statements written in a sequential
order. Pseudo code uses selection statements (if, then and if, then,
else), and the initial keyword in each statement needs to be
capitalized. It requires one statement per sentence, which need to
be indented to show code hierarchy.
Example

M = 10
N=5
(Where M and N are variables)
IF (M >= N) Then
Statement 1
Else
Statement 2
END IF
Statement 3
According to this example, the condition of M>=N is true (since M is
10 and N is 5), and statement 1 will be executed. The execution of
statement 3 follows that.

Advantages

Pseudo code makes it easy to implement a program. It is the


intermediary step between a formal programming language code
and human language, and explains the purpose of a particular code
in layman's terms. It is easy to write and requires a simple text
editor (Microsoft Word or Notepad) to create pseudo code
statements. Pseudo code requires minimal programming

21
Computer Programming & Data Structures

knowledge, and has few formal syntax rules. It saves time that is
otherwise spent in debugging and testing codes, since it allows
programmers to spot and correct errors.

Disadvantages

Pseudo code can be lengthy and complicated when coding a


complex problem. There are no standardized rules for writing
pseudo code and it varies from company to company and individual
to individual. Pseudo code offers no visual representation of code,
making it difficult to ascertain the validity of certain statements.

1.8 FLOWCHARTS

A Flowchart is a Graphical representation of an Algorithm or a


portion of an Algorithm. Flowcharts are drawn using certain special
purpose symbols such as Rectangles, Diamonds, Ovals and small
circles. These symbols are connected by arrows called flow lines.

(Or)

The diagrammatic representation of way to solve the given problem


is called flow chart.

Guidelines for drawing a Flowchart

Flow charts are drawn using slandered flowchart symbols. While


drawing flowchart some guideline to be followed. Below are some
guidelines for drawing flowchart:

1) First of all list all necessary requirements in a logical order.

2) The flowchart should be clear and easy to understand. There


should not be any ambiguity in understanding the flowchart. For
doing this it is necessary to have all the
steps and operation very simple.

3) Usually direction of the flow of data /procedure in the system


should be from left

22
Computer Programming & Data Structures

to right or top to bottom.

4) Only one flow line should come out from a process symbol.

5) In the case of use of decision symbol, only one flow line should
enter to it (decision symbol), but there may be two or three flow
lines coming out of the decision symbol, one for each possible
answer.

6) In a flowchart only one flow line should come to the end symbol.

7) While writing steps in side the processing symbol, steps should


be brief and if necessary, you can use the annotation symbol to
describe data or processing steps more clearly.

8) In the case of complex flowchart connector symbols to be used


for reducing the

23
Computer Programming & Data Structures

number of flow lines in the flowchart.

9) Intersection of flow lines should be avoided to make a flowchart


more effective
and for better way of communication.

10) A flowchart must have a logical start and end.

11) Once a flowchart is drawn its validity should be tested by


passing through it with
a simple set of test data.

The following are the most common symbols used in drawing


flowcharts:

Limitations of using Flowcharts

24
Computer Programming & Data Structures

1. Complex logic: Sometimes, the program logic is quite


complicated. In that case, flowchart becomes complex and
clumsy.
2. Alterations and Modifications: If alterations are required the
flowchart may require re-drawing completely.

3. Reproduction: As the flowchart symbols cannot be typed,


reproduction of flowchart becomes a problem.

4. The essentials of what is done can easily be lost in the


technical details of how it is done.

Advantages of using Flowcharts

The benefits of flowcharts are as follows:

1. Communication: Flowcharts are better way of communicating


the logic of a system to all concerned.
2. Effective analysis: With the help of flowchart, problem can be
analyzed in more effective way.

3. Proper documentation: Program flowcharts serve as a good


program documentation, which is needed for various
purposes.

4. Efficient Coding: The flowcharts act as a guide or blueprint


during the systems analysis and program development phase.

5. Proper Debugging: The flowchart helps in debugging process.

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

Example1: Find the area of a circle of radius r.

25
Computer Programming & Data Structures

Example2: Convert temperature Fahrenheit to Celsius.

26
Computer Programming & Data Structures

1.9 PROGRAM DEVELOPMENT STEPS

Program Development is a multistep process that requires that we


understand the problem, develop a solution, write the program, and
then test it. When we are given the assignment to develop a
program, we will be given a program requirements statement and
the design of any program interfaces. We should also receive an
overview of the complete project so that we will take the inputs we
are given and convert them to the outputs that have been specified.
This is known as program design.

1.9.1 Understand the Problem

The first step in solving any problem is to understand it. By reading


the requirements statements carefully, we fully understand it; we
review our understanding with the user and the systems analyst to
know the exact purpose.

1.9.2 Develop the solution

Once we fully understand the problem we need to develop our


solution. Three tools will help in this task. 1. Structure chart,
2.Psuedocode &3.Flowcharts. Generally we will use structure chart
and either flowchart or Pseudo code.
27
Computer Programming & Data Structures

The structure chart is used to design the whole program. Pseudo


code and flowcharts are used to design the individual parts of the
program.

Structure chart: A structure chart, also known as hierarchy chart,


shows the functional flow through our program. The structure chart
shows how we are going to break our program into logical steps
each step will be a separate module. The structure chart shows the
interaction between all the parts (modules) of our program.

We can use flowchart or pseudo code to complete the design of your


program will depend on experience and difficulty of the program
your designing.

1.9.3 Write the program

When we write a program, we start with the top box on the


structure chart and work our way to the bottom. This is known as
top-down implementation. We will write the programs by using
structure chart and flowchart or pseudo code.

1.9.4 Test the Program

Program testing can be a very tedious and time-consuming part of


program development. As the programmer we are responsible for
completely testing our program. In large-development projects test
engineers are responsible for testing to make sure all the programs
work together.

There are 2 types of testing.

1. Black box testing: This is done by the system test engineer


and the user. Black box testing is the programs are tested
without knowing what is inside it, without knowing how it
works. Black box test plans are developed by looking only the
requirements statement. The test engineer uses these
requirements to develop test plans.
2. White box testing: This is the responsibility of the
programmer. White box testing assumes that the tester
knows everything about the program.

28
Computer Programming & Data Structures

Except for the simplest program, one set of test data will not
completely validate a program.

INTRODUCTION TO C LANGUAGE

Introduction to C Language – Background, Simple C Programme,


Identifiers, Basic data types, Variables, Constants, Input / Output,
Operators, Expressions, Precedence and Associativity, Expression
Evaluation, Type conversions, Bit wise operators, Statements,
Simple C Programming examples.
Selection Statements – if and switch statements, Repetition
statements – while, for, do-while statements, Loop examples, other

29
Computer Programming & Data Structures

statements related to looping – break, continue, goto, Simple C


Programming examples.

2.1 BACKGROUND

C language facilitates a very efficient approach to the development


and implementation of computer programs. The History of C started
in 1972 at the Bell Laboratories, USA where Dennis M. Ritchie
proposed this language. In 1983 the American National Standards
Institute (ANSI) established committee whose goal was to produce
“an unambiguous and machine independent definition of the
language C “while still retaining its spirit.

C is the programming language most frequently associated


with UNIX. Since the 1970s, the bulk of the UNIX operating system
and its applications have been written in C. Because the C language
does not directly rely on any specific hardware architecture, UNIX
was one of the first portable operating systems. In other words, the
majority of the code that makes up UNIX does not know and does
not care which computer it is actually running on. Machine-specific
features are isolated in a few modules within the UNIX kernel, which
makes it easy for you to modify them when you are porting to
different hardware architecture.

C was first designed by Dennis Ritchie for use with UNIX on


DEC PDP-11 computers. The language evolved from Martin
Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first
book on C was The C Programming Language by Brian Kernighan
and Dennis Ritchie, published in 1978.

In 1983, the American National Standards Institute (ANSI)


established a committee to standardize the definition of C. The
resulting standard is known as ANSI C, and it is the recognized
standard for the language, grammar, and a core set of libraries. The
syntax is slightly different from the original C language, which is
frequently called K&R for Kernighan and Ritchie. There is also an
ISO (International Standards Organization) standard that is very
similar to the ANSI standard. It appears that there will be yet
another ANSI C standard officially dated 1999 or in the early 2000
years; it is currently known as "C9X."

2.2 BASIC STRUCTURE OF C LANGUAGE

30
Computer Programming & Data Structures

The program written in C language follows this basic structure. The


sequence of sections should be as they are in the basic structure. A
C program should have one or more sections but the sequence of
sections is to be followed.

1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section

1. Documentation Section: comes first and is used to document


the use of logic or reasons in your program. It can be used to write
the program's objective, developer and logic details. The
documentation is done in C language with /* and */. Whatever is
written between these two are called comments.

2. Linking Section: This section tells the compiler to link the


certain occurrences of keywords or functions in your program to the
header files specified in this section.
e.g. #include <stdio.h>

3. Definition Section: It is used to declare some constants and


assign them some value.
e.g. #define MAX 25

Here #define is a compiler directive which tells the compiler


whenever MAX is found in the program replace it with 25.

4. Global Declaration Section: Here the variables which are used


through out the program (including main and other functions) are
declared so as to make them global (i.e. accessible to all parts of
program)
e.g. int i; (before main ())

5. Main Function Section: It tells the compiler where to start the


execution from main().
main()
{
point from execution starts

31
Computer Programming & Data Structures

main function has two sections

1. Declaration section: In this the variables and their data


types are declared.

2. Executable section: This has the part of program which


actually performs the task we need.

7. Sub Program or Function Section: This has all the sub


programs or the functions which our program needs.

Simple ‘C’ Program:

/* simple program in c */
#include<stdio.h>
main()
{
printf(“welcome to c programming”);
} /* End of main */

2.3 C-TOKENS

Tokens are individual words and punctuations marks in English


language sentence. The smallest individual units are known as C
tokens.

A C program can be divided into these tokens. A C program


contains minimum 3 c tokens no matter what the size of the
program is.

OPERATORS E.g. +, -,*

SPECIAL SYMBOLS E.g. [ ], { }

STRINGS E.g. “asifia”


C
TOKENS 32
Computer Programming & Data Structures

CONSTANTS E.g.15.4,‘a’,200

E.g.rate,no_of_hours
IDENTIFIERS
E.g. int, printf
KEY WORDS

Fig. 1: C-Tokens

IDENTIFIERS

Names of the variables and other program elements such as


functions, array, etc are known as identifiers.

There are few rules that govern the way variables are
named(identifiers).

1. Identifiers can be named from the combination of A-Z, a-z,


0-9, _(underscore).
2. The first alphabet of the identifier should be either an
alphabet or an underscore. Digit is not allowed.
3. It should not be a keyword.

E.g.: name, ptr, sum


After naming a variable we need to declare it to compiler of what
data type it is.

The format of declaring a variable is

Data-type id1, id2 ...idn;

where data type could be float, int, char or any of the data
types.

id1, id2, id3 are the names of variable we use. In case of


single variable no commas are required.

e.g. float a, b, c;
int e, f, grand total;
char present_or_absent;

KEYWORDS

33
Computer Programming & Data Structures

There are certain words, called keywords (reserved words) that


have a predefined meaning in ‘C’ language. These keywords are
only to be used for their intended purpose and not as identifiers.

The following table shows the standard ‘C’ keywords

Auto break case char const continue

default do double else enum extern

Float for goto if int long

register return short signed sizeof static

Struct switch typedef union unsigned void

volatile while

2.4 DATA TYPES

To represent different types of data in C program we need different


data types. A data type is essential to identify the storage
representation and the type of operations that can be performed on
that data. C supports four different classes of data types namely

1. Basic data types


2. Derived data types
3. User defined data types
4. Pointer data types

2.4.1 Basic Data Types

All arithmetic operations such as Addition, subtraction etc is


possible on basic data types.

E.g.: int a, b;
char c;

The following table shows the Storage size and Range of


basic data types:

TYPE LENGTH RANGE

unsigned char 8 bits 0 to 255

34
Computer Programming & Data Structures

char 8 bits -128 to 127


short int 16 bits -32768 to 32767
unsigned int 32 bits 0 to
4,294,967,295
int 32 bits -2,147,483,648 to
2,147,483,648
unsigned long 32 bits 0 to
4,294,967,295
enum 16 bits -2,147,483,648 to
2,147,483,648
long 32 bits -2,147,483,648 to
2,147,483,648
float 32 bits 3.4*10E-38 to
3.4*10E38
double 64 bits 1.7*10E-308
to 1.7*10E308
long double 80 bits 3.4*10E-4932 to
1.1*10E4932

2.4.2 Derived Data Types

Derived data types are used in ‘C’ to store a set of data values.
Arrays and Structures are examples for derived data types.

Ex: int a[10];


char name[20];

2.4.3 User Defined Data Types

C Provides a facility called typedef for creating new data type names
defined by the user. For Example, the declaration,
typedef int Integer;

makes the name Integer a synonym of int. Now the type Integer
can be used in declarations, casts, etc, like,

Integer num1, num2;

Which will be treated by the C compiler as the declaration of num1,


num2 as int variables?

“typedef” is more useful with structures and pointers.

35
Computer Programming & Data Structures

2.4.4 Pointer Data Types

Pointer data type is necessary to store the address of a variable.

2.5 VARIABLES

A quantity that can vary during the execution of a program is


known as a variable. To identify a quantity we name the variable for
example if we are calculating a sum of two numbers we will name
the variable that will hold the value of sum of two numbers as
'sum'.

Assigning Values to Variables

When we name and declare variables we need to assign value to


the variable. In some cases we assign value to the variable directly
like

Syntax: variable_name=value;

e.g.: a=10;

In some cases we need to assign values to variable after the


user has given input for that.
E.g. we ask user to enter any no and input it

Example:
/* write a program to show assigning of values to variables */
#include<stdio.h>
main()
{
int a;
float b;
printf("Enter any number\n");
b=190.5;
scanf("%d",&a);
printf("user entered %d", a);
printf("B's values is %f", b);
}

2.6 CONSTANTS

36
Computer Programming & Data Structures

A quantity that does not vary during the execution of a program is


known as a constant. It supports two types of constants namely
Numeric constants and character constants.

2.6.1 Numeric Constants

1. Example for an integer constant is 786,-127

2. Long constant is written with a terminal ‘l’or ‘L’, for example


1234567899L is a Long constant.

3. Unsigned constants are written with a terminal ‘u’ or ‘U’, and the
suffix ‘ul’ and ‘UL’ indicates unsigned long. for example 123456789u
is a Unsigned constant and
1234567891ul is an unsigned long constant.

4. The advantage of declaring an unsigned constant is to increase


the range of storage.

5. Floating point constants contain a decimal point or an exponent


or both. For Eg:
123.4, 1e-2, 1.4E-4, etc.The suffixes f or F indicate a float constant
while the absence of f or F indicate the double, l or L indicate long
double.

2.6.2 Character Constants

A character constant is written as one character with in single


quotes such as ‘a’. The value of a character constant is the
numerical value of the character in the machines character set.
Certain character constants can be represented by escape
sequences like ‘\n’. These sequences look like two characters but
represent only one.

The following are the some of the examples of escape sequences:

Escape sequence Description

\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return

37
Computer Programming & Data Structures

\t Horizontal Tab
\v Vertical Tab

String constants or string literal is a sequence of zero or more


characters surrounded by a double quote. Example, “I am a little
boy”. Quotes are not a part of the string.

To distinguish between a character constant and a string that


contains a single character ex: ‘a’ is not same as “a”. ‘a’ is an
integer used to produce the numeric value of letter a in the machine
character set, while “a” is an array of characters containing one
character and a ‘\0’ as a string in C is an array of characters
terminated by NULL.

There is one another kind of constant i.e Enumeration


constant, it is a list of constant integer values.
Ex.: enum color {RED, GREEN, BLUE}

The first name in the enum has the value 0 and the next 1
and so on unless explicit values are specified.

If not all values specified, unspecified values continue the


progression from the last specified value. For example

Enum months {JAN=1, FEB, MAR… DEC}

Where the value of FEB is 2 and MAR is 3 and so on.

Enumerations provide a convenient way to associate constant


values with names.

2.7 OPERATORS

An operator is a symbol that tells the compiler to perform certain


mathematical or logical manipulations. They form expressions.

C operators can be classified as

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator

38
Computer Programming & Data Structures

7. Bit wise operators


8. Special operators

1. Arithmetic Operators: All basic arithmetic operators are


present in C.

operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)

An arithmetic operation involving only real operands(or


integer operands) is called real arithmetic(or integer arithmetic). If
a combination of arithmetic and real is called mixed mode
arithmetic.

2. Relational Operators: We often compare two quantities and


depending on their relation take certain decisions for that
comparison we use relational operators.

operator meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
It is the form of
ae-1 relational operator ae-2

3. Logical Operators: An expression of this kind which combines


two or more relational expressions is termed as a logical
expressions or a compound relational expression. The operators and
truth values are

op-1 op-2 op-1 && op-2 op-1 || op-2

non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0

op-1 !op-1

39
Computer Programming & Data Structures

non-zero zero
zero non-zero

4. Assignment Operators: They are used to assign the result of


an expression to a variable. The assignment operator is '='.
Syntax: v op=exp

v is variable

op binary operator

exp expression

op= short hand assignment operator

Short hand assignment operators

use of simple assignment operators use of short hand


assignment operators

a=a+1 a+=1

a=a-1 a-=1

a=a%b a%=b

5. Increment and Decrement Operators :

++ and -- are called increment and decrement operators used


to add or subtract.
Both are unary and as follows
++m or m++
--m or m--
The difference between ++m and m++ is
if m=5; y=++m then it is equal to m=5;m++;y=m;
if m=5; y=m++ then it is equal to m=5;y=m;m++;

6. Conditional Operator: A ternary operator pair "?:" is available


in C to construct conditional expressions of the form

Syntax: exp1? exp2: exp3;


It work as
if exp1 is true then exp2 else exp3

7. Bitwise operators: C supports special operators known as bit


wise operators for manipulation of data at bit level. They are not
applied to float or double.

40
Computer Programming & Data Structures

operator meaning

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
~ one's complement

8. Special operators: These operators which do not fit in any of


the above classification are ,(comma), sizeof, Pointer operators(&
and *) and member selection operators (. and ->). The comma
operator is used to link related expressions together.

sizeof operator is used to know the sizeof operand.

Example1:

/* programs to exhibit the use of operators */


#include<stdio.h>
main()
{
int sum, mul, modu;
float sub, divi;
int i,j;
float l, m;
printf("Enter two integers ");
scanf("%d%d",&i,&j);
printf("Enter two real numbers");
scanf("%f%f",&l,&m);
sum=i+j;
mul=i*j;
modu=i%j;
sub=l-m;
divi=l/m;
printf("sum is %d", sum);
printf("mul is %d", mul);
printf("Remainder is %d", modu);

41
Computer Programming & Data Structures

printf("subtraction of float is %f", sub);


printf("division of float is %f", divi);
}
Example2:

/* program to implement relational and logical */


#include<stdio.h>
main()
{
int i, j, k;
printf("Enter any three numbers ");
scanf("%d%d%d", &i, &j, &k);
if((i<j)&&(j<k))
printf("k is largest");
else if i<j || j>k
{
if i<j && j >k
printf("j is largest");
else
printf("j is not largest of all");
}
}

Example3:

/* program to implement increment and decrement operators */


#include<stdio.h>
main()
{
int i;
printf("Enter a number");
scanf("%d", &i);
i++;
printf("after incrementing %d ", i);
i--;
printf("after decrement %d", i);
}

Example4:

/* program using ternary operator and assignment */


#include<stdio.h>
main()
{
int i,j,large;
42
Computer Programming & Data Structures

printf("Enter two numbers ");


scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("largest of two is %d",large);
}

2.8 EXPRESSIONS

An expression is a sequence of operands and operators that reduces


to a single value. Expression can be simple or complex. An
operator is a syntactical token that requires an action be taken. An
operand is an object on which an operation is performed.
A simple expression contains only one operator.E.g: 2 + 3 is a
simple expression whose value is 5.A complex expression contains
more that one operator. E.g: 2 + 3 * 2.

To evaluate a complex expression we reduce it to a series of


simple expressions. In this first we will evaluate the simple
expression 3 * 2 (6) and then the expression 2 + 6, giving a result
of 8.

2.8.1 Precedence

The order in which the operators in a complex expression are


evaluated is determined by a set of priorities known as
precedence, the higher the precedence ,the earlier the expression
containing the operator is evaluated. If two operators with the same
precedence occur in a complex expression, another attribute of an
operator, its associativity, takes control.

2.8.2 Associativity

Associativity is the parsing direction used to evaluate the


expression. It can be either left-to-right or right-to-left .When two
operators with the same precedence occur in an expression and
their associativity is left-to-right, the left operator is evaluated first.
For example, in the expression 3*4/6, there are two operators’
multiplication and division, with the same precedence and left-to-
right associativity .Therefore the multiplication is evaluated before
the division.

2.8.3 Arithmetic Expressions

It is a combination of variables, constants and operators arranged


according to the syntax of C language.

Some examples

43
Computer Programming & Data Structures

A*B–C

(M + N) * (X + Y)

Evaluation of expressions: Expressions are evaluated using an


assignment statement of the form

Variable = expression

Eg x = x*y + z-3 *(z *y)

2.8.4 Precedence of arithmetic expressions

Precedence of arithmetic expressions is used to evaluate an


expression to provide unambiguous way of solving an expression.
The highest precedence operator is evaluated then next highest
precedence operator until no operator is present.

The precedence or priorities are as follows

High * / %

Low + -

The following table shows the precedence and associativity


of operators:

44
Computer Programming & Data Structures

2.8.5 Expression Evaluation

An expression is evaluated in left to right and value is assigned


to variable in left side of assignment operator.
Example:

/* program to demonstrate evaluation of expressions */


#include<stdio.h>
main()
{
float a,b,c,x,y,z;
a=9;b=23;c=3;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("values of x,y,z are %d%d%d",x,y,z); }
2.9 TYPE CONVERSIONS

In an expression that involves two different data types, such as


multiplying an integer and a floating point number to perform these
evaluations, one of the types must be converted.

45
Computer Programming & Data Structures

We have two types of conversions

1. Implicit Type Conversion

2. Explicit Type Conversion

1. Implicit Type Conversion

When the types of the two operands in a binary expression are


different automatically converts one type to another .This is known
as implicit type conversion.

2. Explicit Type Conversion

Explicit type conversion uses the unary cast operator, to convert


data from one type to another. To cast data from one type to
another, we specify the new type in parentheses before the value
we want converted.

For example, to convert an integer, a, to a float, we code the


expression like

(float) a

2.10 INPUT AND OUTPUT STATEMENTS

2.10.1 Input Statements

The simplest of input operator is getchar to read a single character


from the input device.

Syntax: varname=getchar();

You need to declare varname.

The getchar() is used only for one input and is not formatted.
Formatted input refers to an input data that has been arranged in a
particular format, for that we have scanf.

Syntax: scanf("control string", arg1, arg2...argn);

Control string specifies field format in which data is to be entered.

arg1, arg2... argn specifies address of location or variable where


data is stored.

e.g. scanf("%d%d",&a,&b);

%d used for integers


46
Computer Programming & Data Structures

%f floats
%l long
%c character

2.10.2 Output Statements

The simplest of output operator is putchar to output a single


character on the output device.

Syntax: putchar(varname);

For formatted output you use printf

Syntax: printf("control string", arg1, arg2...argn);

Example:

/* program to exhibit I/O */

#include<stdio.h>
main()

{
int a,b;
float c;
printf("Enter any number");
a=getchar();
printf("the char is ");
putchar(a);
printf("Exhibiting the use of scanf");
printf("Enter three numbers");
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
}

2.11 STATEMENTS

A statement causes an action to be performed by the program. It


translates directly in to one or more executable computer
instructions.

47
Computer Programming & Data Structures

Statement Types

1. Null Statement:

The null statement is just a semicolon (the terminator).

Eg:

//null statement

Although they do not arise often, there are syntactical situations


where we must have a statement but no action is required .In these
situations we use the null statement.

2. Expression Statement:

An expression is turned in to a statement by placing a semicolon(;)


after it.

expression; //expression statement

Eg: a=2;

3. Return Statement:

A return statement terminates a function. All functions, including


main, must have a return statement. Where there is no return
statement at the end of the function, the system inserts one with a
void return value.

Syntax: return expression; //return statement

The return statement can return a value to the calling function. In


case of main, it returns a value to the operating system rather than
to another function. A return value of zero tells the operating
system that the program executed successfully.

4. Compound Statements:

A compound statement is a unit of code consisting of zero or more


statements .It is also known as a block. The compound statement
allows a group of statements to become one single entity.

A compound statement consists of an opening brace ,an


optional declaration and definition section ,and an optional
statement section ,followed by a closing brace.

Example:

{
//Local Declarations
48
Computer Programming & Data Structures

int x;
int y;
int z;
//Statements
x=1;
y=2;

} //End Block

2.12 SELECTION STATEMENTS

2.12.1 If Statements

We have a number of situations where we may have to change the


order of execution of statements based on certain conditions or
repeat a group of statements until certain specified conditions are
met.

if statement:

The if statement is a two way decision statement and is used in


conjunction with an expression. It takes the following form

if(test expression)

If the test expression is true then the statement block after


if is executed otherwise it is not executed. Only statement–x is
executed.

Syntax:

if (test expression)
{
statement block;

}
statement–x;

Example:

/* program for if */
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):

49
Computer Programming & Data Structures

if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
}

if–else statement:

If your have another set of statement to be executed if condition is


false then if-else is used.

Syntax:

if (test expression)
{
statement block1;
}
else
{
statement block2;
}
statement –x ;

Example:

/* program for if-else */


#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”);
else
printf(“b is greater”);
}

Nesting of if..else statement :

if-else statement within if-else statement is called nesting of if-else


statement.

Syntax:

50
Computer Programming & Data Structures

if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}

else
{
statement block2;
}
statement-x ;

if else ladder:

Syntax:

if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;

The nesting of if-else depends upon the conditions with which we


have to deal.

2.12.2 Switch Statement

If for suppose we have more than one valid choices to choose from
then we can use switch statement in place of if statements.

Syntax:

switch(expression)
51
Computer Programming & Data Structures

{.
case value-1
block-1
break;
case value-2
block-2
break;
--------
--------
default:
default block;
break;
}
statement–x;

In case of

if(cond1)
{
statement-1;
}
if (cond2)
{
statement-2;
}

Example:

/* program to implement switch */


#include<stdio.h>
main()
{
int marks,index;
char grade[10];
printf(“Enter your marks”);
scanf(“%d”,&marks);
index=marks/10;
switch(index)
{
case 10 :
case 9:
case 8:
case 7:
case 6: grade=”first”;
break;
52
Computer Programming & Data Structures

case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
default : grade =”fail”;
break;
}
printf(“%s”,grade);
}
2.13 LOOPING

Sometimes we require a set of statements to be executed


repeatedly until a condition is met.

We have two types of looping structures. One in which


condition is tested before entering the statement block called entry
control.

The other in which condition is checked at exit called exit


controlled loop.

2.13.1 Repetition Statements

While Statement :

Syntax: While(test condition)

body of the loop;

It is an entry controlled loop. The condition is evaluated and if


it is true then body of loop is executed. After execution of body the
condition is once again evaluated and if true body is is executed
once again. This goes on until test condition becomes false.

Example:

/* program for while */


#include<stdio.h>
main()
{
int count,n;
float x,y;
printf(“Enter the values of x and n”);
53
Computer Programming & Data Structures

scanf(“%f%d”,&x,&n);
y=1.0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf(“x=%f; n=%d; x to power n = %f”,x,n,y);
}

Do While Statement :

The while loop does not allow body to be executed if test condition
is false. The do while is an exit controlled loop and its body is
executed at least once.
Syntax:

do

statement-body;

}while(test condition);

Example:

/* printing multiplication table */


#include<stdio.h>
#define COL 10
#define ROW 12
main()
{
int row,col,y;
row=1;
do
{
col=1;
do
{
y=row*col;
printf(“%d”,y);
col=col+1;
}while(col<=COL);
printf(“\n”);
row=row+1;

54
Computer Programming & Data Structures

}while(row<=ROW);
}

For Loop :
It is also an entry control loop that provides a more concise
structure

Syntax:

for(initialization; test control; increment)


{
body of loop;
}

Example:

/* program of for loop */


#include<stdio.h>
main()
{
long int p;
int n;
double q;
printf(“2 to power n “);
p=1;
for(n=0;n<21;++n)
{
if(n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
printf(“%101d%10d”,p,n);
}
}

2.13.2 Other Statements Related to Looping

break statement:

This is a simple statement. It only makes sense if it occurs in the


body of a switch, do, while or for statement. When it is executed
the control of flow jumps to the statement immediately following
the body of the statement containing the break. Its use is

55
Computer Programming & Data Structures

widespread in switch statements, where it is more or less essential


to get the control .

The use of the break within loops is of dubious legitimacy. It


has its moments, but is really only justifiable when exceptional
circumstances have happened and the loop has to be abandoned. It
would be nice if more than one loop could be abandoned with a
single break but that isn't how it works. Here is an example.

Example:

#include <stdio.h>
#include <stdlib.h>
main(){
int i;

for(i = 0; i < 10000; i++){


if(getchar() == 's')
break;
printf("%d\n", i);
}
exit(EXIT_SUCCESS);
}

It reads a single character from the program's input before


printing the next in a sequence of numbers. If an ‘s’ is typed, the
break causes an exit from the loop.

If you want to exit from more than one level of loop, the
break is the wrong thing to use.

continue statement:

This statement has only a limited number of uses. The rules for
its use are the same as for break, with the exception that it doesn't
apply to switch statements. Executing a continue starts the next
iteration of the smallest enclosing do, while or for statement
immediately. The use of continue is largely restricted to the top of
loops, where a decision has to be made whether or not to execute
the rest of the body of the loop. In this example it ensures that
division by zero (which gives undefined behaviour) doesn't happen.

Example:

#include <stdio.h>
#include <stdlib.h>
56
Computer Programming & Data Structures

main()
{
int i;

for(i = -10; i < 10; i++){


if(i == 0)
continue;
printf("%f\n", 15.0/i);
/*
* Lots of other statements .....
*/
}
exit(EXIT_SUCCESS);
}

The continue can be used in other parts of a loop, too, where


it may occasionally help to simplify the logic of the code and
improve readability. continue has no special meaning to a switch
statement, where break does have. Inside a switch, continue is only
valid if there is a loop that encloses the switch, in which case the
next iteration of the loop will be started.

There is an important difference between loops written with


while and for. In a while, a continue will go immediately to the test
of the controlling expression. The same thing in a for will do two
things: first the update expression is evaluated, then the controlling
expression is evaluated.

goto and labels:

In C, it is used to escape from multiple nested loops, or to go to an


error handling exit at the end of a function. You will need a label
when you use a goto; this example shows both.

Syntax:
goto L1;
/* whatever you like here */
L1: /* anything else */

A label is an identifier followed by a colon. Labels have their


own ‘name space’ so they can't clash with the names of variables or
functions. The name space only exists for the function containing
the label, so label names can be re-used in different functions. The
label can be used before it is declared, too, simply by mentioning it
in a goto statement.

57
Computer Programming & Data Structures

Labels must be part of a full statement, even if it's an empty


one. These usually only matters when you're trying to put a label at
the end of a compound statement—like this.

label_at_end: ; /* empty statement */


}

The goto works in an obvious way, jumping to the labelled


statements. Because the name of the label is only visible inside its
own function, you can't jump from one function to another one.

It's hard to give rigid rules about the use of gotos but, as with
the do, continue and the break (except in switch statements), over-
use should be avoided. More than one goto every 3–5 functions is a
symptom that should be viewed with deep suspicion.

UNIT-II
3.0 INTRODUCTION

There are six derived types in C: arrays, functions, pointer,


structure, union and enumerated types. The function type is
derived from its return type.

Figure: 3.0 Derived Types

58
Computer Programming & Data Structures

3.1 DESIGNING STRUCTURED PROGRAMS

Whenever we are solving large programs first, we must understand


the problem as a whole, then we must break it in to simpler,
understandable parts. We call each of these parts of a program a
module and the process of sub dividing a problem into manageable
parts top-down design.

 The principles of top-don design and structured programming


dictate that a program should be divided into a main module
and its related modules.
 The division of modules proceeds until the module consists
only of elementary process that is intrinsically understood and
cannot be further subdivided. This process is known as
factoring.
 Top-down design is usually done using a visual representation
of the modules known as a structured chart.

Figure: 3.1 Structure Chart

3.2 FUNCTIONS IN C

A function is a self-contained block of code that carries out some


specific and well-defined task.

59
Computer Programming & Data Structures

C functions are classified into two categories

1. Library Functions

2. User Defined Functions

Library Functions

These are the built in functions available in standard library of C.The


standard C library is collection various types of functions which
perform some standard and predefined tasks.

Example: abs (a) function gives the absolute value of a, available in


<math.h> header file

pow (x, y) function computes x power y. available in


<math.h> header file

printf ()/scanf () performs I/O functions. Etc..,

User Defined Functions

These functions are written by the programmer to perform some


specific tasks.

Example: main (), sum (), fact () etc.

60
Computer Programming & Data Structures

The Major distinction between these two categories is that library


functions are not required to be written by us whereas a user
defined function has to be developed by the user at the time of
writing a program.

3.3 USER-DEFINED FUNCTIONS

The basic philosophy of function is divide and conquer by which a


complicated tasks are successively divided into simpler and more
manageable tasks which can be easily handled. A program can be
divided into smaller subprograms that can be developed and tested
successfully.

A function is a complete and independent program which is used (or


invoked) by the main program or other subprograms. A subprogram
receives values called arguments from a calling program, performs
calculations and returns the results to the calling program.

3.3.1 ADVANTAGES OF USER-DEFINED FUNCTIONS

1. Modular Programming It facilitates top down modular


programming. In this programming style, the high level logic
of the overall problem is solved first while the details of each
lower level functions is addressed later.
2. Reduction of source code The length of the source program
can be reduced by using functions at appropriate places. This
factor is critical with microcomputers where memory space is
limited.
3. Easier Debugging It is easy to locate and isolate a faulty
function for further investigation.
4. Code Reusability a program can be used to avoid rewriting
the same sequence of code at two or more locations in a
program. This is especially useful if the code involved is long
or complicated.
5. Function sharing Programming teams does a large
percentage of programming. If the program is divided into
61
Computer Programming & Data Structures

subprograms, each subprogram can be written by one or two


team members of the team rather than having the whole
team to work on the complex program

3.3.2 THE GENERAL FORM OF A C FUNCTION


Return_type function_name (argument declaration)

//local declarations

……

……

//statements

……

return-type

Specifies the type of value that a function returns using the return
statement. It can be any valid data type. If no data type is specified
the function is assumed to return an integer result.

function-name

Must follow same rules of variable names in C. No two functions


have the same name in a C program.

argument declaration

62
Computer Programming & Data Structures

Is a comma-separated list of variables that receive the values of the


argument when function is called. If there are no arguments
declaration the bracket consists of keyword void.

A C function name is used three times in a program

1. for function declaration

2. in a function call

3. for function definition.

3.3.3 FUNCTION DECLARATION (OR) PROTOTYPE

The ANSI C standard expands the concept of forward function


declaration. This expanded declaration is called a function
prototype.

A function prototype performs two special tasks.

1. First it identifies the return type of the function so that the


compile can generate the correct code for the return data.
2. Second, it specifies the type and number of arguments used
by the function.

The general form of the prototype is

63
Computer Programming & Data Structures

Figure: 3.3 Function Prototype

Note: The prototype normally goes near the top of the program and
must appear before any call is made to the function.

3.3.4 THE FUNCTION CALL

A function call is a postfix expression. The operand in a function is


the function name. The operator is the parameter lists (…), which
contain the actual parameters.

Example:

void main ()

sum (a, b);

When the compiler encounters the function call ,the control is


transferred to the function sum().The functions is executed line by
line and outputs the sum of the two numbers and returns to main
when the last statement in the following has executed and
conceptually, the function’s ending } is encountered.

3.3.5 FUNCTION DEFINITION

The function definition contains the code for a function. It is made


up of two parts: The function header and the function body, the
compound statement is must.

64
Computer Programming & Data Structures

Parameter names are required


here – they’ll be used in the
function body
Function header

return_type function_name (type1 name1, type2 name2,…namen)

{
Body of the
// local declarations
function
No
... appears in the
Semicol
// statements definition
on
...

 Function header consists of three parts: the return type, the


function name, and the formal parameter list.
 function body contains local declarations and function
statement.
 Variables can be declared inside function body.
 Function can not be defined inside another function.

3.2.6 CATEGORY OF USER -DEFINEDFUNCTIONS

A function, depending on whether arguments are present or not and


whether a value is returned or not, may belong to one of the
following categories:

Category 1: Functions with no arguments and no return values

Category 2: Functions with no arguments and return values

Category 3: Functions with arguments and no return values

65
Computer Programming & Data Structures

Category 4: Functions with arguments and return values

3.2.6.1 FUNCTIONS WITH NO ARGUMENTS AND NO RETURN


VALUES

This type of function has no arguments, meaning that it does not


receive any data from the calling function.Simillary this type of
function will not return any value. Here the calling function does not
receive any data from the called function. In effect, there is no data
transfer between the calling function and the called function.

Figure: 3.5 Functions with no arguments and no return values

Observe from the figure 3.5 that the function greeting () do not
receive any values from the function main () and it does not return
any value to the function main ().Observe the transfer of control
between the functions indicated with arrows.

//C program to find sum of two numbers using functions


with no arguments and no return values

66
Computer Programming & Data Structures

#include<stdio.h>

void sum ();

void main ()

clrscr ();

sum (); /*calling function */

getch ();

void sum ()

3.2.6.2
{ FUNCTIONS WITH NO ARGUMENTS AND RETURN
VALUES

There are two ways that a function terminates execution and


returns to the caller.

1. When the last statement in the function has executed and


conceptually the function’s ending ‘}’ is encountered.

2. Whenever it faces return statement.

THE RETURN STATEMENT

 The return statement is the mechanism for returning a value


from the called function to its caller.
 The general form of the return statement is

return expression;

 The calling function is free to ignore the returned value.


Further more, there need not be expression after the return.
 In any case if a function fails to return a value, its value is
certain to be garbage.

67
Computer Programming & Data Structures

 The return statement has two important uses


1. It causes an immediate exit of the control from the
function. That is ,it causes program execution to return
to the calling function.

2. It returns the value present in the expression.

example: return(x+y);

return (6*8);

return (3);

return;

Figure 3.6 Functions with no arguments and return values

In this category, there is no data transfer from the calling function


to the called function. But, there is data transfer from called
function to the calling function.

In the above example, observe from the figure 3.6 that the function
getQuantity () do not receive any value from the function main
().But, it accepts data from the keyboard, and returns the value to
the calling function.

// C program to find sum of two numbers using functions


with no arguments and return values

68
Computer Programming & Data Structures

#include<stdio.h>

int sum ();

void main ()

int c;

clrscr ();

c=sum (); /*calling function */

printf (“\n The sum = %d”, c);

RETURNING
getch (); VALUES FROM MAIN ()

int sumwe
When () use a return statement in main (), some program returns
a termination code to the calling process (usually to the O.S).The
return values must be an integer.

For many Operating Systems, a return value of ‘0’ indicates that the
program terminated normally. All other values indicate that some
error occurred. For this reason, it is good practice to use an explicit
return statement.

3.2.6.3 FUNCTIONS WITH ARGUMENTS AND NO RETURN


VALUES

In this category there is data transfer from the calling function to


the called function using parameters. But, there is no data transfer
from called function to the calling function.

Local Variables

variables that are defined within a function are called local


variables.A local variable comes into existence when the function is
entered and is destroyed upon exit.

69
Computer Programming & Data Structures

Function arguments

The arguments that are supplied in to two categories

1. actual arguments/parameters

2. formal arguments/parameters

Actual arguments/parameters

Actual parameters are the expressions in the calling functions.


These are the parameters present in the calling statement (function
call).

formal arguments/parameters

formal parameters are the variables that are declared in the header
of the function definition. These list defines and declares that will
contain the data received by the function. These are the value
parameters, copies of the values being passed are stored in the
called functions memory area.

Note: Actual and Formal parameters must match exactly in type,


order, and number. Their names however, do not need to match.

70
Computer Programming & Data Structures

Figure 3.7 Functions with arguments and no return values

Observe from the figure 3.7 that the function printOne () receives
one value from the function main (), display the value copy of a.

//C program to find sum of two numbers using functions


with arguments and no return values

#include<stdio.h>

void sum (int ,int );

void main ()

int a, b;

clrscr ();

printf (“\n Enter the values of a and b: “);

scanf (“%d%d”, &a, &b);

sum (a, b); /*calling function */


71
getch ();
Computer Programming & Data Structures

Passing Parameters to Functions

There are two ways of passing parameters to the functions.

1. call by value

2. call by reference

call by value

When a function
// C program illustrates is
callcalled
by value with actual parameters, the values of
actual parameters are copied into the formal parameters. If the
#include<stdio.h>
values of the formal parameters changes in the function, the values
ofvoidthe
swapactual
(int , int parameters
); are not changed. This way of passing
parameters is called call by value (pass by value).
void main ()
In the below example, the values of the arguments to swap () 10
{
and 20 are copied into the parameters x and y.Note that the values
of int
x and
a, b; y are swaped in the function. But, the values of actual
parameters remain same before swap and after swap.
clrscr ();

printf (“\n Enter the values of a and b: “);

scanf (“%d%d”, &a, &b);

swap (a, b); /*calling function */

printf (“\nFrom main The Values of a and b a=%d, b=%d “, a, b);


72
getch ();

void swap (int x, int y)


Computer Programming & Data Structures

Note: In call by value any changes done on the formal parameter


will not affect the actual parameters.

 call by reference will be discussed in UNIT IV.

3.2.6.4. FUNCTIONS WITH ARGUMENTS AND RETURN


VALUES

In this category there is data transfer between the calling function


and called function.

73
Computer Programming & Data Structures

Figure 3.8 Functions with arguments and return values

Observe from the above figure 3.8 t the function sqrt receive one
value from the function main (), finds the square of the number and
sends the result back to the calling function.

//C program to find sum of two numbers using functions


with arguments and return values

#include<stdio.h>

int sum (int ,int );

void main ()

int a, b;

clrscr ();

printf (“\n Enter the values of a and b: “);

scanf (“%d%d”, &a, &b);

c=sum (a, b); /*calling function */ 74

printf (“\n The Sum =%d”, c);

getch ();
Computer Programming & Data Structures

Note: generally we are using functions with arguments and return


values (category 4) in our applications. Why because the job of a
function is to perform a well-defined task, it carrys inputs and sends
result after executed. In real world the programming teams codes
the modules (functions) according to the input (arguments) given
by the team coordinators.

3.3 STANDARD LIBRARY FUNCTIONS

C has a large set of built-in functions that perform various tasks. In


order to use these functions their prototype declarations must be
included in our program.

75
Computer Programming & Data Structures

Figure 3.9 Library Functions and the Linker

The above figure shows how two of the C standard functions that
we have used several times are brought into out program. The
include statement causes the library header file for standard input
and output(stdio.h) to be copied in to our program It contains the
declaration for printf and scanf.Then,when the program is linked,
the object code for these functions is combined with our code to
build the complete program.

Some of the header files includes these functions are

<stdio.h> Standard I/O functions

<stdlib.h> Utility functions such as string coversion routines,


memory allocation routines, etc..,

<string.h> String manipulation functions

<math.h> Mathematical functions

76
Computer Programming & Data Structures

<ctype.h> Character testing and conversion functions

3.4 NESTING OF FUNCTIONS

C permits nesting of functions, main can call function1, which calls


function2, which calls function3 .., There is no limit as how deeply
functions can be b=nested .

consider the following example:

#include<stdio.h>

int read ();

int sum (int, in t);

void main ()

int a, b;

printf (“%d”, sum ());

int sum (int x, int y)

x=read ();

y=read ();

return x+y;

}
Inintthe
read above
() example ,when the main() function executes it finds
the function call sum(), then the control is transferred from main()
to{ the function sum(),here we are calling the function read(), then
the control transferred to read() function,then the body of the
int p;
function read() executes,the control transfered from read to sum()
printf (“\n Enter any value: “);
77
Scanf (“%d”, &p);

return p;

}
Computer Programming & Data Structures

and once again the same is done for rading some other value. Then
the addition is performed this value is carried from sum() to
main().Observe the chain of control transfers between the nested
functions.

3.5 RECURSION IN C

In C, functions can call themselves .A function is recursive if a


statement of the function calls the function that contains it. This
process is some times called circular definition.

Recursion is a repetive process, where the function calls itself.

Example: Recursive factorial function

Iteration definition

fact (n) =1 if n=0

=n*(n-1)*(n-2)…….3*2*1 if n>0

Recursion definition

BASE CASE
fact (n) =1 if n=0

GENERAL CASE
=n*fact (n-1) if n>0

78
Computer Programming & Data Structures

//C program to find the factorial using recursion

#include <stdio.h>

long factorial (long);



void main (void)
Output:
{

int i;
4! = 24
i=4;

printf (“%2d! = %1d\n”, i, factorial (i));

long factorial (long number)

if (number ==0)

return 1;

else

return (number * factorial (number-1));

79
Computer Programming & Data Structures

Difference between Iteration and Recursion

ITERATION RECURSION

Iteration explicitly uses Recursion achieves repetition by


repetition structure. calling the same function
repeatedly.

Iteration is terminated Recursion is terminated when base


when the loop condition case is satisfied.
fails

May have infinite loop if Recursion is infinite if there is no


the loop condition never base case or if base case never
fails reaches.

Iterative functions execute Recursive functions are slow and


much faster and occupy takes a lot of memory space
less memory space. compared to iterative functions

Table 3.1 Difference between Iteration and Recursion

3.6 PREPROCESSOR COMMANDS

The C compiler is made of two functional parts: a preprocessor and


a translator. The preprocessor is a program which processes the
source code before it passes through the compiler. The translator
converts the C statements into machine code that in places in an
object module. Compilation

Source Preproc-essor Translation Transl- Object


Program unit 80 code
ator
Computer Programming & Data Structures

Figure 3.11 Compilation Components

The preprocessor is a collection of special statements called


commands or preprocessor directives. Each directive is examined by
the preprocessor before the source program passes through the
compiler.

 Statements beginning with # are considered preprocessor


directives.
 Preprocessor directives indicate certain things to be done to
the program code prior to compilation.
 It includes certain other files when compiling, replace some
code by other code.
 Only white space characters before directives on a line.
 Preprocessor commands can be placed anywhere in the
program.

There are three major tasks of a preprocessor directive

1. Inclusion of other files (file inclusion)


2. Definition of symbolic constants and macros(macro
definition)
3. Conditional compilation of program code/Conditional
execution of preprocessor directives

3.6.1 FILE INCLUSION

The first job of a preprocessor is file inclusion ,the copying of one or


more files into programs. The files are usually header files and
external files containing functions and data declarations.

81
Computer Programming & Data Structures

General form is, #include filename

It has two different forms

1. #include <filename>

 It is used to direct the preprocessor to include header files


from the system library.
 In this format, the name of the header file is enclosed in
pointed brackets.(< and >)
 Searches standard library only for inclusion of a file.

Example: #include<stdio.h>

In the above example ,the preprocessor directive statements


searches for content of entire code of the header file stdio.h in the
standard library ,if it finds there includes the contents of the entire
code at the place where the statement is in the source program
before the source program passes through the compiler.

Note: here we can’t include user files why because it searches for
the files in the standard library only.

2. #include “filename”

 it is used to direct the preprocessor look for the files in the


current working directory, standard library
82
Computer Programming & Data Structures

 Use for inclusion of user-defined files, also includes standard


library files.
 Searches current directory, then standard library for the
inclusion of a file.
 In this format, the name of the file is enclosed in double
quotes.
 We can also include macros. The included file or the program
either may contain main() function but not the both.

Example: #include “header.h”

In the above example, the preprocessor directive statement directs


the preprocessor to include content of entire code of the file
header.h which is in the current directory at the place where the
statement is in the source program before the source program
passes through the compiler.

note: We can also include file that is not present in the current
directory by specifying the complete path of the file like

#include “e:\muc.h”

//C Program illustrates file inclusion

83
Computer Programming & Data Structures

In the above example the file mac.h is stored in E: Drive of the


computer. After finding the include command by the preprocessor
the contents of the file are copied in to the program then send for
the compilation.

3.6.2 MACRO DEFINITION

A macro definition command associates a name with a sequence of


tokens. The name is called the macro name and the tokens are
referred to as the macro body.

The following syntax is used to define a macro:

#define macro_name(<arg_list>) macro_body

84
Computer Programming & Data Structures

#define is a define directive, macro_name is a valid C


identifier.macro_body is used to specify how the name is replaced
in the program before it is compiled.

 Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )

would cause area = CIRCLE_AREA( 4 );

to become area = ( 3.14159 * ( 4 ) * ( 4 ) );

 Use parenthesis for coding macro_body,Without them the


macro

#define CIRCLE_AREA( x ) PI * ( x ) * ( x )

would cause area = CIRCLE_AREA( c + 2 );

to become area = 3.14159 * c + 2 * c + 2;

 We can also supply Multiple arguments like

#define RECTANGLE_AREA( x, y ) ( ( x ) *
(y))

would cause rectArea = RECTANGLE_AREA( a + 4, b + 7 );

to become rectArea = ( ( a + 4 ) * ( b + 7 ) );

85
Computer Programming & Data Structures

 macro must be coded on a single line. we can use


backslash(\) followed immediately by a new line to code
macro in multiple lines.
 Performs a text substitution – no data type checking. W need
to carefully code the macro body .Whenever a macro call is
encounter, the preprocessor replaces the call with the macro
body. If body is not created carefully it may create an error or
undesired result.

For example the macro definition

#define Mac =0

…..

…..

a=Mac;

….

will result in

num==0;

This is unwanted.

//C program illustrating usage of Macro

#include<stdio.h>

#define square(x) (x*x)

int main()

int a=10;

printf("\nThe square of %d=%d",a,square(a));

86
Computer Programming & Data Structures

Symbolic Constants

Macro definition without arguments is referred as a constant. The


body of the macro definition can be any constant value including
integer, float, double, character, or string.However, character
constants must be enclosed in single quotes and string constants in
double quotes.

Example #define PI 3.14159

Here “PI” replaces with "3.14159"

Nested Macros

It is possible to nest macros. C handles nested macros by simply


rescanning a line after macro expansion.Therefore,if an expansion
results in a new statement with a macro ,the second macro will be
properly expanded.

For example,
87
Computer Programming & Data Structures

#define sqre(a) (a*a)

#define cube(a) (sqre(a)*a)

The expansion of x=cube(4);

results in the following expansion: x=(sqre(4)*4);

this after rescanning becomes x=((4*4)*4);

Undefining Macros

Once defined, a macro command cannot be redefined. Any attempt


to redefine it will result in a compilation error. However, it is
possible to redefine a macro by first undefining it, using the #undef
command and the defining it again.

Example

#define Val 30

#undef Val

#define val 50

Predefined Macros

88
Computer Programming & Data Structures

C language provides several predefined macros .these macros


cannot be undefined using the undef command. Some of the
predefined macros are

Command Meaning

__DATE__ Provides a string constant in the form “mm dd


yyyy” containing the date of translation.

Provides a string constant containing the name of


__FILE__
the source file.

Provides a string constant in the form “hh:mm:ss”


__TIME__ containing the time of the translation.

Provides an integer constant containing the


current statement number in the source file.
__LINE__

Table 3.2 List of Predefined Macros in C

//C program Demonstrating Predefined macros

89
Computer Programming & Data Structures

String Converting Operator(#)

It is a macro operation Causes a replacement text token to be


converted to a string surrounded by quotes.

The statement #define HELLO( x ) printf( “Hello, ” #x “\n” );

would cause HELLO( John )

to become printf( “Hello, ” “John” “\n” );

Strings separated by whitespace are concatenated when using printf


statement.

The Defined Operator

90
Computer Programming & Data Structures

The defined operator can be used only in a conditional compilation .


It can be used in macros. The value of defined(macro-name) is o if
the name is not defined and 1 if it is defined.

For example, after #define val 24

the value of defined(val) is 1 and

the value of !defined(val) is 0.

3.6.3 CONDITIONAL COMPILATION

 It allows us to control the compilation process by including or


excluding statements.
 Cast expressions, size of, enumeration constants cannot be
evaluated in preprocessor directives.
 Its structure similar to if statement.

 Syntax

#if expression1

code to be included for true

#elif expression2

code to be included for true

#else

code to be included false

#endif

91
Computer Programming & Data Structures

 Example: #if !defined( NULL )


#define NULL 0

#endif

 Determines if symbolic constant NULL has been defined If


NULL is defined, defined( NULL ) evaluates to 1,If NULL is not
defined, and this function defines NULL to be 0.
 Every #if must end with #endif.
 #ifdef short for #if defined( name ).
 #ifndef short for #if !defined( name ).

Command Meaning

#if expression When expression is true, the code that


follows is included for compilation.

Terminates the conditional command.


#endif

Specifies alternate code in two-way


#else
decision.

#elif
Specifies alternate code in multi-way
decision.

#ifdef name
Tests for the macro definition.

#ifndef name
Tests whether macro is not defined .

92
Computer Programming & Data Structures

Table 3.3 Conditional Compilation Commands

3.7 STORAGE CLASSES

'Storage' refers to the scope of a variable and memory allocated by


compiler to store that variable. Scope of a variable is the boundary
within which a variable can be used. Storage class defines the the
scope and lifetime of a variable.

From the point view of C compiler, a variable name identifies


physical location from a computer where variable is stored. There
are two memory locations in a computer system where variables
are stored as: Memory and CPU Registers.

Functions of storage class:

 To determine the location of a variable where it is stored?


 Set initial value of a variable or if not specified then setting it
to default value.
 Defining scope of a variable.
 To determine the life of a variable.

Types of Storage Classes:

Storage classes are categorized in 4 (four) types as,

 Automatic Storage Class


 Register Storage Class

 Static Storage Class

 External Storage Class

Automatic Storage Class:


o Keyword : auto
o Storage Location : Main memory

o Initial Value : Garbage Value

93
Computer Programming & Data Structures

o Life: Control remains in a block where it is defined.

o Scope: Local to the block in which variable is declared.

Syntax:

auto [data_type] [variable_name];

Example:

auto int a;

Program:

/* Program to demonstrate automatic storage class.*/

#include <stdio.h>
#include <conio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}

Output :
20

10

Register Storage Class :


o Keyword : register
o Storage Location : CPU Register

o Initial Value : Garbage

o Life : Local to the block in which variable is declared.

o Scope : Local to the block.

Syntax: register [data_type] [variable_name];

94
Computer Programming & Data Structures

Example: register int a;

When the calculations are done in CPU, then the value of variables
are transferred from main memory to CPU. Calculations are done
and the final result is sent back to main memory. This leads to
slowing down of processes.

Register variables occur in CPU and value of that register variable is


stored in a register within that CPU. Thus, it increases the resultant
speed of operations. There is no waste of time, getting variables
from memory and sending it to back again.

It is not applicable for arrays, structures or pointers.

It cannot not used with static or external storage class.

Unary and address of (&) cannot be used with these variables as


explicitly or implicitly.

Program:
/* Program to demonstrate register storage class*/

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

void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}

Output: 20

10

Static Storage Class:


o Keyword : static
o Storage Location : Main memory

o Initial Value : Zero and can be initialize once only.

95
Computer Programming & Data Structures

o Life : depends on function calls and the whole application or


program.

o Scope : Local to the block.

Syntax: static [data_type] [variable_name];

Example: static int a;

There are two types of static variables as :

a) Local Static Variable


b) Global Static Variable

Static storage class can be used only if we want the value of a


variable to persist between different function calls.

Program:
/* Program to demonstrate static storage class.*/

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

void main()
{
int i;
void incre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}

void incre(void)
{
int avar=1;
static int svar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}

Output:
Automatic variable value : 2 Static variable value : 2
96
Computer Programming & Data Structures

Automatic variable value : 2 Static variable value : 3

Automatic variable value : 2 Static variable value : 4

External Storage Class:


o Keyword : extern
o Storage Location : Main memory

o Initial Value : Zero

o Life: Until the program ends.

o Scope: Global to the program.

Syntax: extern [data_type] [variable_name];

Example: extern int a;

The variable access time is very fast as compared to other storage


classes. But few registers are available for user programs.

The variables of this class can be referred to as 'global or external


variables.' They are declared outside the functions and can be
invoked at anywhere in a program.

Program:
/* Program to demonstrate external storage class.*/

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

extern int i=10;


void main()
{
int i=20;
void show(void);
clrscr();
printf("\n\t %d",i);
show();
getch();
}
void show(void)
{

97
Computer Programming & Data Structures

printf("\n\n\t %d",i);
}

Output: 20

10

3.8 ARRAYS IN C

3.8.1 INTRODUCTION

 Often we need many different variables that are of the same


type and play a similar role in the program
 For example, suppose we have a temperature reading for
each day of the year and need to manipulate these values
several times within a program.
 With simple variables,
o We would need to declare 365 variables.
o We would not be able to loop over these variables.
 An array is a numbered collection of variables of the same
type.
 An array is a homogeneous collection of data.
 The variables in an array share the same name and are
distinguished from one another by their numbers or
subscripts.
 We can loop through the variables of an array by using a
variable for the subscript.
 The subscripts are always 0,1,…, size-1

3.8.2 ARRAY CHARACTERISTICS

98
Computer Programming & Data Structures

 An array represents a group of related data.


 An array has two distinct characteristics:

An array is ordered: data is grouped sequentially. In other


words, here is element 0, element 1, etc.

An array is homogenous: every value within the array


must share the same data type. In other words, an int array
can only hold ints, not doubles.

3.8.3 HOW TO CREATE AN ARRAY

 Before we create an array, we need to decide on two


properties:

Element type: what kind of data will your array hold? ints,
double, chars? Remember, we can only choose one type.

Array size: how many elements will your array contain?

When we initially write our program, we must pick an array size. An


array will stay this size throughout the execution of the program. In
other words, we can change the size of an array at compile time,
but cannot change it at run-time.

3.8.4 USING ARRAYS IN C

In C, the arrays can be classified based on how the data items are
arranged for human understanding

99
Computer Programming & Data Structures

Arrays are broadly classified into three categories,

1. One dimensional arrays

2. Two dimensional arrays

3. Multi dimensional arrays

3.8.5 ONE DIMENSIONAL ARRAYS

One dimensional array is a linear list consisting of related and


similar data items. In memory all the data items are stored in
contiguous memory locations one after the other.

3.8.5.1 DECLARING ONE DIMENSIONAL ARRAYS

 To declare regular variables we just specify a data type and a


unique name:

int number;

 To declare an array, we just add an array size.

 For example:

int temp[5];

Creates an array of 5 integer elements.

100
Computer Programming & Data Structures

 For example:

double stockprice[31];

creates an array of 31 doubles.

Syntax for Declaring one dimensional Arrays

elementType arrayName [size];

Where :

elementType: specifies data type of each element in the array.

arrayName: specifies name of the variable you are declaring.

size: specifies number of elements allocated for this array.

3.8.5.2 INITIALIZING ONE DIMENSIONAL ARRAYS

 We have four options for initializing one dimensional arrays.


 But, first, REMEMBER THIS: Just like regular variables, arrays
that have not been initialized may contain “garbage values.”
 But, now, the stakes are even higher. If you declare an array
with 31 elements, and forget to initialize it, you end up with
31 garbage values!

101
Computer Programming & Data Structures

Option 1 Initializing all memory locations

If you know all the data at compile time, you can specify all your
data within brackets:

int temp [5] = {75, 79, 82, 70, 68};

during compilation, 5 contiguous memory locations are reserved by


the compiler for the variable temp and all these locations are
initialized as shown in Fig.3.14.

If the size of integer is 2 bytes, 10 bytes will be allocated for the


variable temp.

temp[0] temp[1] temp[2] temp[3] temp [4]

1000 1002 1004 1006 1008 Address

Figure: 3.14 Storage Representation of array

Option 2 initialization without size

If we omit the size of your array, but specify an initial set of data,
the compiler will automatically determine the size of your array.
This way is referred as initialization without size.

int temp [] = {75, 79, 82, 70, 68};

102
Computer Programming & Data Structures

In this declaration, even though we have not specified exact


number of elements to be used in array temp, the array size will be
set of the total number of initial values specified. Here, the compiler
creates an array of 5 elements. The array temp is initialized as
shown in Figure 3.15.

temp[0] temp[1]temp[2] temp[3] temp[4]

1000 1002 1004 1006 1008 Address

Figure: 3.15 Storage Representation of array

Option 3 Partial Array Initialization

If the number of values to be initialized is less than the size of the


array, then the elements are initialized in the order from 0 th
location. The remaining locations will be initialized to zero
automatically.

int temp [5] = {75, 79, 82};

Even though compiler allocates 5 memory locations, using this


declaration statement, the compiler initializes first three locations
with 75,70 and 82,the next set of memory locations are
automatically initialized to 0’s by the compiler as shown in figure
3.16

temp[0]temp[1] temp[2]temp[3]temp[4]

103
Computer Programming & Data Structures

1000 1002 1004 1006 1008 Address

Figure: 3.16 Storage Representation of array

Option 4

If you do not know any data ahead of time, but you want to
initialize everything to 0, just use 0 within { }.

For example:

int temp [5] = {0};

This will initialize every element within the array to 0 as shown in


below figure 3.17.

temp[0] temp[1] temp[2] temp[3] temp [4]

1000 1002 1004 1006 1008 Address

Figure 3.17

If at least one element is assigned then only one element is


assigned with the value and all the remaining elements of the array
will be zero.

104
Computer Programming & Data Structures

For example:

int temp [5] = {5};

temp[0] temp[1] temp[2] temp[3] temp [4]

1000 1002 1004 1006 1008 Address

Figure 3.18

The first value is supplied in the first element memory location,


remaining all elements are placed with zero.

3.8.5.3 REFERENCING/ACCESSING ONE DIMENSIONAL


ARRAY ELEMENTS

 Suppose we have an array, temperature, for the temperature


readings for the year.
 The subscripts would be 0,1,…,364.
 To refer to the reading for a given day, we use the name of
the array with the subscript in brackets: temperature [4] for
the fifth day.

105
Computer Programming & Data Structures

Figure 3.19

 To assign the value 89 for the 150th day:

temperature [149] = 89;

 We can loop through the elements of an array by varying the


subscript. To set all of the values to 0, say

for(i=0;i<365;i++)
temperature[i] = 0;

 We can not use assignmet statement directly with arrays.


if a[] , b[] are two arrays then the assignment a=b is not
valid .
// C program to read an array elements and find the sum of
the elements.

#include <stdio.h>

void main()

int a[10];

int i, SIZE, total=0;

printf(“\n Enter the size of the array : “);

scanf(“%d”,&size);

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

scanf(“%d”,&a[i]);

 C does not provide array bounds checking.


 Hence, if we have

double stockPrice[5];

printf ("%d", stockPrice[10]);

106
Computer Programming & Data Structures

 This will compile, but you have overstepped the bounds of


your array. You may therefore be accessing another
variable in your program or another application.

3.8.5. TWO DIMENSIONAL ARRAYS

An array of arrays is called a two-dimensional array and can be


regarded as a table with a number of rows and columns:

'J' 'o' 'h' 'n' 'J' 'o' 'h' 'n'


is a 3  4 array:
'M' 'a' 'r' 'y' 'M' 'a' 'r' 'y'
'I' 'v' 'a' 'n' 3 rows, 4 columns 'I' 'v' 'a' 'n'

This is an array of size 3 names [3] whose elements are arrays of


size 4 [4] whose elements are characters char

3.8.5.1 DECLARATION OF TWO DIMENSIONAL ARRAY

elementType arrayName [rows][cols];

107
Computer Programming & Data Structures

Figure:3. Two-dimensional Array representation

The above figure shows the representation of elements in the two-


dimensional array

Example,

char names[3][4];

in the above declaration

char(elementType)  specifies type of element in each slot

names(arrayName)  specifies name of the array

[3](rows)  specifies number of rows

[4](cols)  specifies number of columns

3.8.5.2 INITIALIZATION OF TWO DIMENSIONAL ARRAYS

 An array may be initialized at the time of declaration:

char names [3][4] = {

{‘J’, 'o', 'h', 'n'},

{‘M’, 'a', 'r', 'y'},

{‘I’, 'v', 'a', 'n'}

};

 An integer array may be initialized to all zeros as follows

108
Computer Programming & Data Structures

int nums [3][4] = {0};

 In the declaration of two dimensional array the column size


should be specifed, to that it can arrange the elements in the
form of rows and columns.
 Two-dimensional arrays in C are stored in "row-major
format": the array is laid out contiguously, one row at a time:
 To access an element of a 2D array, you need to specify both
the row and the column:
nums[0][0] = 16;

printf ("%d", nums[1][2]);

//C Program to read and print the elements of the two


dimensional array.

/* Fill 2-d array, print out values, sum the array. */

#include <stdio.h>

#define M 3 /* Number of rows */

#define N 4 /* Number of columns */

int main(void)

int a [ M ] [ N ], i, j, sum = 0;

for ( i = 0; i < M; ++i ) /* fill the array */

for (j = 0; j < N, ++j )

scanf (%d”, &a [i] [j]);

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

{ /* print array values */

for (j = 0; j < N, ++j )

printf(“a [ %d ] [ %d ] = %d “, i, j, a[ i ] [ j ]);

printf (“\n”);
109
}
Computer Programming & Data Structures

8.6 MULTI DIMENSIONAL ARRAYS

 C allows three or more dimensions. The exact limit is


determined by the compile.
 The general form of multidimensional array is

type arrayName[s1][s2][s3]….[sm];

Where si is the size of the ith dimension.

 Array declarations read right-to-left


 For example

int a[10][3][2];

 it is represented as “an array of ten arrays of three arrays of


two ints”
 In memory the elements are stored as shown in below figure

110
Computer Programming & Data Structures

3.8.7 FUNCTIONS WITH ARRAYS

Like the values of variable, it is also possible to pass values of an


array to a function. To pass an array to a called function, it is
sufficient to list the name of the array, without any subscripts, and
the size of the array as arguments.

for example, the call

findMax(a,n);

will pass all the elements contained in the array a of size n.The
called function expecting this must be appropriately defined.

The findMax function header looks like:

int findMax(int x[],int size);

The pair of brackets informs the compiler that the argument x is an


array of numbers. It is not necessary to specify the size of the array
here.

The function prototype takes of the form

int findMax (int [], int );

int findMax (int a [], int );

111
Computer Programming & Data Structures

// C program to find Maximum value in a given list int findMax(int x[],int size)

#include<stdio.h> {

int findMax(int[],int ); int temp;

void main() temp=x[0];

{ for(i=1;i<size; i++)

int a[10], n ,i , max; {

printf(“\n Enter the size of the array “); if(x[i]>temp)

scanf(“%d”,&n); {

printf(‘\n Enter the elements of the array : “); temp=x[i];

Note: The same thing is applied for passing a multidimensional


array to a function. Here we need to specify the column size, for
example to read two-dimensional array elements using functions it
takes of the form

int readElements (int [] [5], int ,int );

UNIT-III
4.0 INTRODUCTION POINTERS
112
Computer Programming & Data Structures

Pointers are one of the derived types in C. One of the powerful tool
and easy to use once they are mastered.

Some of the advantages of pointers are listed below:

 A pointer enables us to access a variable that is defined


outside the function.
 Pointers are more efficient in handling the data tables.
 Pointers reduce the length and complexity of a program.
 The use of a pointer array to character strings save data
storage space in memory.

The real power of C lies in the proper use of pointers.

4.1 POINTER CONCEPTS

The basic data types in C are int, float, char double and void.
Pointer is a special data type which is derived from these basic data
types.

There are three concepts associated with the pointers are,

 Pointer Constants
 Pointer Values
 Pointer Variables

4.1.1 POINTER CONSTANT

 As we know, computers use their memory for storing the


instructions of a program, as well as the values of the
variables that are associated with it.

113
Computer Programming & Data Structures

 The computer’s memory is a sequential collection of ‘storage


cells’.
 Each cell can hold one byte of information, has a unique
number associated with it called as ‘address’.
 The computer addresses are numbered consecutively, starting
from zero. The last address depends on the memory size.
 Let us assume the size of the memory is 64K then,

The total memory locations = 64K

= 64 * 1K

= 64 * 1024 bytes

= 65536 bytes (locations)

 So, here the last address is 65535(started with 0).


 Physically they are divided into even bank and odd bank.
 Even bank is set of memory locations with even addresses.
Like 0, 2, 4, 6……65534.
 Odd bank is set of memory locations with odd addresses.
Like 1, 3, 5 ….65535.

Address Memory Locations Address

114
Computer Programming & Data Structures

0 1

2 3

4 5

.. ..

.. ..

32278 32279

.. ..

65530 65531

65532

65534 65535

even bank odd bank

Figure: 4.1 Memory Organization.

 These memory addresses are called pointer constants.


 We cannot change them, but we can only use them to store
data values.

115
Computer Programming & Data Structures

 For example, in the above memory organization, the


addresses ranging from 0 to 65535 are known as pointer
constants.
 Remember one thing, the address of a memory location is a
pointer constant and cannot be changed .

4.1.2 POINTER VALUE

Whenever we declare a variable, the system allocates , an


appropriate location to hold the value of the variable somewhere in
the memory,.

Consider the following declaration,

int i=10;

This declaration tells the C compiler to perform the following


activities:

 Reserve space in the memory to hold the integer value.


 Associate the name i with this memory location.
 Store the value 10 at this location.

We can represent i’s location in the memory by the following


memory map:

i Variable Name

10 Variable value

65510 Variable address

Pointer Values

 Memory is divided into number of storage cells called


locations.
116
Computer Programming & Data Structures

 Out of these the addresses, the system assigns some


addresses of the memory locations to the variables.
 These memory locations assigned to the variables by the
system are called pointer values.
 For example, the address 65510 which is assigned to the
variable i is a pointer value.

The & Operator

 The address of the variable cannot be accessed directly. The


address can be obtained by using address operator(&) in C
language.
 The address operator can be used with any variable that can
be placed on the left side of an assignment operator.
 The format specifier of address is %u(unsigned integer),the
reason is addresses are always positive values. We can also
use %x to know the address of a variable.
 Example, to know the address of variable n, just use &n.
Note: Constants, expressions, and array name cannot be placed on
the left side of the assignment and hence accessing address is
invalid for constants, array names and expressions.

The following are illegal use of address Operator.

&125 (Pointing at constant)

int a[10];

&a (pointing to array name)

&(x+y) (pointing at expressions)

4.1.3 POINTER VARIABLE

 A variable Which holds the address of some other variable is


called pointer variable.

117
Computer Programming & Data Structures

 A pointer variable should contain always the address only.

The * Operator

 It is called as ‘Value at address’ operator. It returns the


value stored at a particular address.
 It is also Known as Indirection or Dereferencing Operator

4.2 ACCESSING A VARIABLE THROUGH POINTER

For accessing the variables through pointers, the following sequence


of operations have to be performed, to use pointers.

1. Declare an ordinary variable.


2. Declare a pointer variable.
3. Initialize a pointer variable(Provide link between pointer
variable and ordinary variable).
4. Access the value of a variable using pointer variable.

We already familiar with the declaration and initialization of


variable. Now we will discuss the remaining here.

Declaring a pointer variable

In C , every variable must be declared before they are used. Since


the pointer variables contain address that belongs to a separate
data type, they must be declared as pointers before we use them.
118
Computer Programming & Data Structures

The syntax for declaring a pointer variable is as follows,

data type *ptr_name;

This tells the compiler three things about the variable ptr_name.

1. The asterisk(*) tells that the variable ptr_name is a pointer


variable.
2. ptr_name needs a memory location.
3. ptr_name points to a variable of type data type.
For example,

int *pi;

declares the variable p as a pointer variable that points to an


integer data type. Remember that the type int refers to the data
type of the variable being pointed by pi.

Initializing Pointers

 Once a pointer variable has been declared, it can be made to


point to a variable using statement such as

ptr_name=&var;

119
Computer Programming & Data Structures

 Which cause ptr_name to point to var.Now ptr_name


contains the address of var. This is known as pointer
initialization.
 Before a pointer is initialized it should not be used.
Access the value of a variable using pointer variable

Once a pointer variable has been assigned the address of a variable,


we can access the value of a variable using the pointer. This is done
by using the indirection operator(*).

*ptr_name

Example1

120
Computer Programming & Data Structures

121
Computer Programming & Data Structures

The above program illustrates how to access the variable using


pointers. After finding the first statement i=10 ,the compiler creates
a variable i with a value of 10 at a memory location. Then coming to
line 2 and 3 a pointer variable pi is create and initialized with the
address of the i variable. then the compiler automatically provides a
link between these two variables as follows.

i pi

10 8342

8342 8338

Note: Pointer variable always points to a address of the another


variable .Following statements are not valid with respect to
pointers.

int i=10, k, *pi=&i;

k=pi; // pointer value cannot be accessed by integer

pi=65506(constant); // we cannot directly assign a value to a


pointer variable

Example2

122
Computer Programming & Data Structures

The following code illustrates how to declare int ,char and float
pointers. Here we have declared three variables of type int, float
and char ,also three pointer variables points to int, float and char.
Remember here pf points to the value of type float but its type is
unsigned integer only.

123
Computer Programming & Data Structures

124
Computer Programming & Data Structures

Declaration versus Redirection:

 When an asterisk is used for declaration, it is associated with


a type.

 Example:

int* pa;

int* pb;

 On the other hand, we also use the asterisk for redirection.


When used for redirection, the asterisk is an operator that
redirects the operation from the pointer variable to a data
variable.

125
Computer Programming & Data Structures

 Example:

Sum = *pa + *pb;

Dangling Pointers

A pointer variable should contain a valid address. A pointer variable


which does not contain a valid address is called dangling pointer.

For example, consider the following declaration,

int *pi;

This declaration indicates that pi is a pointer variable and the


corresponding memory location should contain address of an integer
variable. But , the declaration will not initialize the memory location
and memory contains garbage value as shown in below.

pi

Garbage Value

Note: We cannot use a pointer variable to the register variable.


The reason is that, user does not know the address of the register
variable. So we are not able to use pointer variable on register
variables.

126
Computer Programming & Data Structures

4.3 POINTER ARITHMETIC

The following operations can be performed on a pointer:

 Addition of a number to a pointer. Pointer can be incremented


to point to the next locations.

Example:

int i=4 ,pi=&i; //(assume address of i=1000)

float j,*pj=&j;// (assume address of j=2000)

pi = pi + 1; // here pi incremented by (1*data type


times)

pi = pi + 9; // pi = 1000 + (9*2)  1018 address

pj = pj + 3; // pj=1018+(3*4)1030 address

 Subtraction of a number from a pointer. Pointer can be


decremented to point to the earlier locations.

Example:

int i=4,*pi=&i; //assume address of i =1000)

char c, *pc=&c; // assume address of c = 2000

double d, *pd=&d; // assume address of d=3000

pi = pi-2; /* pi=1000-(2*2)=996 address */

pc = pc-5; /* pc=2000-(5*1)=1985 address

pd = pd-6; /* pd=3000-(6*8)=2952 address */

 Pointer variables may be subtracted from one another. This is


helpful while finding array boundaries. Be careful while
performing subtraction of two pointers.
127
Computer Programming & Data Structures

 Pointer variables can be used in comparisons, but usually only


in a comparison to NULL.
 We can also use increment/decrement operators with pointers
this is performed same as adding/subtraction of integer
to/from pointer.

The following operations cannot be performed on pointers.

 Addition of two pointers.


 Multiplication of a pointer with a constant, two pointers.
 Division of a pointer with a constant, two pointers.

POINTER EXPRESSIONS

Like other variables, pointer variables can be used in expressions.


For example, if p1 and p2 are two valid pointers ,then the following
statements are valid.

a= *p1 + *p2;

sum = sum + *p1;

z = 10 / *p2;

f = *p1 * i;

Note: be careful while writing pointer expressions .The expression


*p++ will result in the increment of the address of p by data type
times and points to the new value. Whereas the expression (*p) +
+ will increments the vale at the address. If you are not properly
coded you will get some unwanted result.

NULL Pointer

128
Computer Programming & Data Structures

 If wish to have a pointer that points to “nowhere”, should


make this explicit by assigning it to NULL.
 If it is too early in the code to assign a value to a pointer,
then it is better to assign NULL (i.e., \0 or 0).

double *pval1 = NULL;

double *pval2 = 0;

 The integer constants 0 and 0L are valid alternatives to NULL,


but the symbolic constant is (arguably) more readable.
 A NULL pointer is defined as a special pointer.
 It can be used along with memory management functions.

4.4 POINTERS TO POINTERS

 It is possible to make a pointer to point to another pointer


variable. But the pointer must be of a type that allows it to
point to a pointer.
 A variable which contains the address of a pointer variable is
known as pointer to pointer.
 Its major application is in referring the elements of the two
dimensional array.
 Syntax for declaring pointer to pointer,

data type **ptr_ptr;

 This declaration tells compiler to allocate a memory for the


variable ptr_ptr in which address of a pointer variable
which points to value of type data type can be stored.
 Syntax for initialization

ptr_ptr=&ptr_name;

129
Computer Programming & Data Structures

 This initialization tells the compiler that now ptr_ptr points to


the address of a pointer variable.
 Accessing the element value,

**ptr_ptr;

 It is equalent to *(*(&ptr_name));

Example

130
Computer Programming & Data Structures

The above program illustrates the use of pointers to pointers. Here,


using two indirection operators the data item 16 can be accessed
(i.e., *ppi refers to pi and **ppi refers to i).

4.5 POINTER COMPATIBILITY

 We should not store the address of a data variable of one type


into a pointer variable of another type.
 During assigning we should see that the type of data variable
and type of the pointer variable should be same or
compatible.
 Other wise it will result in unwanted output.
 The following program segment is wrong,

int i=10;

float *pf;

131
Computer Programming & Data Structures

pf=&i; // data variable is integer and pointer


variable is float

It is possible to use incompatible pointer types while assigning with


type casting pointer.

Casting pointers

When assigning a memory address of a variable of one type to a


pointer that points to another type it is best to use the cast operator
to indicate the cast is intentional (this will remove the warning).

Example:

int V = 101;

float *P = (float *) &V; /* Casts int address to float * */

Removes warning, but is still a somewhat unsafe thing to do.

Void Pointer

 A pointer to void is a generic type that is not associated with a


reference type.
 It is neither the address of a character nor an integer, nor a
float nor any other type.
 It is compatible for assignment purposes only with all other
pointer types.
 A pointer of any reference type can be assigned to a pointer
to void type.
132
Computer Programming & Data Structures

 A pointer to void type can be assigned to a pointer of any


reference type.
 Certain library functions return void * results.
 No cast is needed to assign an address to a void * or from a
void * to another pointer type.
 Where as a pointer to void can not be deferenced unless it is
cast.
void *

void

Figure 4.2 pointer to void

 Example:

int V = 101;

float f=98.45;

void *G = &V; /* No warning */

printf (“%d”,*((int*)G)); /* Now it will display 101

float *P = G; /* No warning, still not safe */

printf (“%f”,*((float*)G)); /* Now it will display


98.45

4.6 POINTERS AND FUNCTIONS

 Pointers can be used to pass addresses of variables to called


functions, thus allowing the called function to alter the values
stored there.
 We looked earlier at a swap function that did not change the
values stored in the main program because only the values
were passed to the function swap.
 This is known as "call by value".
 Here we are going to discuss how to pass the address.

133
Computer Programming & Data Structures

Call by Reference

Instead of passing the values of the variables to the called function,


we pass their addresses, so that the called function can change the
values stored in the calling routine. This is known as "call by
reference", since we are referencing the variables.

Here the addresses of actual arguments in the calling function are


copied into formal arguments of the called function. Here The
formal parameters should be declared as pointer variables to store
the address.

The following shows the swap function modified from a "call by


value" to a "call by reference". Note that the values are now
swapped when the control is returned to main function.

Observe the following points when the program is executed,

134
Computer Programming & Data Structures

 The address of actual parameters a and b are copied into


formal parameters pa and pb.
 In the function header of swap (), the variables a and b are
declared as pointer variables.
 The values of a and b accessed and changed using pointer
variables pa and pb.

Call by Value Call by Reference

When Function is called the


When a function is called
values of variables are
address of variables is passed.
passed.

Formal parameters contain


Formal parameters contain the
the value of actual
address of actual parameters.
parameters.

Change of formal parameters The actual parameters are


in the function will not affect changed since the formal
the actual parameters in the parameters indirectly manipulate
calling function the actual parameters

Execution is slower since all


Execution is faster since only
the values have to be copied
addresses are copied.
into formal parameters.

Table: 4.1 Difference between Call by Value and Call by Reference

4.6.1 FUNCTION RETURNING POINTERS

 The way function return an int, float and char, it can return a
pointer.
 To make a function return a pointer it has to be explicitly
mentioned in the calling function as well as in the function
declaration.
 Three things should be done to avail the feature of functions
return pointer.
135
Computer Programming & Data Structures

1. Declaration of function returning pointer

2. Declaring pointer and assigning function call

3. Defining function returning pointer

 Syntax for declaration of function returning pointer


return_type *function_name (arguments);

This declaration helps the compiler to recognize that this


function returns address.

 Now declare pointer variable and place the function call

ptr = function_name (arguments);

 After executing above statement ptr consisting of the address


that is returned by the function. Remember the return type of
the function and pointer type should match here.
 The function Definition returning pointer takes of the form,

return_type *function_name (arguments)

// local declarations

// executable statements

136
Computer Programming & Data Structures

Example:

The execution of the program as follows,

 Execution of the program starts at main.


 Two variables and b are created and initialized at run-time.
 A pointer variable is created and initialized with the return
value of the function max ().
137
Computer Programming & Data Structures

 Once the control is transferred from function main () to max


(), it got executed and returns the pointer value to main().
 Here we are having the address of the maximum variable
address to display it just use indirection operator (*).

Note: function return pointer does not have any advantage except
in the handling of strings.

4.6.2 POINTERS TO FUNCTIONS

Pointer to a function (also known as function pointer) is a very


powerful feature of C. Function pointer provides efficient and
elegant programming technique. Function pointers are less error
prone than normal pointers since we will never allocate or de-
allocate memory for the functions.

Every variable with the exception of register has an address. We


have seen how we can refer variables of type char, int and float.
Through their addresses, by using pointers.

Functions exist in memory just like variables. C will allow you to


define pointers to functions. Just like variables, a function name
gives the starting address of function stored in memory.

The below code illustrate how to get the address of a function.

138
Computer Programming & Data Structures

4.6.2.1 DEFINING POINTERS TO FUNCTIONS

Like declaring pointer variables, we can define pointers to function


variables and store the address. The below figure illustrate how
function pointer can be represented.

main Code for main ()

display

f_ptr Code for display ()

Figure: 4.3. Functions in Memory.

The syntax for declaring pointer to function as follows,

139
Computer Programming & Data Structures

return_type (*f_ptr) (arguments);

Everything is same as function declaration except the braces for the


name, to tell the compiler that this is a fuction pointer braces are
required here and as usual for pointer declarations * is used.

Note that the return type of function pointer, number of arguments


and type of arguments must match with the normal function.

The next after the declaration is calling the function using function
pointer. before calling takes place we must initialize the function
pointer with the address of the function.

The syntax for this assignment,

f_ptr=function_name;

After this assignment we need to call the function, the syntax


associated with the function call is as follows,

(*f_ptr)(argument’s);

This is another way of calling the function. There are no changes in


the declaration of the function body.
140
Computer Programming & Data Structures

The below program simulates a simple calculator using function


pointers.

141
Computer Programming & Data Structures

142
Computer Programming & Data Structures

4.7 POINTERS AND ARRAYS

143
Computer Programming & Data Structures

 An array is a collection of similar elements stored in


contiguous memory locations.
 When an array is declared, the compiler allocates a base
address and sufficient amount of memory depending on the
size and data type of the array.
 The base address is the location of the first element of the
array.
 The compiler defines the array name as a constant pointer to
the first element.

4.7.1 POINTERS AND ONE DIMENSIONAL ARRAY

Let us take the following declaration,

int num [5] = {1, 2, 3, 4, 5};

 After having this declaration, the compiler creates an array


with name num, the elements are stored in contiguous
memory locations, and each element occupies two bytes,
since it is an integer array.

 The name of the array num gets the base address. Thus by
writing *num we would be able to refer to the zeroth element
of the array, that is 1.
 Then *num and *(num+0) both refer to the element 1.and
*(num+2) will refer 3.
 When we have num[i] , the compiler internally converts it to
*(num+i).
 In this light the following notations are same.

num[i]  *(num+i)  *(i+num)  i [num]

144
Computer Programming & Data Structures

 Then we can also define a pointer and initialize it to the


address of the first element of the array (base address).
 Example, for the above array we can have the following
statement,

int *ptr=a; (or) int *ptr=&a[0];

 To refer the array elements by using pointer the following


notations are used.

*ptr  *(ptr+i)  *(i+ptr)  i [ptr]

 p++ will point to the next location in the array.


 Accessing array elements by using pointers is always faster
than accessing them by subscripts.
 The below figure shows the array element storage in the
memory.

num [0] num [1] num [2] num [3]num [4] elements

1 2 3 4 5
values

1000 1002 1004 1006 1008 address

ptr

base address

Figure 4.4 Storage representation of array

145
Computer Programming & Data Structures

Example

146
Computer Programming & Data Structures

The above program illustrates displaying the array elements using


pointers.

Note: Note that the array name num is a constant pointer points to
the base address, then the increment of its value is illegal, num++
is invalid.

4.7.2 POINTERS AND TWO DIMENSIONAL ARRAYS

A two dimensional array is an array of one dimensional arrays. The


important thing to notice about two-dimensional array is that, just
as in a one-dimensional array, the name of the array is a pointer
constant the first element of the array, however in 2-D array, the
first element is another array.

Let us consider we have a two-dimensional array of integers. When


we dereference the array name, we don’t get one integer, we get an
array on integers. In other words the dereference of the array name
of a two-dimensional array is a pointer to a one-dimensional array.
Here we require two indirections to refer the elements

Let us take the declaration

int a [3][4];

Then following notations are used to refer the two-dimensional


array elements,

147
Computer Programming & Data Structures

a -----> points to the first row

a+i -----> points to ith row

*(a+i) -----> points to first element in the ith row

*(a+i) +j -----> points to jth element in the ith row

*(*(a+i)+j)----->value stored in the ith row and jth


column

Columns

0 1 2 3

0
1 2 3 4

Rows 1 5 6 7 8

2
9 10 11 12

Example

148
Computer Programming & Data Structures

149
Computer Programming & Data Structures

4.7.3 POINTERS AND THREE DIMENSIONAL ARRAYS

Three-dimensional array can be thought of array of two-dimensional


array. To refer the elements here we require tree indirections.

The notations are,

*(*(a+i) +j) +k --> points to the address of kth dimension in


ith row jth column

*(*(*(a+i) +j) +k) --> value stored at kth dimension ith row jth
column

150
Computer Programming & Data Structures

Example

151
Computer Programming & Data Structures

4.8 FUNCTIONS AND ARRAYS

To process arrays in large program, we have to be able to pass


them to function. We can pass arrays in two ways,

 Passing individual elements


 Passing entire array elements

Passing individual elements

152
Computer Programming & Data Structures

We can pass individual elements by either their data values or by


passing their addresses.

1. Passing Data Values

 This is same as passing data values. Here we are passing an


individual array element at a time tp the function.
 The called function cannot tell whether the value it receives
comes from an array, or a variable.

Example

2. Passing Addresses of array elements

Here we are passing the individual elements address. the called


function requires declaration of arguments as pointer variables.

153
Computer Programming & Data Structures

Example

Passing the Entire Array

Here we see the first situation in which C does not pass values to a
function. The reason for this change is that a lot of memory and
time would be used in passing large arrays every time we wanted to
use one in function.

For example, if an array containing 1200 elements were passed by


value to a function, another 1200 elements would have to be
allocated in the called function and each element would be copied
from one array to the other. So, instead of passing the whole
array, C passes the address of the array.

In C, the name of the array value is address of the first element in


the array. When we pass the name, it allows the called function to
refer to the array back in the calling function. Passing both two

154
Computer Programming & Data Structures

dimensional array and one dimensional are same but subscripts are
changed.

#include<stdio.h>

void square (int [] [4]);

int main ()

int a[5][4]={

{0, 1, 2, 3},

{10, 11, 12, 13},

{20, 21, 22, 23},

{30, 31, 32, 33},

{40, 41, 42, 43}

};

square(a);

return 0;

void square(int x[5][4])

The above program find the squares of the elements of the array
.Here we passed the name of the array as an argument to the
function an in the called function the formal argument is created
and points to the elements of the calling function argument array.

4.9 INTER FUNCTION COMMUNICATION

155
Computer Programming & Data Structures

The communication between the calling function and called function


for the exchange of data is referred as inter function
communication.

The dataflow between the calling function and called function can be
divided into three strategies:

1. Downward flow

` 2. Upward flow

3. Bi-directional flow

Figure 4.5 Data flow strategies

4.9.1 DOWNWARD FLOW

 In downward communication, the calling function sends data


to the called function. NO data flows in opposite direction.
Downward communication is one-way communication.
 In this strategy, copies of the data items are passed from the
calling function to the called function.

156
Computer Programming & Data Structures

 The called function may change the values passed, but the
original values in the calling function remain unchanged.
 The call by value mechanism in C is a perfect solution for the
communication in the downward direction.

 The figure 4.6 illustrates the downward communication. Two


data items are passed from main to the downFun function.
One data value is a literal (value); the other is the value of a
variable.

Figure 4.6 Downward communication

Rules for Downward communication

 Use values in the function call to pass data.


 Use appropriate data values in the function parameter list to
receive the data values.
 Use the parameter identifiers in the called function to access
the local copies of the data.
157
Computer Programming & Data Structures

4.9.2 UPWARD COMMUNICATION

Upward communication occurs when the called function sends data


back to the calling function without ‘receiving any data from it.

 C provides only one upward direction flow, the return


statement. While it works well, only one data item can be
returned.
 The only way that a called function can pass multiple data an
item up to the calling function is to access variables in the
calling function and deposit the data there.
 However, C does not allow us to directly reference a variable
in the calling function. In other words, we cannot access a
variable in the calling function by its identifier.
 The solution is for the calling function to pass address of the
variable to the called function.
 To get the address of a variable, we use the address operator
(&). The following example passes the address of a and b to
function upFun ().
upFun (&a, &b);

 The called function needs to declare that the parameter is to


receive an address in other words, it needs to create an
address variable.
 To declare an address variable, we can use an asterisk (*).
For Example, to define the function upFun (), we can use the
following header.
upFun (int *ax, int *ay);

158
Computer Programming & Data Structures

Figure 4.7 Upward communication

Rules for Upward Communication

To send data from the called function to the calling function:

1. We need to use the & symbol in front of the data variable


when we call the function.

2. We need to use the * symbol after the data type when we


declare the address variable

3. We need to use the * in front of the variable when we


store data indirectly.

4.9.3 BI-DIRECTIONAL FLOW

159
Computer Programming & Data Structures

 Bi- directional communication occurs when the calling function


sends data down to the called function.
 Here the called function sends data up to the calling function.
 Here indirection must be used in both sides of the assignment
statement.
 The rules for the Bi-directional compunction are same as
upward communication.

Figure 4.8 Bi-direction communication

4.10 TYPE QUALIFIERS IN C

The type qualifier associated with some values which do not change
frequently. There are three type qualifiers in C,

1. const

160
Computer Programming & Data Structures

2. volatile

3. restrict

When a storage class, such as static, and a type qualifier are both
needed, the storage class comes before the type qualifier.

4.10.1 CONSTANTS

 The keyword for the constant type qualifier is const.


 A constant object must be initialized when it is declared
because it cannot be changed later.
 The syntax for declaring constant is

const type var_name = value;

 Example,

const float pi=3.14;

 Remember that, we cannot change the value of constant once


it is initialized.
 A string constant can be declared as follows,

const char str[] =”hello”;

Pointers and Constants

Pointers can also be defined as constants. Depending on how they


are coded, however, three different variations can occur.

161
Computer Programming & Data Structures

1. The pointer itself is a constant.

2. The object being pointed to is constant.

3. Both the pointer and its object are constants.

1. The pointer itself is a constant

 When the keyword const is associated with the identifier, that


it is placed after the data type and before the identifier, the
pointer itself is a constant.
 This declaration tells that its contents cannot be changed after
initialization.
 Can change what it points to but cannot change the value of
the object it points to.
 This form turns out to be useful for passing objects to
functions when using “pass-by-reference” semantics.

 Example,

int i = 5, j = 6;

const int *p = &i;

p = &j; /* Valid. p now points to j. */

*p = i; /* Invalid. Cannot change j via p. */

2. The object being pointed to is constant

 When the keyword const is associated with the type, that is, it
is placed before the type, then the object being referenced is
a constant, but the pointer itself is not.
 Can change value of pointed-to object, but pointer must
always refer to the same address.

 Example,

162
Computer Programming & Data Structures

int i = 5, j = 6;

int * const p = &i;

*p = j; /* Valid. i is now 6 */

p = &j; /* Invalid. p must always point to i. */

3. Both the pointer and its object are constants

 To indicate that both the pointer and the object it points to


are constant, use the keyword const twice.
 Example,
int i = 5, j = 6;

const int * const p = &i;

*p = j; /* Invalid. i cannot be changed via p. */

p = &j; /* Invalid. p must always point to i. */

4.10.2 VOLATILE

The volatile qualifier tells the computer that an object may be


changed by entities other than this program. When the compiler
owns an object, it can store and handle it in any way necessary to
optimize the program. As an example, a C compiler may think that
it is more efficient to remove an object from RAM memory and put
it int a register.

 However, sometimes objects must be shared between your


program and some other facilities outside the C program.
 To tell the compiler that the object is shared, we declare it as
type volatile.
 The following shows how an integer or a pointer can be
declared volatile.
163
Computer Programming & Data Structures

volatile int x;

volatile int* ptr;

4.10.3 RESTRICTED

The restrict qualifier, which is used only with pointers, indicates


that the pointer is only the initial way to access the deferenced
data. It provides more help to the compiler for optimization.

Let us at the following code:

int *ptr;

int i=0;

ptr=&i;

*ptr = *ptr+4;

*ptr = *ptr+5;

Here, the compiler cannot replace two statement *ptr=*ptr+4 and


*ptr=*ptr+5 by one statement *ptr=*ptr+9 because it does not
know if the variable i can be accessed directly or through other
pointers.

164
Computer Programming & Data Structures

Now, let us look a same code using the restrict qualifier:

restrict int *ptr;

int i=0;

ptr=&i;

*ptr = *ptr+4;

*ptr = *ptr+5;

Here, the compiler replaces the two statements by one statement


*ptr=*ptr+9, because it is sure that variable i cannot be accessed
through other resources.

4.11 STRINGS IN C

 A string is a sequence/array of characters.


 C has no native string type; instead we use arrays of char.
 A special character, called a “null”, is important because it is
the only way the functions that work with a string can know
where the string ends.
165
Computer Programming & Data Structures

 This may be written as ‘\0’ (zero not capital ‘o’). This is the
only character whose ASCII value is zero.
 Depending on how arrays of characters are built, we may
need to add the null by hand, or the compiler may add it for
us.

The following operations performed on character strings,

 Reading and Writing strings.


 Combining Strings together.
 Copying one string to another.
 Comparing strings for equality.

4.11.1 DECLARING AND INITIALIZING STRING VARIABLES

Declaring a String

A string variable is a valid C variable name and always declared as


an array.

The general form of declaration of a string variable is,

char string_name [size];

 The size determines the number of characters in the


string_name.
 When the compiler assigns a character string to a character
array, it automatically supplies a null character(‘\0’) at the
end of the string.
 The size should be equal to the maximum number of
characters in the string plus one.

166
Computer Programming & Data Structures

Initializing String Variables

Character arrays may be initialized when they are declared. C


permits a character array to be initialized in one of the following
forms,

 Initializing locations character by character.


 Partial array initialization.
 Initializing without specifying the size.
 Array initialization with a string constant.

Initializing locations character by character

If you know all the characters at compile time, you can specify all
your data within brackets:

Example,

char s[6]={‘h’,’e’,’l’,’l’,’o’};

The compiler allocates 6 memory locations ranging from 0 to 5 and


these locations are initialized with the characters in the order
specified. The remaining locations are automatically initialized to
null characters as shown in the below figure 4.9.

s[0] s[1] s[2] s[3] s[4] s[5]

h e l l o \0

1000 1001 1002 1003 1004 1005 Address

167
Computer Programming & Data Structures

Figure 4.9: Initializing Location Character by character

Note: It is the programmer responsibility to allocate sufficient


memory so as to accommodate NULL character at the end. Note
that The ASCII values of characters are stored in the memory.

Partial Array Initialization

If the number of characters values to be initialized is less than the


size of the array, then the characters are initialized in the order
from 0th location. The remaining locations will be initialized to NULL
automatically. Consider the following initialization,

char s[10]={‘h’,’e’,’l’,’l’,’o’};

The above statement allocates 10 bytes for the variable s ranging


from 0 to 9 and initializes first 5 locations with the characters. The
remaining locations are automatically filled with NULL as shown in
below figure 4.10.

s[0] s[1]s[2] s[3]s[4] s[5] s[6] s[7] s[8] s[9]


h e l l o \0 \0 \0 \0 \0

200 201 202 203 204 205 206 207 208 209 --> Address

Figure 4.10 Partial Array Initialization

Initialization Without Size

168
Computer Programming & Data Structures

If we omit the size of the array, but specify an initial set of


characters, the compiler will automatically determine the size of the
array. This way is referred as initialization without size.

char s[]={‘h’,’e’,’l’,’l’,’o’};

In this declaration, even though we have not specified exact


number of characters to be used in array s, the array size will be set
of the total number of initial characters specified and appends the
NULL character.. Here, the compiler creates an array of 6
characters. The array s is initialized as shown in Figure 4.11.

s[0] s[1] s[2] s[3] s[4] s[5]

h e l l o \0

1000 1001 1002 1003 1004 1005 Address

Figure 4.11: Initializing With out size

Array Initialization with a String Constant

It takes of the following form,

char s[]=”hello”;

Here the length of the string is 5 bytes, but size is 6 bytes. The
compiler reserves 5+1 memory locations and these locations are

169
Computer Programming & Data Structures

initialized with the characters in the order specified. The string is


terminated by Null as shown in the figure 4.12.

s[0] s[1] s[2] s[3] s[4] s[5]

h e l l o \0

1000 1001 1002 1003 1004 1005 Address

Figure 4.12: Array Initializing With a String

Here are some illegal statements representing initialization of


strings,

 The following declaration creates character array only not a


string

char s[5]={‘h’,’e’,’l’,’l’,’o’}; //no location for appending


NULL

 The following declaration is illegal.

char str[3]=“Good”; //size is less than the total characters

 We cannot separate the initialization from declaration.

char str3[5];

str3=“Good”; Is not allowed.

170
Computer Programming & Data Structures

 Similarly,
char s1[4]=“abc”;

char s2[4];

s2=s1; /* Error */

Note: Observe the difference between the following ,

0 --> it is an integer zero. Occupies two bytes of memory.

‘0’ --> it is a character constant .It occupies one byte.

‘’0” --> it is a string constant. It occupies two bytes. The first


byte contains the value 0 and second byte
contains \0.

‘\0’ --> it is Null character and occupies 1 byte.

“\0” --> it is a string containing a null-character. It occupies 2


bytes. Together, the string “\0” occupies two
bytes.

4.11.2 STRING INPUT/OUTPUT FUNCTIONS

Strings can be read from the keyword and can be displayed onto
the monitor using the following I/O functions.

Formatted Input Function-scanf ()

The string can be read using the scanf function also. The format
specifier associated with the string is %s.

Syntax for reading string using scanf function is

171
Computer Programming & Data Structures

scanf (“%s”, string_name);

Disadvantages

 The termination of reading of data through scanf function


occurs, after finding first white space through keyboard. White
space may be new line (\n), blank character, tab(\t).
 For example if the input string through keyword is “hello
world” then only “hello” is stored in the specified string.

Formatted Output function-printf ()

The various options associated with printf ():

1. Field width specification


2. Precision specifier
3. Left Justification

1. Field Width Specification

Syntax: %ws

 W is the field with specified width.


 S indicates that the string is being used.

NOTE:

172
Computer Programming & Data Structures

1. If the string to be printed is larger than the field width w, the


entire string will be printed.
2. If the string to be printed is smaller than the field width w,
then appropriate numbers of blank spaces are padded at the
beginning of the string so as to ensure that field width w is
reached.

Example:

#include<stdio.h>

void main () OUTPUT:

char s[]=“RAMANANDA”; RAMANANDA

2. Precision Specifier

Syntax: %w.ns

 W is the field specified width


 N indicates that first n characters have to be displayed. This
Example:
gives precision.
 S indicates that the string is being used.

#include<stdio.h>

#include<conio.h>

void main()

{
173
char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A’}:
clrscr();

printf(“%0.2s\n”,s);
Computer Programming & Data Structures

OUTPUT:
RA

RAMA

RAM

NOTE:

 The string is printed right justification by default.


 If w > n, w columns are used to print first n characters
.example 2nd and 3rd printf statements.
 If w < n, minimum n columns are used to print first n
characters. Example, 1st and 4th printf statements.

3. Left justification

Syntax: %-w.ns

 - just before w indicates that string is printed using left


justification.
 W is the field with specified width.
 S indicates that the string is being printed.

174
Computer Programming & Data Structures

Example:

#include<stdio.h>

#include<conio.h> OUTPUT:
void main ()

{
RA
char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A’}:
clrscr(); RAMA

printf (“%-0.2s\n”, s);

Character I/O from Keyboard

To read characters from the keyboard and write to screen it tkas


the following form:

c = getchar( ); //reads one character from the keyboard

putchar(c); // display the character on the monitor

175
Computer Programming & Data Structures

Un-Formatted Input Function-gets ()

C provides easy approach to read a string of characters using gets()


function.

Syntax: gets (string_name);

The function accepts string from the keyboard. The string entered
includes the white spaces. The input will terminate only after
pressing <Enter Key>. Once the <Enter key > is pressed ,a null
character(\0) appended at the end of the string.

Advantage

 It is capable of reading multiple words from the keyword.

Un-Formatted Output Function- puts ()

 It is a library function available in <stdio.h>.


 This a one parameter function and is invoked as under:

puts(str);

 Where str is a string variable containing a string value.

4.11.3 TWO DIMENSIONAL ARRAY OF CHARACTERS

176
Computer Programming & Data Structures

It is also referred as table of strings. It can be initialized as follows:

type variable-name[][];

The first subscript gives the number of names in the array.

The second subscript gives the length of each item in the array.

Example:char list[6][10]={

“akshay”,

“parag”,

“raman”,

“srinivas”,

“gopal”,

“rajesh”

};

The names would be store in the memory as shown below.

177
Computer Programming & Data Structures

4.11.4 STRING HANDLING FUNCTIONS

The C Library provides a rich set of string handling functions that


are placed under the header file <string.h>.

strcat () function:

The strcat function joins two strings together. It takes of the


following form:

strcat(string1,string2);

String1 and string2 are character arrays. When the function strcat is
executed, string2 is appended to string1.It does so by removing
the null character at the end of string1 and placing string2 from
there.

178
Computer Programming & Data Structures

strcat function may also append a string constant to a string


variable. The following is valid.

strcat(part1,”Good”);

C permits nesting of strcat functions. Example:

strcat(strcat(string1,string2),string3);

Example

#include <stdio.h>

#include <string.h>

main ()

char opening[255] = "And, the Oscar goes to... ";

char winner[255] = "American Beauty";

strcat (opening, winner);

When using strcat, be careful


that you do not overrun the
strcmp () function:
array size. For example, do
not append a 255 char word to
opening.
The strcmp function compares two strings identified by the
arguments and has the value 0 if they are equal. If they are not, it
has the numeric difference between the first non matching
characters in the strings. It takes the following form:

strcmp(str1,str2);

179
Computer Programming & Data Structures

 return value less than 0 means ''str1'' is less than ''str2'‘


 return value 0 means ''str1'' is equal to ''str2'‘
 return value greater than 0 means ''str1'' is greater than
''str2''

String1 and string2 may be string variables or string constants.

Example: strcmp(name1,name2);

strcmp(name1,”John”);

strcmp(“their” ,”there”);

Example: Password Protection

#include <stdio.h>

#include <string.h>

main ()

char password[255];

printf ("Enter password: ");

scanf ("%s", password);

while (strcmp (password, "bluemoon") != 0) {

strcpy () function:

it takes the following form:

strcpy(string1,string2);

180
Computer Programming & Data Structures

and assign the contents of string2 to string1.

String2 may be a character array variable or a string constant.

Example: strcpy(city ,”Delhi”);

strcpy(city1,city2);

#include <stdio.h>

#include <string.h>

main ()

char word1[] = "And, the winner is....";

char word2[255];

Output:

And, the winner is....

strlen () function:

This function counts and returns the number of characters in a


string. It takes the form

181
Computer Programming & Data Structures

n=strlen(string);

Where n is an integer variable, which receives the value of the


length of the string. The counting ends at the first null character.

Example:

#include<stdio.h>

#include<string.h>

void main()
Output: 4
{

char name[100]="Gore";
Note, however, that the
size of the array is 100

strrev () function

Reverses the contents of the string. It takes of the form

strrev(string);

Example:

#include<stdio.h>

#include<string.h>

void main() 182

char s[]=”hello”;
Computer Programming & Data Structures

OUTPUT:

olleh

strstr () function:

It is a two-parameter function that can be used to locate a sub-


string in a string. It takes the form:

strstr (s1, s2);

Example: strstr (s1,”ABC”);

The function strstr searches the string s1 to see whether the string
s2 is contained in s1.If yes, the function returns the position of the
first occurrence of the sub-string. Otherwise, it returns a NULL
pointer.

Example: if (strstr (s1, s2) ==NULL)

printf (“substring not found”);

else
183
Computer Programming & Data Structures

printf (“s2 is a substring of s1”);

We also have the functions to determine the existence of a


character in a string.

Example: strchr (s1,’m’);

Will locate the first occurrence of the character ‘m’.

Example: strrchr(s2,’m’);

Will locate the last occurrence of the character ‘m’.

Functions included in <string.h>

Operation Function Description

memcpy Copies a block of memory

Copying memmove Move block of memory

strcpy Copy string

strncpy Copy n number characters from


string

Concatenation strcat Concatenate strings

strncat Append n number of characters from


string

memcmp Compare two blocks of memory

Comparison strcmp Compare two strings

strcoll Compare two strings using locale

184
Computer Programming & Data Structures

strncmp Compare first n characters of two


strings

strxfrm Transform string using locale

memchr Locate character in block of memory

strchr Locate first occurrence of character


in string

strcspn Get span until character in string


Searching
strpbrk Locate character in string

strrchr Locate last occurrence of character


in string

strspn Get span of character set in string

strstr Locate substring

strtok Split string into tokens

Other strrev reverse the content of the string

memset Fill block of memory

strerror Get pointer to error message string

strlen Get string length

Table 4.2: String Functions in C

4.11.3 CHARACTER POINTER

Suppose we wish to store “Hello”. We may either store it in a string


or we may ask the C compiler to store it at some location in
memory and assign the address of the string in a char pointer.

Consider the following declaration with string initialization,

char *p=”hello”;

Here the string length is 5 bytes. So the compiler allocates 6 bytes


memory locations. Probably the characters are stored in the

185
Computer Programming & Data Structures

constant memory area of the computer, and the pointer p points to


the base address as shown in the below figure 4.13.

s [0] s [1] s[2] s[3] s[4] s[5]

h e l l o \0

1000 1001 1002 1003 1004 1005 Address

1000

Figure 4.13: Initializing using Character Pointer

 We cannot assign a string to another. But, we can assign a


char pointer to another char pointer.

Example: char *p1=”hello”;

char *p2;

p1=p2; //valid

printf (“%s”, p1); //will print hello

 *p will refer to a particular character only, p will refer whole


string.

4.11.4 POINTERS AND STRINGS

186
Computer Programming & Data Structures

A string is a character array. so the name of the string it self is a


pointer. Like referring array elements also string characters also
refereed with its name.

Example:

char s [] =”hello”;

The following notations are used to refer individual characters

s[i] --> *(s+i) --> *(i+ s) all will point to the ith character in
the given string.

We can also use pointer variable to refer the string elements.

char s [ ]=”hello”;

char *ptr;

ptr=s; // now ptr points to the base address of the string.

then the following notations are same,

*ptr --> *(ptr+i) --> *(i+ptr) will point value at the ith
character.

Example: // illustrates displaying characters using pointer

#include<stdio.h>

void main ()

char s [] =”hello”;

char *ptr; 187

ptr=s;

while (*ptr! =’\0’)


Computer Programming & Data Structures

OUTPUT

hello

4.12 ARRAY OF POINTERS

 A pointer variable always contains an address; an array of


pointers would be nothing but a collection of addresses.
 The addresses present in the array of pointers can be
addresses of variables or addresses of array elements or any
other addresses.
 The major application of this is in handling data tables
efficiently and table of strings.
 All rules that apply to an ordinary array apply to the array of
pointes as well.
 The Syntax for declaration of array of pointers as follows,

data type *arr_ptr [size];

 This declaration tells the compiler arr_ptr is an array of


addresses, pointing to the values of data type.
 Then initialization can be done same as array element
initialization. Example arr_ptr [3] =&var, will initialize 3rd
element of the array with the address of var.
 The dereferencing operator is used as follows

*(arr_ptr [index]) --> will give the value at particular


address.
188
Computer Programming & Data Structures

 Look at the following code array of pointers to ordinary


Variables
Example

OUTPUT

#include<stdio.h> 1

void main () 2

int i=1, j=2, k=3, l=4, x;

int *arr [4]; //declaration of array of pointers

arr [0] =&i; //initializing 0th element with address of i

arr [1] =&j; //initializing 1st element with address of j

i j k l

1
4000 2
5000 3
6000 7000 4

arr[0] arr[1] arr[2] arr[3]

4000 5000 6000 7000

Figure 4.14 Memory organization

The above figure 4.14 shows contents and the arrangement of the
array of pointers in memory. Here, arr contains the addresses of int
variables i, j, k and l. The for loop is used to print the values
present at these addresses.

189
Computer Programming & Data Structures

A two-dimensional array can be represented using pointer to an


array. But, a two-dimensional array can be expressed in terms of
array of pointers also.

Using array of pointers a two dimensional array can be defined as,

data type *arr_ptr [size];

where data type refers to the data type of the array. arr_ptr refers
to the name of the array and size is the maximum number of
elements in the row.

Example int *arr [3];

Here, p is an array of pointers, and then following notations are


used to refer elements.

p [i] --> points the address of the element ith row,

p[i] +j --> points the address of the element ith row and jth
column

*(p[i] +j) --> value at ith row and jth column.

Array of pointers and Strings

 Each element of the array is a pointer to a data type (in this


case character).
 A block of memory (probably in the constant area) is
initialized for the array elements.
 Declaration:
char *names [10]; // array of 10 character pointers.
190
Computer Programming & Data Structures

 In this declaration names [] is an array of pointers. It contains


base address of respective names. That is, base address of
first name is stored in name [0] etc., a character pointer etc.
 The main reason to store array of pointers is to make more
efficient use of available memory.

# include <stdio.h>

int main ()

char *name [] = {

"Illegal month",

"January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November",
"December"

};

191
Computer Programming & Data Structures

The pointers are initialized like so

Note: When we are using an array of pointers to strings we can


initialize the string at the place where we are declaring the array,
but we cannot receive the string from keyword using scanf ().

192
Computer Programming & Data Structures

Exercise Programs

1. The names of employees of an organization are stored in


three arrays, namely, first name, second name, and last
name. Write a program to concatenate the three parts into
one string to be called name.

2. Write a C program to read in an array of integers. Instead of


using subscripting, however, employ an integer pointer that
points to the elements currently being read in and which is
incremented each time.

3. Write a C program to find number of words, blank spaces,


special characters, digits and vowels of a given text using
pointers.

4. Write a C program using pointer for string comparison.

5. Write a C program to find out the presence of a substring in a


given string using pointers.

6. Write a C program to find the length of a given string using


pointers.

7. Write a program to reverse the strings stored in array of


pointers.

8. Write a program to find rank of a matrix using pointers.

9. Write a C program using pointers to read in an array of


integers and print its elements in reverse order.

193
Computer Programming & Data Structures

10. Write a C program to arrange the given numbers in


ascending order using pointers.

11. Write a ‘C’ program to find factorial of a given number using


pointers.

12. Write a ‘C’ program to arrange the given names in


alphabetical order using pointers.

13. Write a ‘C’ Program to compute the sum of all elements


stored in an array using pointers.

14. Write a C program to find the desired element in an array of


N elements. Use pointers to search an element.

15. The roots of a quadratic equation of the form ax2+bx+c = 0


are given by the following equations:
X1 = −b +sqrt (b2− 4ac)/2a

X2 = −b −sqrt (b2− 4ac)/2a

Write a function to calculate the roots. The function must use


two pointer parameters, one to receive the coefficients a, b
and c and the other to send the roots to the calling function.

194
Computer Programming & Data Structures

ASSIGNMENT IV

1. a) Write short notes on pointer to void.


b) Write short notes on Address Arithmetic.

c) Explain pointer to pointer with an example.

2. a) How to use pointers as arguments in a function? Explain


through an example.
b) Write a ‘C’ function using pointers to exchange the values
stored in two locations in the memory.

3. a) Explain how strings can be stored using a


multidimensional arrays?
b) What are the string in-built functions available? Write in
detail about each one of them with an example.

c) Write a C program to replace a particular word by another


word in a given string.

4. a) What is a pointer variable? How is a pointer variable


different from an ordinary variable.

b) Distinguish between address operator and dereferencing


operator.

c) Write a C Program to illustrate the use of indirection


operator “*” to access the value pointed by a pointer.

5. What is the purpose of array of pointers? illustrate with


an example.

6. a) Distinguish between array of pointers and pointer to array


with examples.

b) Explain pointer to function and function returning pointer


with example.

195
Computer Programming & Data Structures

UNIT IV
5.0 INTRODUCTION

The basic data types in C are int, float and char. using these data
types, we can derive some other data types, the data types that are
derived from the basic data types are called derived data types.

We have already discussed three of the six derived types: arrays,


functions and pointers. In this unit, we discuss the three remaining
derived types: structure, union and enumerated. We will also
discuss the use of type definition and Bit field. The derived data
types are shown in Figure 5.0.

Figure 5.0 Derived Types in C

5.1 STRUCTURES

We have seen that arrays can be used to represent a group of data


items that belong to the same type. However in real world, we often
deal with entities that are collection of dissimilar data items. Using
array variables we cannot store different items under one name. C

196
Computer Programming & Data Structures

supports a derived data type known as structure, which is a method


for storing data of different types.

Structure Definition

A structure is a collection of logically related elements, possibly of


different types, having a single name.

Advantages

 Structures help to organize complex data in a more


meaningful way.
 Being able to manipulate several variables as a single group
makes your programs easier to manage.
 Business data processing uses the concepts of structures in
almost every program. Example, student database and
employee database management.

Good candidates for structures:

Time: year, month, day, hour, minutes, second

Complex number: real part, imaginary part

Point in a 2-dimensional plane: x axis, y axis

5.1.1 DEFINITION OF STRUCTURES

As variables are defined before they use in the program, structures


are also defined and declared before they are used.

197
Computer Programming & Data Structures

A structure definition forms a template that may be used to crate


structure objects. The variables that make up the structure are
called members of the structure.

A structure can be defined using three different ways,

 Tagged Structure
 Structure Variables
 Typedef Structure

Tagged Structure

The structure definition associated with the structure name is


referred as tagged structure. It does not create an instance of a
structure and

Does not allocate any memory.

The general form or syntax of tagged structure definition is as


follows,

struct tag_name

type1 member1;

type2 member2;

……………

198
Computer Programming & Data Structures

Where,

 struct is the keyword which tells the compiler that a


structure is being defined.
 Tag_name is the name of the structure.
 member1, member2 … are called members of the
structure. The members are declared within curly braces.
 The closing brace must end with the semicolon.

Example: student details using tagged structure

struct student

char name [10];

int roll_number;

float avg_marks;

}; // no memory is allocated for the structure

Note the following points with respect to above structure definition,

 struct is the keyword which tells the compiler structure is


being defined.
 student is an identifier representing the structure name
(tag_name).
 name, roll_number and avg_marks are members of a
structure and are themselves are not variables. They do not
occupy any memory.

Memory is not reserved for the structure definition since no


variables are associated with the structure definition. The members
of the structure do not occupy any memory until they are
associated with the structure variables.

199
Computer Programming & Data Structures

The declaration of the structure variable takes of the form,

struct tag_name var1, var2…;

where, struct is the keyword. Tag_name is the name of the


structure. Structure variables are separated by comma, followed by
semicolon.

We can declare structure variables any where in the program.

For the above example the variable declaration as follows,

struct student s1; // memory is allocated for the


variable

now a variable of type struct student (derived type) is created,


the memory is allocated for the variable s1.

The following figure shows the memory organization for the above
example.

s1

------ Name ------> <- Roll_Number -> <- Avg_Marks ->

< 10 Bytes > < 2 Bytes > < 4 Bytes >


Figure 5.1 Memory map for structure
variable

200
Computer Programming & Data Structures

The number of bytes allocated for the structure variable is the sum
of sizes of the individual members. In the above example the size of
s1=16 bytes (10+2+4).

Note: Normally, structure definition appears at the beginning of the


program file, before any variables or functions defined.

Structure Variables

Here we are combining both the template declaration and variable


declaration in one statement, is referred as structure variables. The
syntax of tagged structure is as follows,

struct tag_name

type1 member1;

type2 member2;

Where,

 struct is the keyword which tells the compiler that a


structure is being defined.
 tag_name is the name of the structure.
 member1, member2 … are called members of the
structure. The members are declared within curly braces.
 var1, var2… are structure variables that follow curly
braces. Here each variable occupies memory.
 The closing brace must end with the semicolon.

Example: student details using structure variables


201
Computer Programming & Data Structures

struct student

char name [10];

int roll_number;

float avg_marks;

} s1;

Here, name, roll_number and avg_marks are the structure


members. s1 is the structure variable, the compiler allocates
memory for the variable s1 as shown in Figure 5.1.

We can omit the tag name from the structure definition, the
following is valid.

struct

char name [10];

int roll_number;

float avg_marks;

} s1, s2;

Declares s1 and s2 as structure variables representing two


students. This structure definition and declaration is normally not
used because we can not declare variables in later stage in the
program.

202
Computer Programming & Data Structures

Typedefined Structure

 The structure definition associated with keyword typedef is


called type-defined structure.
 This is the most powerful way of defining the structure.

 The syntax of typedefined structure is

typedef struct

type1 member1;

type2 member2;

where,

 typedef is keyword added to the beginning of the


definition.
 struct is the keyword which tells the compiler that a
structure is being defined.
 member1, member2…are called fields of the structure.
 The closing brace must end with type definition name
which in turn ends with semicolon.

Example: Student details

203
Computer Programming & Data Structures

//Structure Definition

typedef struct

char name [10];

int roll_number;

float avg_marks;

} STUDENT; //no memory is allocated for structure

/* structure declaration */

STUDENT s1, s2; //memory is allocated for the variables.

Note: Using typedef it is not possible to declare a variable. But, we


can have user defined data type. TYPE_ID can be treated as the
new data type.

5.1.2 INITIALIZATION OF STRUCTURES

The rules for structure initialization are similar to the rules for array
initialization. The initializers are enclosed in braces and separate by
commas. They must match their corresponding types in the
structure definition.

The syntax is shown below,

struct tag_name variable = {value1, value2,… valuen};

204
Computer Programming & Data Structures

Structure initialization can be done in any of the following


initialization.

Initialization along with Structure definition

Consider the structure definition for student with three fields name,
roll number and average marks. The initialization of variable can be
done as shown below,

struct student

char name [5];

int roll_number;

float avg;

} s1= {“Ravi”, 10, 67.8};

The various members of the structure have the following values.

--- name -------------->  roll_number -> ------ avg


-------->

R a v i \0 1 0 6 7 . 8

Figure 5.2 Initial Value of S1

Initialization during Structure declaration

205
Computer Programming & Data Structures

Consider the structure definition for student with three fields name,
roll number and average marks. The initialization of variable can be
done as shown below,

struct student

char name[5];

int roll_number;

float avg;

};

struct student s1= {“Ravi”, 10, 67.8};

The various members of the structure have the values as shown in


Figure 5.2.

We can also initialize multiple variables using comma between


variables.

Points to Remember

 The members of the structure cannot be initialized in the


structure definition.

For example,

struct s

206
Computer Programming & Data Structures

char name [10] ="ravi”;

int rno;

} s1;

is invalid.

 The initial values are assigned to members of the structure on


one-to-one basis i.e., the values are assigned to various
members in the order specified from the first member.

For example,

s1= {“ravi”, 60, 56.7};

is valid. Here, the string “ravi” will be assigned to the first


member. 60 is assigned to the second member and 56.7 is
assigned to the third member.

 During partial initialization, the values are assigned to


members in the order specified and the remaining members
are initialized with garbage values.

For example,

s1= {“ravi”};

will assign the string “ravi” to name and the remaining


members are initialized to garbage values.

However the statement,

s1= {40, 67.8};

207
Computer Programming & Data Structures

is invalid, because, without initializing the first member name,


we are trying to initialize last two members.

 During initialization, the number of initializers should not


exceed the number of members. It leads to syntax error.

For example,

s1= {“ravi”, 45, 78.9, 89};

the compiler issues a syntax error “too many initializers”

5.1.3 ACCESSING STRUCTURES

We know that variables can be accessed and manipulates using


expressions and operators. On the similar lines, the structure
members can be accessed and manipulated. The members of a
structure can be accessed by using dot(.) operator.

dot (.) operator

Structures use a dot (.) operator to refer its elements, also known
as period operator.

Before dot, there must always be a structure variable. After the dot,
there must always be a structure element.

The syntax to access the structure members as follows,

208
Computer Programming & Data Structures

structure_variable_name. structure_member_name

For example, consider the example as shown below,

struct student

char name [5];

int roll_number;

float avg;

};

struct student s1= {“Ravi”, 10, 67.8};

The members can be accessed using the variables as shown below,

s1.name --> refers the string “ravi”

s1.roll_number --> refers the roll_number 10

s1.avg --> refers avg 67.8

Arrays with in structures

It is also possible to declare an array as a member of structure, like


declaring ordinary variables.

For example to store marks of a student in three subjects the we


can have the following definition of a structure.

209
Computer Programming & Data Structures

struct student

char name [5];

int roll_number;

int marks [3];

float avg;

};

Then the initialization of the array marks done as follows,

struct student s1= {“ravi”, 34, {60,70,80}};

The values of the member marks array are referred as follows,

s1.marks [0] --> will refer the 0th element in the marks

s1.marks [1] --> will refer the 1st element in the marks

s1.marks [2] --> will refer the 2ndt element in the marks

The below program illustrates how to define a structure, declare a


structure and access the members of the structure.

210
Computer Programming & Data Structures

211
Computer Programming & Data Structures

5.2 STRUCTURE OPERATIONS

Any operation that can be performed on ordinary variables can also


be performed on structure members. But, some operations can not
be performed on structure variables. The following sections deals
with operations that carried on structure and structure members.

Copying of structure Variables or members

Copying of two structure variables is achieved using assignment


operator. But, one structure variable can be assigned to another
structure variable of the same type.

Example,

struct student

{
212
Computer Programming & Data Structures

char name [10];

float avg;

} a, b;

a=b; //copies b in to a

a.avg = b.avg; // copies b average in to a.avg

We can not copy the variables of different structure type.

213
Computer Programming & Data Structures

Comparison of two structure variables or members

214
Computer Programming & Data Structures

Two variables of same structure type or dissimilar type is not


allowed.

For example, the following operations are invalid, even though s1


and s2 are of the same type,

s1==s2; (or) s1! = s2; invalid: because comparison is not allowed


between structure variables.

However, the members of two structure variables of same type can


be compared the same way as ordinary variables. s1 and s2 are two
structures, and then the following operations are valid.

Operation Meaning

s1.member1 == s2.member1 Compares member1 of a with


member1 of b and return true if
they are same, false otherwise.

returns if the member1 of a and


s1.member1 != s2.member1 member1 of b are not same and
false otherwise.

Table 5.1 Comparison of Structure Members

Arithmetic Operations on Structures

The members of a structure are same to any ordinary variable and


so any operation that can be performed on a variable can also be
performed on structure members. The following operations are
valid.

215
Computer Programming & Data Structures

Expression Meaning

increments the salary before


++e.salary accessing its value.

increments the salary after


e.salary++
accessing its value.

&e.salary Access the address if e.salary.

Access the beginning address of


&e
the structure.

Table 5.2 Arithmetic Operations on Structure Members

Note: The arithmetic, relational, logical and other various


operations can be performed on individual members of the
structures but not on structure variables.

5.3 NESTED STRUCTURES

A structure which includes another structure is called nested


structure i.e a structure can be used as a member of another
structure.

The syntax for the nesting of the structure as follows,

struct tag_name1

type1 member1;

…….

216
Computer Programming & Data Structures

…….

};

struct tag_name2

type1 member1;

……

……

struct tag_name1 var;

……

};

The syntax for accessing members of a nested structure as follows,

outer_structure_variable.innerstructurevariable.membername

Good candidates for nested structures:

Student: dob -> day, month, year

Employee: allowance -> da, ta, hra

Player: tests, one days, T20

Example: Consider the student information name, roll no, DOB and
avg. The DOB consists of day, month, and year. It can be defined as
shown below,

217
Computer Programming & Data Structures

struct data

int day;

int month;

int year;

};

struct student

char name [10];

int roll_number;

struct data dob;

int marks [3];

float avg;

} s1;

Note that the above structure consists of a member identified by


dob whose type is struct data.

The members contained in the inner structure namely day, month


and year can be referred to as

s1.dob.day

s1.dob.month

s1.dob.year

218
Computer Programming & Data Structures

An inner-most member in a structure can be accessed by chaining


all the concerned structure variables (from outer-most to inner-
most).

The memory organization of variable s1 is shown in Figure 5.3.

s1

name roll_number dob marks year

10 bytes 2 bytes day month year 6 bytes 4 bytes

2 bts 2 bts 2 bts

Figure 5.3: Memory organization of nested structure

We can nest two structures by using the following syntax,

struct tag_name1
Example
{
struct student

{
type1 member1;
char name [10];
…….
int roll_number;
…….
struct data
219
struct tag_name2
{
{
int day;
type1 member1;
Computer Programming & Data Structures

in the

In the above definition it is mandatory to initialize variable to the


inner most structure. The members are accessed same way as first
method.

Below program illustrates nesting of structures.

220
Computer Programming & Data Structures

221
Computer Programming & Data Structures

5.4 ARRAY OF STRUCTURES

As we have an array of integers, we can have an array of structures


also. For example, suppose we want to store the information of
class of students, consisting of name, roll_number and marks, A
better approach would be to use an array of structures.

Array of structures can be declared as follows,

struct tag_name arrayofstructure[size];

After having the above declaration a list of variables of type struct


tag_name.

Let’s take an example, to store the information of 3 students, we


can have the following structure definition and declaration,

222
Computer Programming & Data Structures

struct student

char name[10];

int rno;

float avg;
// program illustrates reading and displaying of student information for a class of
students
}; using array of structures

#include<stdio.h>

struct student
struct student s[3];
{

char rollno[10];
Defines array called s, which contains three elements. Each element
char name[20];
is defined to be of type struct student.
char branch[10];

For char
the gender;
student details, array of structures can be initialized as
follows,
struct birthday

struct
{ student s[3]={{“ABC”,1,56.7},{“xyz”,2,65.8},
{“pqr”,3,82.4}};
int day;
The memory organization of the variables is illustrated in the below
char month[10];
Figure,
int year;
s
}DOB; Name rno avg

int sub[3];(10bytes) (2 bytes) (4bytes)


s [0]
float avg; Name rno avg

}; (10bytes) (2 bytes) (4bytes)


s [1]

Name rno avg


int main()
5.4: Memory organization of array of structures
{

int i,n,j,sum=0;
223
struct student s[10];

printf(" Enter how many students are there in the class:");


Computer Programming & Data Structures

sum=0;

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

scanf("%d",&s[i].sub[j]);

sum=sum+s[i].sub[j];

s[i].avg=sum/3.0;

printf("\n******************************************");

printf("\n\t\t\t Student details:");

printf("\n******************************************");
224

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

{
Computer Programming & Data Structures

5.5 STRUCTURES AND POINTERS

The way we can have a pointer pointing to an int, or a pointer


pointing to a char, similarly we can have a pointer pointing to a
struct. Such pointers are known as ‘structure pointers’.

To access the values of the members of the structure using pointers


we need to perform following things,

1. Declare structure variable: struct tag_name var;

2. Declare a pointer to a structure: struct tag_name *ptr;

3. Store the address of structure variable in structure pointer:


ptr=&var;

4. Access the members of the structure.


225
Computer Programming & Data Structures

Members of the structures can be accessed in following ways.

Using De-Reference Operator * and Dot (.) Operator

If ptr is a pointer to a structure, then the structure itself can be


accessed using indirection operator as shown below,

struct tag_Name *ptr; // Refers to the whole structure

Once the structure pointer is initialized, then each member of the


structure can be accessed using dot operator as shown below,

(*ptr).structure_member1

(*ptr).structure_member2

Let’s take the following segment of code

struct student

int rno;

char name[10];

float avg;

};

struct student s1={101,”ABC”,78.98};

struct student *ptr;

ptr=&s1;

226
Computer Programming & Data Structures

Now the members of the structure can be accessed by using the dot
operator as shown below,

(*ptr).name // Access the name

(*ptr).rno // Access roll number

(*ptr).avg // Access average

Note: The parenthesis to all three expressions is necessary. We


should not omit the parenthesis. For example,

*ptr .name // invalid way of accessing the member

Using Selection Operator (->)

If ptr is a pointer to structure, then the members of the structure


can also be accessed using selection operator denoted by ->(which
is formed by minus sign and greater than symbol).

Using this various members of the structure can be accessed as


shown below,

ptr -> structrure_member

For the above example the members can be accessed as follows,

ptr - > name // Access the name

ptr - > rno // Access roll number

ptr - > avg // Access average

227
Computer Programming & Data Structures

Remember that on the left hand side of the dot operator, there
must always be a structure variable, whereas on the left hand side
of -> operator there must be always be a pointer to structure. This
method is efficient, preferred over the previous method.

s1.rno s1.name s1.avg

101 ABC 78.98

4001 4003 4013

ptr

4001

5001

Figure 5.5: Memory Representation of Structure Pointer

The arrangement of structure variable and pointer to structure in


memory is as shown in the Figure 5.5,

// C program to read and display student details using pointer to


structure

228
Computer Programming & Data Structures

229
Computer Programming & Data Structures

Structure Containing Pointers

We can also contain pointers as members of the structures. The


pointer is pointing to a value of the structure member or some
other variable. In general to reduce memory wastage we are using
this concept to declare strings as structure members using
character pointer.

The below code illustrates pointers as members of structures.

#include<stdio.h>

struct student

char name [10];

int rno;

float *ptr;

};

int main () 230


{
Computer Programming & Data Structures

5.6 STRUCTURES AND FUNCTIONS

We should note that structures are more useful if we are able to


pass them to functions and return them. The structures members
can be passed to the function in various ways as shown below,

1. BY passing individual members of structure

2. By passing the whole structure

3. By passing structures through pointers

Passing Individual Members

The first method is to pass each member of the structure as an


actual argument of the function call. The actual arguments are
treated independently like ordinary variables.

// Passing individual structure elements

231
Computer Programming & Data Structures

232
Computer Programming & Data Structures

Explanation

Observe that in the declaration of the structure, rno is declared as


int, marks are declared as integer array and avg as float. Therefore,
when we call the function display using

display (s1.rno, s1.marks, &s1.avg);

We are passing the structure individual member value, the base


address of the array marks and the address of structure member.
Thus, this is a mixed of call-a call by reference as well as a call by
value.

Note: This method is inefficient when the structure size becomes


large. A better way would be to pass the entire structure variable at
a time.

233
Computer Programming & Data Structures

Passing Whole Structure

The second method involves passing a copy of the entire structure


to the called function. 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 general format of sending a copy of a structure to the called


function is:

return_type function_name (structure_variable_name);

The called function takes the following form:

data_type function_name(struct_type tag_name)

………

………

return(expression);

The called function must be declared for its type, appropriate to the
data type it is expected to return.

The structure variable used as the actual argument and the


corresponding formal argument in the called function must of the
same struct type.

234
Computer Programming & Data Structures

The return statement is necessary only when the function is


returning some data back to the calling function. The expression
may be any simple variable or structure variable or an expression
using simple variables.

When a function returns a structure, it must be assigned to a


structure of identical type in the calling function. The called
functions must be declared in the calling function appropriately.

// Passing Entire Structure

235
Computer Programming & Data Structures

Explanation
236
Computer Programming & Data Structures

Note that here the calling of function fun becomes quite compact,
fun (s1); Then the formal argument in the called function defined as
struct type struct student.

Returning Structure from a function

It is also possible that using return statement we can return


structure to the calling function. Here the return type of the function
and the return value both must be of type structure.

When the function call comes with an assignment to the structure


variable, after executing the called function the structure is returned
and it is copied into the structure variable in the assignment
statement.

// Program illustrating function returning structure

237
Computer Programming & Data Structures

Passing Structures Through Pointers

238
Computer Programming & Data Structures

We have a pointer pointing to a structure. such pointers are known


as “structure pointers. The third approach employs the concept of
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 indirectly the entire structure and work on
it.

// C program illustrate Passing address of a structure variable

239
Computer Programming & Data Structures

5.7 SELF-REFERENTIAL STRUCTURE

 A structure definition which includes at least one member as a


pointer to the same structure is known as self-referential
structure.
 Can be linked together to form useful data structures such as
lists, queues, stacks and trees.
 Terminated with a NULL pointer (0).

The syntax for using the self referential structure as follows,

Struct tag_Name

type1 member1;

type2 member2;

….

240
Computer Programming & Data Structures

Example,

struct node

I int data;

struct node *next;

} n1, n2;

Diagram of two self-referential structure objects linked together is


shown in below Figure 5.6.

Figure 5.6 Self Referential Structure Object Linking

Here next points to an object of type node referred to as a link ties


one node to another node.

241
Computer Programming & Data Structures

5.8 UNIONS

 A union is one of the derived data type.


 Union is a collection of variables referred under a single name.
 The syntax, declaration and use of union is similar to the
structure but its functionality is different.
 The major distinction between structure and union is, in terms
of storage.
 In structure each member has its own storage location.
 Whereas all the members of a union use the same location.
 Although a union may contain many members of different
types, it can handle only one member at a time.

The general format or syntax of a union definition is as follows,

union tag_name

type1 member1;

type2 member2;

……..

Observe the following points while defining a union.

242
Computer Programming & Data Structures

 union is the keyword which tells the compiler that a union is


being defined.
 member1, member2, … are called members(or fields) of the
union.
 The members are declared within curly braces.
 The compiler allocates a piece of storage that is large enough
to hold the largest variable type in the union.
 There should be semicolon at the end of closing braces.

A union variable can be declared same way as structure variable.

union tag_name var1, var2...;

A union definition and variable declaration can be done by using any


one on the following Figure 5.7.

union u union u typedef union

{ { {

char c; char c; char c;

int i; int i; int i;

float f; float f; float f;

tagged
union variable union typedef union

Figure 5.7 Types of Union Definitions

To access the members of union, the same syntax used to access


various members of a structure can be used, by using the dot
operator (“. “). For above example, we can access various
members of the union as shown below,

243
Computer Programming & Data Structures

a.c

a.i

a.f

For the above example, union contains three members, each with a
different data type. However, we can use only one of them at a
time.

1001 1002 1003 1004

a.c

a.i
a.f

Figure 5.8: Memory Organization Union

In the above declaration, the member f requires 4 bytes which is


the largest among the members. Figure 5.8 shows how all the
three variables share the same address. The size of the structure
here is 4 bytes.

During accessing, we should make sure that we are accessing the


member whose value is currently stored. For example look at the

244
Computer Programming & Data Structures

below program, would produces erroneous output (which is


machine dependent).

In the above program we are initializing all the members of the


union at a time, the member which is large enough to hold the
largest variable type in the union occupies the memory, here float
value is stored in all memory locations of the union.

245
Computer Programming & Data Structures

A union creates a storage location that can be used by any one of


its members at a time. When a different member is assigned a new
value, the new value supersedes the previous members’ value.

246
Computer Programming & Data Structures

The above program illustrates the effective use of union memory


locations.

We can also create a pointer to a union; the syntax is as follows,

union tag_name *ptr;

union u

char c;

int i;

float f;

For the pointer variables, the indirection operator * and dot


operator or selection operator -> can be used to access the
members. For the above example, using pointer variable ptr, the
various members of the union as shown below,

ptr -> c or (*ptr).c

ptr.i -> i or (*ptr).i

ptr.f -> f or (*ptr).f

structure with in union

247
Computer Programming & Data Structures

It also possible union may also contain structures as members of it.


The following code illustrates this concept.

248
Computer Programming & Data Structures

In the above program we have two structure declarations a and b


followed by one union declaration u. Here the members of the union
are two structure variables. Now the size of the union is 4 bytes,
because the first structure contains two integer members so its size
is 4 bytes, and the second structure contains two character
members so its size is 2 bytes, therefore the size of the union is 4
bytes and entire memory locations are occupied by the first
structure variable.

uu.aa.i uu.aa.j

uu.bb.x uu.bb.y

6501 6502 6503 6504

0000 0000 0000 0010 0000 0000 0000 0001


512:- Binary representation 256:- Binary representation

0000 0010 0000 0000 0000 0010 0000 0000

249
Computer Programming & Data Structures

Figure 5.9: Sharing of Union Members

Difference between Array, Structure and Union

Arrays Structures Unions

Keyword … struct union

Defini- An array is a A structure is a A structure is a


tion homogeneous collection of collection of logically
collection of logically related related elements,
data. elements, possibly possibly of different
of different types, types, having a
having a single single name, shares
name. single memory
location.

Declarati data_type struct tag_name union tag_name


on array_Name[s
{ {
ize];
type1 member1; type1 member1;

type1 member2; type1 member2;

250
Computer Programming & Data Structures

…………… ……………

…………… ……………

}; };

struct tag_name union tag_name


var; var;

Initializa Done by Same. Same.


tion separating list
of values with
comma (,),
specified in
Curly braces {
}.

Accessin Accessed by Accessed by Accessed by


g specifying specifying specifying
array name
structure Union
with subscript
variablename.mem variablename.memb
bername ername

Memory Each array Each member of Memory is allocated


element the structure by considering the
Allocatio
occupies occupies unique size of largest
n
memory, location, stored in member. All the
stored in contigenous members share the
contigenous locations. common location
locations.

Size Size of the Size of the Size is given by the


array is structure depends size of largest
depending on on the type of member storage.
the array type members, adding
and size. size of all
members. sizeof(un_variable);
sizeof (st_var);
sizeof (arr);

251
Computer Programming & Data Structures

Using An array Structure members Same as structure.


pointers elements can be accessed by
values can be using de-
accessed by referencing
using de- operator dot
referencing operator and
operator(*) selection
operator(->)

We can have We can have We can have array


array of arrays as a as a member of
structures or member of union.
unions. here structures.
the array type
is structure or
union.

All elements All members can Only one member


can be be accessed at a can be accessed at a
accessed at a time time.
time

… Nesting of Same. It is possible


structures is union may contain
possible. It is structure as a
possible union with member
in structure as a
member.

Table 5.3: Difference Between Array, Structure and Union

5.9 TYPEDEF

C supports a feature known as “type definition” that allows users to


define an identifier that would represent an existing data type. Its
purpose is to redefine the name of an existing variable type.

The general syntax of the typedef is as follows,

252
Computer Programming & Data Structures

typedef data_type IDENTIFIER;

where,

 typedef is the keyword tells the compiler about the type


definition.
 data_type refers to an existing data type.
 IDENTIFIER refers the “new” name given to the data type.
 Usually, uppercase letters are used to make it clear that we
are dealing with a renamed data type

Note that using typedef, we are not creating new data types.
Instead we are creating only new name for the existing data type.
These new data type names are called user-defined data types.

Suppose we want to store marks scored in various subjects in


variables sub1, sub2 and sub3. These variables can be declared as
follows,

int sub1, sub2, sub3;

Using the user-defined data types, the variables can be declared as


shown below,

typedef int MARKS;

MARKS sub1, sub2, sub3;

Advantages

 Provides a meaningful way of declaring the variables.


 Increase the readability of the program.
 A complex declaration can be reduced to short and meaningful
declaration.
 typedef is widely used while dealing with structures.

253
Computer Programming & Data Structures

typedef with structures

using typedef, it is efficient way to define a structure. It can be


defined as follows,

typedef struct

type1 member1;

type2 member2;

254
Computer Programming & Data Structures

Following are examples of typedef structure

struct employee typedef struct employee

{ {

char name [30]; char name [30];

int age; int age;

float b_sal; float b_sal;

}; } EMP;

members can be accessed same way as normal structure. But here


we are creating new type. For the above example the type name is
EMP.

typedef can also be used to rename pointer data types as shown


below:

typedef struct employee

char name [30];

int age;

float bs;

The below program illustrates the definition of structure with


typedef, declaring variables and accessing members.

255
Computer Programming & Data Structures

256
Computer Programming & Data Structures

5.10 ENUMERATED TYPES

 We know that words speak more than numbers (as pictures


speak more than words).
 For example we may use integers 1, 2, 3,.. 12 to represent
months for easy programing.

257
Computer Programming & Data Structures

 It is more readable and understandable if we replace these


numbers by some meaningful and descriptive names such as
Jan, Feb… Dec.
 This concept of replacing integers by some descriptive names
gives rise to new data type called enumerated type.
 An enumerated data type is a user defined data type which
can take the integer values from a list.
 These integer values are replaced by meaningful and
descriptive names so as to enhance the readability of the
program.
 These descriptive names are called enumerators or
enumerator constants.

Declaring an Enumerated Type

To declare an enumerated type, we must declare its identifier and


its values. Because it is derived from integer type, its operations are
the same as for integers.

Syntax for defining an enumerated type is as follows,

enum type_Name

member1;

member2;

….

258
Computer Programming & Data Structures

Where,

 enum is the keyword tells the compiler about enumerated


type definition.
 enum type_Name together represent the user defined data
type.
 member1, member2… are integer constants but represented
using descriptive names. These are called enumerator
constants or enumerators.
 The definition terminated with a semicolon.

The syntax for declaring the variables are shown below,

enum type_Name var;

Following are some of the examples of enumerator type:

enum color enum days

{ {

RED, SUNDAY,

BLUE, MONDAY,

GREEN …

}; SATURDAY
259
Computer Programming & Data Structures

Assigning Values to Enumerated Types

After an enumerated variable has been declared, we can store


values in it. While, the compiler automatically assigns values to
enumerated types starting with 0, the next values are initialized
with a value by adding 1 to previous value.

For example, to set up an enumerated type for the rain status, we


could use the following program.

260
Computer Programming & Data Structures

We can override it and assign our own values, For example, for
example to make JAN start with 1 we could use the following
declaration

enum month

JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV,
DEC

} m1;

Note that we don’t have to assign initializes to every value. If we


omit the initializes, the complier assigns the next value by adding 1.

consider the following enumerated declaration,

enum days

sun=3, mon, tue, wed=0, thu, fri, sat

} d1, d2;

Observe that first enumerator sun=3, so for the subsequent


enumerators the compiler assigns 4, 5. Now the enumerators
mon=4, tue=5.

But, observe that the enumerator, wed is initialized to 0. SO, the


subsequent enumerators will have 1, 2, and so on. Now the
enumerators thu=1, fri=2, sat=3.

261
Computer Programming & Data Structures

Any manipulations done on integer variables can also done on the


variables d1 and d2.

Look at the following statements,

w1= sun; // is valid assignment

w2= 5; // is invalid assignment

It is also possible to associate typedef with enumerated type as


shown below,

typedef enum

sun=3, mon, tue, wed=0, thu, fri, sat

} DAYS;

DAYS d1, d2; // Declaring Variables

using typedef we can write more readable code. In this example,


we can say the variables d1 and d2 are of type DAYS.

262
Computer Programming & Data Structures

263
Computer Programming & Data Structures

264
Computer Programming & Data Structures

5.11 BIT FIELDS

If in a program a variable is to take only two values 1 and 0, we


really need only a single bit to store it. If a variable is to take
values from 0 to 3, then two bits are sufficient to store these
values. So, we cannot waste entire integer to store such data.

There are several variables whose max values are small enough to
pack into a single memory location. We can use ‘bit fields’ to store
several values in a single integer.

A bit field is a set of adjacent bits whose size can be from 1 to 16


bits length. A word can therefore be divided in to a number of bit
fields. The name and size of bit fields are defined using structure.
Since bit fields are defined within a structure, the various bits can
be accessed in a way we access individual members of a structure.

The general for or syntax for bit field definition as follows,

struct tag_Name

Unsigned int name1: bit_length;

Unsigned int name2: bit_length;

Where,
265
Computer Programming & Data Structures

 unsigned int is always used to define bit fields.


 bit_length is the number of bits used for the specified name.
 field name is followed by semicolon.

Remember that a signed bit field should have at least 2bits (1bit for
sign). The bit_length is decided by the range of value stored. The
largest value that can be stored is 2n-1, where n is bit_length.

The internal representation of bit fields is machine dependent.


Some machines store bits from left to right and others from right to
left. The below Figure 5.10 illustrates the layout of bit fields,
assuming a 16-bit word that is ordered from right to left.

name n ……………….. name 2


name 1

Figure 5.10: Bit Field Storage representation

There are several specific points to observe:

 The first field always starts with first bit of the word.
 A bit can not overlap integer boundaries. This is, the sum of
lengths of all fields in a structure should not be more than the
size of a word. In case, it is more, the overlapping field is
automatically forced to the beginning of the next word.
 There can be unnamed field declared with size. Example,
unsigned : bit_length;

Such fields provide within a word.

 There can be unused bits in a word.

266
Computer Programming & Data Structures

 We cannot take the address of a bit field variable.


 Bit fields cannot be arrayed.
 Bit fields should be assigned values that are the range of
their size.
// C program illustrates Bit Fields

267
Computer Programming & Data Structures

268
Computer Programming & Data Structures

Exercise Programs

1. Write a program using structures to display the following


information for each customer name, account number, street,
city, old balance, current payment, new balance, account
status.

2. Write a C program to accept records of the different states


using array of structures. The structure should contain char
state, population, literary rate, and income. Display the state
whose literary rate is highest and whose income is highest.

3. Define a structure type struct ABS, which contains name,


age, designation, and salary. Using this structure, write a C
program to read this information for one person from the
keyboard and print the same on the screen.

4. Write a C program using structure to read and print the


student’s records of a class with the following members.

Field Name Data Type

name string

reg no integer

major string

result string

269
Computer Programming & Data Structures

5. Write a C program to store the information of vehicles. Use bit


fields to store the status information. Assume the vehicle
object consists of type, fuel and model member fields.
Assume appropriate number of bits for each field.

6. Write a C program to compute the monthly pay of 100


employees using each employee’s name, basic-pay. The DA is
computed as 52% of the basic pay. Gross-salary (Basic
pay+DA). Print the employees name and gross salary.

7. Write a C program using structure to create a library


catalogue with the following fields; access number, author’s
name, title of the book, year of publication, publisher’s name,
and price.

8. Define a structure that can describe a hotel. It should have


members that include the name, address, grade, average
room charge, and number of rooms. Write a C program to
perform following operations:

(a) To print out hotels of a given grade in order of charges.

(b) To print out hotels with room charges less than a given
value.

9. Write a C program to read the information from the keyboard


in which the “Employee” structure consists of employee name,
code, designation and salary. Construct an array of structures
that stores n employee’s information and write a program to
carry out operations like inserting a new entry, deleting entry.

10. Design a structure to store length in kilometers, meters and


centimeters. Write a function to find the addition of two
measurements by passing two measurements as arguments
to a function.

270
Computer Programming & Data Structures

11. A company markets Hardware items. Create a structure


“hwItem” that stores the title of the item, its price, an array
of three floats so that it can record the sale in rupees of a
particular item for the last three months, category of the item
and it’s original equipment manufacturer. Write a short
program that provides facility to read N no. of items
information, append new item, and displays all records.

12. The annual examination is conducted for 50 students for


three subjects. Write a program to read the data and
determine the following:

(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the
student who secured it.

(c) The student who obtained the highest total marks.

13. Write a C program to accept records of the different states


using array of structures. The structure should contain char
state, population, literary rate, and income. Display the state
whose literary rate is highest and whose income is highest.

ASSIGNMENT V

1. Define Structure and write the general format for declaring


and accessing members.

271
Computer Programming & Data Structures

2. a) How bits are manipulated using bit fields in ‘C’ explain?


b) What is the use of typedef in structure declaration?

3. a) How Structure elements are accessed using pointer? Which


operator is used? Give an example
b) What is a self - referential structure? What kind of
applications it is used? Give example.

4. a) Describe nested structures. Draw diagrams to explain


nested structure.
b) How to compare structure variables? Give an example.

5. a) Distinguish between an array of structures and an array


within a structure. Give an example each.
b) Write a program to use structure within union. Display the
contents of structure elements.

6. Compare arrays, structures and unions.

6.0 INTRODUCTION

Reading, processing and writing of data are the three essential


functions of a computer program. Most programs take some data as
input and display the processed data, often known as result. Unlike
other high level languages, C does not have any built-in
input/output statements as part of its syntax.

A library of functions is supplied to perform these (I/O) operations.


The I/O library functions are listed the “header” file <stdio.h>. You
do not need to memorize them, just be familiar with them.

The I/O library functions can be classified into two broad categories:

Console I/O functions - functions to receive input from keyboard


and write output to VDU.

272
Computer Programming & Data Structures

File I/O functions – functions to perform I/O operations on a


floppy disk or a hard disk.

Console I/O Functions

Console I/O refers to the operations that occur at the keyboard and
screen of the computer. Because input and output to the console is
such a common affair, a subsystem of the ANSI I/O file system was
created to deal exclusively with console I/O. Technically, these
functions direct their operations to the standard input (stdin) and
standard output (stdout) of the system.

Console I/O functions are further divided into two categories:

1. Formatted console I/O functions —printf/scanf.

2. Unformatted console I/O functions – getchar, putchar etc.

Disadvantages

This works fine as long as the data is small. Real-world problems


involve large volumes of data and in such situations Console I/O
functions pose two major problems,

1. It becomes time consuming to handle large amount of


data.

2. Entire data is lost when either the program is terminated


or the computer is turned off.

At these times it becomes necessary to store the data in a manner


that can be later retrieved and displayed. This medium is usually a
‘file’ on the disk. This chapter discusses how file I/O operations can
be performed.

6.1 FILES

 A file is an external collection of related data treated as a unit.

 The primary purpose of a file is to keep record of data. Record


is a group of related fields. Field is a group of characters they
convey meaning.

273
Computer Programming & Data Structures

 Files are stored in auxiliary or secondary storage devices. The


two common forms of secondary storage are disk (hard disk,
CD and DVD) and tape.

 Each file ends with an end of file (EOF) at a specified byte


number, recorded in file structure.

 A file must first be opened properly before it can be accessed


for reading or writing. When a file is opened an object (buffer)
is created and a stream is associated with the object.

6.1.1 BUFFER

 When the computer reads, the data move from the external
device to memory; when it writes, the data move from
memory to the external device. This data movement often
uses a special work area known as buffer.

 A buffer is a temporary storage area that holds data while


they are being transferred to or from memory.

 The primary purpose of a buffer is to synchronize the physical


devices with a program's need.

6.1.2 FILE NAME

File name is a string of characters that make up a valid filename.


Every operating system uses a set of rules for naming its files.

When we want to read or write files, we must use the operating


system rules when we name a file. The file name may contain two
parts, a primary name and an optional period with extension.

Example: input.txt

program.c

6.1.3 FILE INFORMATION TABLE

A program that reads or write files needs to know several pieces of


information, such as name of the file, the position of the current
character in the file, etc..,
274
Computer Programming & Data Structures

C has predefined structure to hold this information. The stdio.h


header file defines this file structure; its name is FILE. When we
need a file in our program, we declare it using the FILE type.

6.1.4 STREAM

 A stream is a general name given to a flow of data.

 All input and output is performed with streams.

 A "stream" is a sequence of characters organized into lines.

 Each line consists of zero or more characters and ends with


the "newline" character.

 ANSI C standards specify that the system must support lines


that are at least 254 characters in length (including the new
line character).

 A stream can be associated with a physical device, terminal,


or with the file stored in memory. The following Figure 6.1
illustrates the data flow between external device(c Program),
buffer and file.

Buffer
//C program
abcdefg

..
Stream
abcdefg

File
Figure: 6.1 data flow

Text and binary Streams

 C uses two types of streams: text and binary.

 A text stream consists of a sequence of characters divided


into lines with each line terminated by a new line (\n).

275
Computer Programming & Data Structures

 A binary stream consists of sequence of data values such as


integer, real, or complex using their memory representation.

System Created Streams

 Standard input stream is called "stdin" and is normally


connected to the keyboard

 Standard output stream is called "stdout" and is normally


connected to the display screen.

 Standard error stream is called "stderr" and is also normally


connected to the screen.

6.2 STREAM FILE PROCESSING

A file exists as an independent entity with a name known to the


O.S. A stream is an entity created by the program. To use a file in
our program, we must associate the program’s stream name with
the file name.

In general, there are four steps to processing a file.

1. Create a stream

2. Open a file

3. Process the file (read or write data)

4. Close file

Creating a Stream

We can create a stream when we declare it. The declaration uses


the FILE type as shown below,

FILE *fp;

276
Computer Programming & Data Structures

The FILE type is a structure that contains the information needed


for reading and writing a file, fp is a pointer to the stream.

Opening File

Once stream has been created, we can ready to associate to a file.


In the next section we will discuss in detail.

Closing the Stream

When file processing is complete, we close the file. After closing the
file the stream is no longer available.

6.3 STANDARD LIBRARY I/O FUNCTIONS

C includes many standard functions to input data from the keyword


and output data to the monitor. For these functions, the stream that
connects our programs to the terminal is automatically created by
the system and we do not have to do anything more.

The stdio.h header file contains several different input/output


functions declarations. These are grouped in to eight different
categories, as shown in Figure 6.2.

277
Computer Programming & Data Structures

Figure 6.2 Categories of I/O functions

File Open and Close

In this section we discuss the C functions to open and close


streams.

File Open (fopen)

The function that prepares a file for processing is fopen. It does two
things: first, it makes the connection between the physical file and
the file stream in the program. Second, it creates a program file
structure to store the information needed to process the file as
shown in Figure 6.3

278
Computer Programming & Data Structures

C Program Buffer
#include<stdio.h> abcdefghijklmnopqrstu
vwxyz
void main () stream
{

….}

stream

File Structure abcdefghijklmnopqrstu


vwxyz
199 10212 10200 … …

1 2 3 ..

File

Figure 6.3 File open operations

File Structure

Some of the fields of file structure are

1) int count: counts bytes left in buffer.

2) char *ptr: pointer to the current buffer position.

3) char *base: pointer to buffer beginning.

To open a file, we need to specify the physical filename and its


mode.

Syntax,

fopen (“filename”, “mode”);

The file mode is a string that tells C compiler how we intend to use
the file: read existing file, write a new file or append to a file.

Successfully opening a file returns a pointer to (i.e., the address of)


a file structure. The actual contents of the FILE are hidden from our
view. All we need to know is that we can store the address of the
file structure and use it to read or write the file.

The statement: fptr1 = fopen (“mydata", "r”);

279
Computer Programming & Data Structures

Would open the file mydata for input (reading).

The statement: fptr2 = fopen ("results", "w”);

Would open the file results for output (writing).

Once the files are open, they stay open until you close them or end
the program (which will close all files.)

File Mode

When we open a file, we explicitly define its mode. The mode shows
how we will use the file: for reading, for writing, or for appending.

“r” (read) mode

The read mode (r) opens an existing file for reading. When a file is
opened in this mode, the file marker is positioned at the beginning
of the file (first character). The file marker is a logical element in
the file structure that keeps track of our current position in the file.

The file must already exist: if it does not, NULL is returned as an


error. Files opened for reading are shown in Figure 6.4. If we try to
write a file opened in read mode, we get an error message.

Syntax fp=fopen (“filename”,”r”);

“w” (write) mode

The write mode (w) opens for writing. If the file doesn’t exist, it is
created. IF it is already exists, it is opened and all its data are
erased; the file marker is positioned at the beginning of the file
(first character) It is an error to try to read from a file opened in
write mode. A file opened for writing is shown in figure 6.4.

Syntax fp=fopen (“filename”,”w”);

“a” (append) mode

The append mode (a) also opens an existing for writing. Instead of
creating a new file, however, the writing starts after the last
character; that is new data is added, or appended, at the end of the
file.

280
Computer Programming & Data Structures

IF the file doesn’t exist, it is created and opened. In this case, the
writing will start at the beginning of the file; File opened in append
mode are shown in Figure 6.4.

Syntax fp=fopen (“filename”,”a”);

“r+” (read and write) mode

In this mode file is opened for both reading and writing the data. If
a file does not exist then NULL, is returned.

Syntax: fp=fopen (“filename”,”r+”);

“w+” (read and write) mode

In this mode file is opened for both writing and reading the data. If
a file already exists its contents erased. If a file does not exist then
new file created.

Syntax: fp=fopen (“filename”,”w+”);

“a+” (append and read) mode

In this mode file is opened for reading the data as well as data can
be added at the end.

Syntax: fp=fopen (“filename”, “a+”);

Figure 6.4 File Opening Modes

The above figure shows the file marker position in different modes.

File Close (fclose)

281
Computer Programming & Data Structures

 Closing a file ensures that all outstanding information


associated with the file is flushed out from the buffers and all
links to the file are broken.

 Another instance where we have to close a file is to reopen


the same file in a different mode.

 The I/O library supports the following function to do this:

fclose (file_pointer);

 Where fp is the file pointer returned by the call to fopen ().

 fclose () returns 0 on success (or) -1 on error.

 Once a file is closed, its file pointer can be reused for another
file.

282
Computer Programming & Data Structures

6.4 FORMATED I/O FUNCTIONS

We have already familiar with two formatting functions scanf and


printf. These two functions can be used only with the keyboard and
monitor. The C library defines two more general functions, fscanf
and fprintf, that can be used with any txt stream.

Formatted Output with printf ()

283
Computer Programming & Data Structures

 This function provides for formatted output to the screen.


The syntax is:

printf (“format string”, var1, var2 …);

 The “format string” includes a listing of the data types of the


variables to be output and, optionally, some text and control
character(s).

 Example:

float a=10.5; int b=15;

printf (“You entered %f and %d \n”, a, b);

Format Conversion Specifiers

d -- displays a decimal (base 10) integer

l -- used with other Specifiers to indicate a "long"

e -- displays a floating point value in exponential notation

f -- displays a floating point value

g -- displays a number in either "e" or "f" format

c -- displays a single character

s -- displays a string of characters

Formatted Input with scanf ()

 This function provides for formatted input from the keyboard.


The syntax is:

scanf ( “format string” , &var1, &var2, …) ;

 The “format string” is a listing of the data types of the


variables to be input and the & in front of each variable name
tells the system Where to store the value that is input.

 It provides the address for the variable.

 Example:

284
Computer Programming & Data Structures

float a; int b;

scanf (“%f %d”, &a, &b);

Reading From Files: fscanf ()

 The general format of fscanf() is,

fscanf (stream_pointer,”format string”, list);

 The first argument is the stream pointer, is the pointer to the


streams that has been declared and associated with a text
file. Remaining is same as scanf function arguments.

 The following example illustrates the use of an input stream.

int a, b;

FILE *fptr1;

fptr1 = fopen (“mydata", "r”);

fscanf (fptr1, "%d %d", &a, &b);

 The fscanf function would read values from the file "pointed"
to by fptr1 and assign those values to a and b.

 The only difference between scanf and fscanf is that scanf


reads data from the stdin (input stream) and fscanf reads
input from a user specified stream(stdin or file).

 The following example illustrates how to read data from


keyboard using fscanf,

fscanf (stdin,”%d”, &a);

End of File

The end-of-file indicator informs the program when there are no


more data (no more bytes) to be processed. There are a number of
ways to test for the end-of-file condition. Another way is to use the
value returned by the fscanf function: The following example
illustrates testing of end of file.

285
Computer Programming & Data Structures

Writing To Files: fprintf ()

286
Computer Programming & Data Structures

 Can handle a group of mixed data simultaneously.

 The first argument of these functions is a file pointer which


specifies the file to be used.

 The general form of fprintf is

fprintf (stream_pointer, ”format string”,


list);

 Where stream_pointer is a file pointer associated with a file


that has been opened for writing.

 The format string contains output specifications for the items


in the list.

 The list may include variables, constants and strings.

 The following example illustrates the use of an Output stream.

int a = 5, b = 20;

FILE *fptr2;

fptr2 = fopen (“results", "w”);

fprintf (fptr2, "%d %d\n", a, b) ;

 The fprintf functions would write the values stored in a and b


to the file "pointed" to by fptr2.

 fprintf function works like printf except that it specifies the file
in which the data will be displayed. The file can be standard
output (stdout) or standard error (stderr) also.

 Example,

fprintf (stdout,”%d”,45); displays 45 on Monitor.

287
Computer Programming & Data Structures

// OUTPUT

// Contents of File testdata.txt

288
Computer Programming & Data Structures

6.5 CHARACTER I/O FUNCTIONS

Character input functions read one character at a time from a text


stream. Character output functions write one character at the time
to a text stream.

These functions can be divided into two categories,

1. Terminal Character I/O

2. Terminal and File Character I/O

6.5.1 TERMINAL CHARACTER I/O

C declares a set of character input/output functions that can only be


used with the standard streams: standard input (stdin), standard
output (stdout).

Read a Character: getchar ()

This function is to read exactly one character from the keyboard; it


reads the next character from the standard input stream.

Syntax for using getchar () function is as follows,

ch =getchar ();

Its return value is integer. Up on successful reading returns the


ASCII value of character. If there is an error returns EOF.

Write a Character: putchar ()

289
Computer Programming & Data Structures

This function provides for printing exactly one character to the


Monitor.

Syntax for using putchar () function is as follows,

ch =getchar (); /* input a character from keyboard*/

putchar (ch); /* display character on the Monitor */

Its return value is integer. Up on successful writing returns the


ASCII value of character. If there is an error returns EOF.

6.5.2 TERMINAL AND FILE CHARACTER I/O

The terminal character input/output functions are designed for


convenience; we don’t need to specify the stream. Here, we can use
a more general set of functions that can be used with both the
standard streams and a file.

These functions require an argument that specifies the stream


associated with a terminal device or a file.

 When used with a terminal device, the streams are declared


and opened by the system, the standard input stream (stdin)
for the keyword and standard output stream (stdout) for the
monitor.

 When used with a file, we need to explicitly declare the


stream, it is our responsibility to open the stream and
associate with the file.

Read a Character: getc () and fgetc ()

The getc functions read the next character from the file stream,
which can be a used-defined stream or stdin, and converts it in to
an integer. This function has one argument which is the file pointer
declared as FILE.

If the read detects an end of file, the function returns EOF, EOF is
also returned if any error occurs. The functionality of getc/fgetc
same.

290
Computer Programming & Data Structures

Syntax for using getc/fgetc,

getc (fp);

fgetc (fp);

Example,

char ch;

ch = getc (stdin); /* input from keyboard */

ch =fgetc (fileptr); /* input from a file */

Write a Character: putc () and fputc ()

The putc functions write a character to the file stream specified


which can be a user-defined stream, stdout, or stderr. The
functionality of putc/ fputc same.

For fputc, the function takes two arguments. The first parameter is
the character to be written and the second parameter is the file,
The second parameter is the file pointer declared as FILE.

If the character is successfully written, the function returns it. If any


error occurs, it returns EOF.

Syntax,

putc (char, *fp);

fputc (char, *fp);

Example,

char ch;

ch = getc (stdin); /* input from keyboard */

putc (ch, stdout); /* output to the screen */

putc (ch, outfileptr); /*output to a file */

291
Computer Programming & Data Structures

292
Computer Programming & Data Structures

6.6 LINE I/O FUNCTIONS

Reading Strings: gets () and fgets ()

The gets and fgets function take a line (terminated by a new line)
from the input stream and make a null-terminated string out of it.
These are sometimes called line-to-string input function.

gets ()

 gets function reads a string from terminal, reading is


terminated by new line.

293
Computer Programming & Data Structures

 The newline (\n) indicates the end of the string, it is replaced


by null (\0) character in the memory by the function gets ()
as shown in Figure 6.5.

 The source of data for the gets function is standard input.

 gets function takes only one parameter, the name of the


string, its syntax is as follows,

gets (string_name);

Figure 6.5 Working of gets/fgets functions

fgets ()

 fgets function reads a string from file or keyboard.

 It reads characters from the specified file until a new line


character has been read or until n-1 characters has been
read, whichever occurs first. The function automatically places
null character at the end as shown in Figure 6.5.

 The source of data for fgets can be a file or standard input.

 The general format,

fgets (string, length, fp);

 First argument is name of the string in which the read data


from the file is to be placed. Second argument is the length of
the string to be read and last argument is the file pointer.

294
Computer Programming & Data Structures

 fgets also reads data from terminal. Below example illustrates


this,

fgets (str, 10, stdin);

295
Computer Programming & Data Structures

Writing Strings: puts () and fputs ()

puts/fputs functions take a null-terminated string from memory and


write it to a file or the monitor. These are sometimes called string-
to-line output functions.

puts ()

296
Computer Programming & Data Structures

 puts function writes a string to terminal, writing is terminated


by null character. the null character is replaced with a new
line inputs as shown in Figure 6.6.

 puts function takes only one parameter, the name of the


string, its syntax is as follows,

puts (string_name);

fputs ()

 fputs function writes a string to a file or monitor.

 Characters stored in the string are written to the file identified


by fileptr until the null character is reached. The null character
is not written to the file as shown in Figure 6.6.

 The general format forms are

fputs (string, fp);

 First argument is address of the string in which the read data


is to be placed. Second argument is the file pointer.

Figure 6.6 Working of puts/fputs Functions

297
Computer Programming & Data Structures

// output

298
Computer Programming & Data Structures

// Contents of file writedat.txt

6.6.1 STRING/DATA CONVERSION FUNCTIONS

A common set of applications format data by either converting a


sequence of characters into corresponding data types or vice versa.
C already has set of data conversion functions created for scanf and
printf. The C standard also includes two sets of memory formatting
functions: sscanf and sprintf.

String to Data Convertion: sscanf ()

The string scan function is called sscanf. sscanf is a one-to-many


function. It splits one string into many variables.

This function scans a string through the data were coming from a
file. Just like fscanf, it requires a format string to provide the
formatting parameters for the data.

Instead of reading these data from the keyboard, we can also read
from a string stored in memory using sscanf ().

299
Computer Programming & Data Structures

Syntax,

sscanf (string, “control string”, variables);

The first argument is the string, which contains the data to be


scanned. The second is the control string consisting of format
Specifiers. Variables, it is a list of variables in to which formatted
data is copied.

Its return value is integer. If the sscanf () is successful it returns


how many variables formatted. The error is specified with EOF.

Figure 6.7 Working of sscanf Function

Example,

sscanf (“hyd 45 67.89”, “%s %d %f”, name, &a, &b);

Would result in name=hyd, a=45 and b=67.890000

Data to String Convertion sprintf ()

The string print function is sprintf, follows the rules of fprintf. Rather
than sending the data to a file. however, it simply “writes” them to
a string. When all data have been formatted to the string, a
terminating null character is added to make the result a valid string.
If an error is detected, sprintf returns any negative value or EOF. If
the formatting is successful, it returns number of characters
formatted.

300
Computer Programming & Data Structures

Figure 6.8 Working of sscanf Function

Syntax,

sprintf (string, “control string”, variables);

The first argument is the string, which contains the data to written.
The second is the control string consisting of format Specifiers.
Variables, it is a list of variables in to which formatted data is
copied.

Example,

sprintf (str,”%s %d %f”, name, a, b);

will result in str =name + a + b.

301
Computer Programming & Data Structures

6.7 TEXT FILES AND BINARY FILES

Text File

A text file is the one where data is stored as a stream of characters


that can be processed sequentially. In the text format, data are
organized into lines terminated by newline character. The text files
are in human readable form and they can be created and read using
any text editor. Since text files process only characters, they can
read or write only one character at a time. A new line may be
converted to carriage return and line feed character. Figure 6.9
shows the data transfer in text file.

302
Computer Programming & Data Structures

Figure 6.9 Reading and Writing Text Files

Because of these translations, the number of characters written /


read may not be the same as the number of characters written /
read on the external device. Therefore, there may not be a one –
to – one relationship between the characters written / read into the
file and those stored on the external devices.

For example, the data 2345 requires 4 bytes with each character
occupying exactly one byte. A text file cannot contain integers,
floating – point numbers etc. converted to their character –
equivalent formats.

Binary File

A binary file is the one where data is stored on the disk in the same
way as it is represented in the computer memory. The binary files
are not in human readable form and they can be created and read
only by specific programs written for them. The binary data stored
in the file cannot be read using any of the text editors.

Figure 6.10 Block Input and Output

For example, the data 2345 takes 2 bytes of memory and is stored
as 0 x 0929 i.e., 0 x 09 is stored as one byte and 0 x 29 is stored as
other byte. The number of characters written / read is same as the
303
Computer Programming & Data Structures

number of characters written / read on the external device.


Therefore, there is one to – one relationship between the characters
written / read into the file and those stored on the external devices.

Differences between Text File and Binary File

The differences between text file and binary file are as shown in
Table 6.1. The following Figure 6.11 illustrates the storage
difference between text file and binary file.

Figure 6.11 Binary and Text Files

Text File Binary File

1. Human readable format. 1. Not in human readable format.

2. Data is stored as lines of 2. Data is stored on the disk in the same way
characters with each line it is represented in the computer memory.
terminated by / n which may
be translated into carriage
return + line feed.

3. Translation of new line 3. No translation of any type.


character to carriage return +
line feed.

4. Data can be read using any 4. Data can be read only by specific program
of the text editors. written for them.

5. The number of characters 5. The number of characters written / read


written / read may not be the same as the number of characters written / re
same as the number of on the external device such as disk.
characters written/read on the
external device such as disk.

6. There may not be a one – 6. There is one – to – one relationship betwe


304
Computer Programming & Data Structures

to- one relationship between the characters written / read into the file a
the characters written / read those stored on the external devices.
into the file and those stored
on the external devices.

7. The data 2345 requires 4 7. The data 2345 requires 2 bytes and stored
bytes with each character 0x0929. The data 2345 is requiring 2 bytes.
requiring one byte. So, it is
stored as 0x 32, 0x 33, and 0 x
34, 0 x 35 (ASCII values) thus
requiring 4 bytes.

Table 6.1 Differences between Text File and Binary File

Opening Binary Files

The basic operation is unchanged for binary files-only the mode changes. Different modes of
operation of binary file are illustrated in Table 6.2.

Mode Meaning

wb This mode opens a binary file in write mode.

Example: fp=fopen (“data.dat”,”wb”);

rb This mode opens a binary file in read mode.

Example: fp=fopen (“data.dat”,”rb”);

ab This mode opens a binary file in append mode.

Example: fp=fopen (“data.dat”,”ab”);

w+b This mode opens/creates a binary file in write and


read mode.

Example: fp=fopen (“data.dat”,”w+b”);

r+b This mode opens a pre-existing binary file in read


and write mode.

Example: fp=fopen (“data.dat”,”r+b”);

a+b This mode opens/creates a binary file in append

305
Computer Programming & Data Structures

mode.

Example: fp=fopen (“data.dat”,”a+b”);

Table 6.2 Binary Modes of Opened File

Just like text files, binary files must be closed when they are not
needed anymore using fclose ().

6.8 BLOCK I/O FUNCTIONS

C language uses the block input and output functions to read and
write data to binary files. As we know that data are stored in
memory in the form of 0’s and 1’s. When we read and write the
binary files, the data are transferred just as they are found in
memory and hence there are no format conversions. The block read
function is file read(fread). The block write function is file write
(fwrite).

File Read: fread ()

This function reads a specified number of bytes from a binary file


and places them into memory at the specified location. This function
declaration is as follows,

int fread (void *pInArea, int elementsize, int count,


FILE *sp);

The first parameter, pInArea, is a pointer to the input area in


memory. The data read from the file should be stored in memory.
For this purpose, it is required to allocate the sufficient memory and
address of the first byte is stored in pInArea. We say that pInArea
now points to buffer.

The next two elements, elementSize and count, are multiplied to


determine how much data are to be transferred. The size is
normally specified using the sizeof operator and the count is
normally one when reading structures. The last argument is the
pointer to the file we want to read from.

This function returns the number of items read. If no items have


been read or when error has occurred or EOF encountered, the
function returns 0.
306
Computer Programming & Data Structures

File read expects a pointer to the input area, which is usually a


structure. This is because binary files are most often used to store
structures.

Figure 6.12 is an example of a file read that reads data into an


array of integers. When fread is called, it transfers the next three
integers from the file to the array, inArea.

Figure 6.12 File Read Operation

File Write: fwrite ()

This function writes specified number of items to a binary file. This


function declaration is as follows,

int fwrite (void *pInArea, int elementsize, int count, FILE


*sp)

The parameters for file write correspond exactly to the parameters


for the file read function. Figure 6.13 shows the write operation that
parallels the read in Figure 6.12.

307
Computer Programming & Data Structures

Figure 6.13 File Write Operation

6.9 FILE POSITIONING FUNCTIONS

File positioning functions have two uses. First, for randomly


processing data in disk files, we need to position the file to read the
desired data. Second, we can use the positioning functions to
change a file’s state. Thus, we can change the state of the file
pointer using one of the positioning functions.

There three file position functions,

 tell location

 rewind file

 file seek

Current Location: ftell ()

 The ftell function reports the current position of the file


marker in the file, relative to the beginning of the file.

 ftell () takes a file pointer and returns a number of type long


integer, that corresponds to the current position.

 Here the return type is long integer because many files have
more than 32,767 bytes. The operation ftell is graphically
shown in Figure 6.14.

 The syntax of ftell function as follows,


n=
ftell(fp);

308
Computer Programming & Data Structures

 n would give the relative offset of the current position. This


means that n bytes have already been read (or written).

 If ftell encounters an error, it returns -1.

 Let us consider the following statement,

n=ftell (fp);

Figure 6.14 Working of ftell Function

 The above Figure 6.14 illustrates the working of ftell, it


returns 16, and the current offset value.

 The primary purpose of ftell is to provide a data address


(offset) that can be used in a file seek. It is especially helpful
when we are dealing with text file for which we cannot
calculate the position of data.

Rewind File: rewind ()

 The rewind function simply sets the file position indicator to


the beginning of the file as shown in Figure 6.15.

 This function helps us in reading a file more than once,


without having to close and open the file.

 Its common use is to change a work from a write state to a


read state. However, that to read and write a file with only
one open, we must open it in update mode w+.

 Syntax to use rewind function is as follows,

rewind (fp);

309
Computer Programming & Data Structures

 Example:

rewind (fp);

n=ftell (fp);

Would assign 0 to n because the file position has been set to the
start of the file by rewind.

Figure 6.15 Working of ftell Function

Set Position: fseek ()

 fseek () function is used to move the file position to a desired


location within the file.

 It takes the following form:

fseek (file_ptr, offset, position);

 file_ptr is a pointer to the file concerned, offset is a number or


variable of type long, and position is an integer number.

 The offset specifies the number of positions to be moved from


the location specified by position.

 The position can take one of the following three values:

310
Computer Programming & Data Structures

Value Meaning

0 beginning of file.

1 Current position.

2 End of file.

 The offset may be positive, meaning move forwards, or


negative, meaning move backwards.

 The following Table 6.3 illustrate operations of the fseek() function:

Statement Meaning

fseek(fp,0L,0); go to the beginning.

fseek(fp,0L,1); stay at the current position.

fseek(fp,0L,2); go to the end of the file, past the last

character of the file.

fseek(fp,m,0) move to (m+1) th byte in the file.

fseek(fp,m,1); go forward by m bytes.

fseek(fp,-m,1); go backward by m bytes from

the current position.

fseek(fp,-m,2); go backward by m bytes from the


end. (positions the file to the
character from the end.)

Table 6.3 Operations of the fseek function

 When the operation is successful, fseek returns a zero.

 If we attempt to move the file pointer beyond the file


boundaries, an error occurs and fseek returns -1.

311
Computer Programming & Data Structures

312
Computer Programming & Data Structures

// contents of input.txt

// output

313
Computer Programming & Data Structures

6.10 FILE STATUS FUNCTIONS

C provides functions for error handling during I/O operations.


Typical error situations include:

 Trying to read beyond the end-of-file mark.

 Device overflow.

 Trying to use a file that has not been opened.

 Trying to perform an operation on a file, when the file is


opened for another type of operation.

 Opening a file with an invalid filename.

 Attempting to write to a write-protected file.

We have two status-inquiry library functions, feof () and ferror ()


that can help us detect I/O errors in the files.

Test End of Files: feof ()

 The feof function can be used to test for an end of file


condition.

 It takes a FILE pointer as its only argument.If all data have


been read, the function returns a nonzero (positive value) and
returns zero (false) otherwise.

 It takes of the following form,

n=feof (fp);
314
Computer Programming & Data Structures

 If fp is a pointer to file that has just been opened for reading,


then the statement

if (feof (fp))

printf (“End of data.\n”);

 Would display the message “End of data” on reaching the end


of file condition.

Test Error: ferror ()

 The ferror function reports the status of the file indicated.


Error can be created for many reasons, such as trying to read
a file in the write state.

 It takes of the following form.

n=ferror (fp);

 It also takes a FILE pointer as its argument and returns a non


zero integer if an error has been detected up to that point,
during processing. Otherwise, it returns zero.

 The statement
if(ferror(fp)!=0)

printf (“An error has occurred.\n”);

 Would print the error message, if the reading is not


successful.

However, that testing for an error not reset the error condition.
Once a file enters the error state. It can only return to a read or
write state by calling clear error function: clearerr.

It takes of the form

clearerr (fp); // clears the error information

6.11 COMMAND LINE ARGUMENTS

Command line arguments are parameters supplied to a program,


when the program is invoked.

315
Computer Programming & Data Structures

C language provides a way to connect to the arguments on the


command line needed for the execution of the program. During
execution, arguments can be passed to the main () function through
command-line arguments. The first parameter treated as name of
the file.

In order to access the command-line arguments, the main function


has a prototype as shown below,

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

The first parameter argc stands for the argument count, which is of
integer data type. Its value is the number of arguments in the
command line that was used to execute the program.

The second parameter argv stands for the argument vector. It is an


array of pointers to the character data type. The program name is
the first parameter on the command line, which is argv [0].

// C program illustrates Command Line Arguments

#include<stdio.h>

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

int j;

printf (“The name of the program is %s”, argv[0]);

printf (“The total number of arguments are: %d”, argc);

for (j=1; j<=argc; j++)


OUTPUT:
printf (“\none
C:\tc\bin\>test argument %d is %s’, j, argv[j]);
two three
return
The name of 0;
the program is test
}
The total number of arguments are:4

argument 1 is one

argument 2 is two

argument 3 is three

316
Computer Programming & Data Structures

Exercise Programs

1. Write a program to read the following data, to find the value


of each item and display the contents of the file.

Item Code Price Quantity

Pen 101 Rs. 20 5

Pencil 103 Rs. 3 100

2. Write a C program to read a text file and to count

(a) number of characters,

(b) number of words and

(c) number of sentences and write in an output file.

3. Write a program to open a pre-existing file and add


information at the end of file. Display the contents of the file
before and after appending.

4. Write a C program to read last ‘n’ characters of the file using


appropriate file function.

317
Computer Programming & Data Structures

5. Write a C program to read a text file and convert the file


contents in capital (upper-case) and write the contents in a
output file.

6. Write a C program to replace every 5th character of the data


file, using fseek ( ) command.

7. Write a program to read the contents of three files and write


the file with largest number of characters into an output file.

8. Write a C program to read information about the student


record containing student’s name, student’s age and student’s
total marks. Write the marks of each student in an output file.

ASSIGNMENT VI

1. a) Distinguish between text mode and binary mode operation


of a file.
b) Write short notes on Block I/O Functions

2. What are the file I/O functions in C. Give a brief note about
the task performed by each function?

3. Explain the following operations

a) fseek()
b) ftell()
c) rewind()
d) ferror()
e) feof()

4. Write the syntax for opening a file and closing a file. Explain
different modes of operation of a file.

318
Computer Programming & Data Structures

319

Potrebbero piacerti anche