Sei sulla pagina 1di 128

LECTURE NOTES

ON

COMPUTER PROGRAMMING

B.TECH CSE I YEAR I SEMESTER


(JNTUA-R15)

Ms.K.Sirisha
Asst.Professor

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


CHADALAWADA RAMANAMMA ENGINEERING COLLEGE
CHADALAWADA NAGAR, RENIGUNTA ROAD, TIRUPATI (A.P) - 517506

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 1


2015-2016
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
ANANTHAPURAMU
I B.Tech. I - Semester
(15A05101) COMPUTER PROGRAMMING
(Common to All Branches)
Objectives:

e
UNIT - I
Overview of Computers and Programming - Electronic Computers Then and Now – Computer
Hardware - Computer Software - Algorithm - Flowcharts - Software Development Method –
Applying the Software Development Method.
Types, Operators and Expressions: Variable Names - Data Types and Sizes - Constants -
Declarations - Arithmetic Operators - Relational and Logical Operators - Type Conversions -
Increment and Decrement Operators - Bitwise Operators - Assignment Operators and Expressions -
Conditional Expressions - Precedence and Order of Evaluation.
UNIT - II
Selections Statements – Iteration Statements – Jump Statements- Expression Statements – Block
Statements.
Single Dimensional Arrays – Generating a Pointer to an Array – Passing Single Dimension Arrays to
Functions – Strings – Two Dimensional Arrays – Indexing Pointers – Array Initialization – Variable
Length Arrays
UNIT - III
Pointer Variables – Pointer Operators - Pointer Expressions – Pointers And Arrays – Multiple
Indirection – Initializing Pointers – Pointers to Functions – C‟s Dynamic Allocation Functions –
Problems with Pointers.
Understanding the scope of Functions – Scope Rules – Type Qualifiers – Storage Class Specifiers-
Functions Arguments –The Return Statement.
UNIT - IV
Command line arguments – Recursion – Function Prototypes – Declaring Variable Length Parameter
Lists
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 2
Structures – Arrays of Structures – Passing Structures to Functions – Structure Pointers – Arrays and
Structures within Structures – Unions – Bit Fields – Enumerations – typedef
UNIT - V
Reading and Writing Characters – Reading and Writing Strings – Formatted Console I/O – Printf -
Scanf – Standard C Vs Unix File I/O – Streams and Files – File System Basics – Fread and Fwrite –
Fseek and Random Access I/O – Fprintf ( ) and Fscanf( ) – The Standard Streams – The
Preprocessor Directives #define and #include.
Text Books:
1. “The Complete Reference C”- Fourth Edition- Herbert Schildt- McGrawHill Eduction.
2. “The C Programming Language” Second Edition- Brain W. Kernighan- Dennis M. Ritchie-
Prentice Hall-India. (UNIT- I)
References:
1. Programming in C, Second Edition – Pradip Dey, Manas Ghosh, Oxford University Press.
2. “C From Theory to Practice”- George S. Tselikis- Nikolaos D. Tselikas- CRC Press.
3. “Programming with C”- R S Bichkar- University Press.
4. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A.Ananda Rao,
Pearson Education. (UNIT-I)
5. Computer Fundamentals and C Programming- Second Edition- P.Chenna Reddy.
Outcomes:
s in designing the solutions for a wide-range of problems

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 3


UNIT -I

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 4


UNIT - I
Overview of Computers and Programming - Electronic Computers Then and Now – Computer Hardware -
Computer Software - Algorithm - Flowcharts - Software Development Method – Applying the Software
Development Method.
Types, Operators and Expressions: Variable Names - Data Types and Sizes - Constants -Declarations -
Arithmetic Operators - Relational and Logical Operators - Type Conversions -Increment and Decrement
Operators - Bitwise Operators - Assignment Operators and Expressions -Conditional Expressions -
Precedence and Order of Evaluation.
1.Electronic computers then and Now
Evolution of Modern Computers from the olden days is known as “Generation of
Computers.” Generations of computers are broadly classified based on the following
characteristics:
ÿ Increasing in storage capacity.
ÿ Increasing in processing speed.
ÿ Increasing reliability.
There are totally 5 generations of computers till today.
1.1 First Generation Computers:
Period: (1945-1955)
Technology: Vacuum tubes
The ENIAC was the first computer developed in this generation. It was capable of
performing 5000 additions (or) 350 multiplications per second. It uses about 18000 vacuum tubes
and it consumes 150 kw/hr.
Limitations:
The limitations of first generation computers are as follows.
ÿ Less operating capacity.
ÿ High power consumption.
ÿ Very large space requirement.
ÿ Produce high temperature.
ÿ Very costly.

1.2 Second Generation Computers:


Period: (1955-1965)
Technology: Transistors

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 5


ÿ The second generation computers use transistors as the main component in CPU. They are
very small in size when compared to vacuum tubes and produce less heat. They are fast and
reliable.
ÿ Due to this invention of Transistors the size, maintenance cost, power consumption has
decreased.
ÿ During this period magnetic storage devices have been started there development. Because
of this, speed and storage capacity has been increased. They are capable to perform 20,000
to 50,000 additions per second.
1.3 Third Generation Computers:
Period: (1965-1975)
Technology: Integrated Circuits {IC}
ÿ In this generation the computers used integrated circuits instead of Transistors
ÿ Integrated circuit is a miniature form of an electronic circuit made of silicon and enclosed
in a metal package.
ÿ These IC’s are caused “chips.” The cost and size of the computers were greatly reduced.
The magnetic disk technology has improved rapidly. It has capable to perform 10 million
additions per second.
1.4 Fourth Generation Computers:
Period: (1975-1990)
Technology: Very Large Scale Integrated Circuit (VLSI)
ÿ IC’s packing nearly 10,000 transistors are grouped in to a single silicon chip known as
“microprocessor”. The computers which use micro processors are called “Micro Computers”.
ÿ Intel Corporation invented the micro processor in the year 1980 with this development the
cost of a computer has reduced a lot.
ÿ The floppy disk technology was developed during this generation.
1.5 Fifth Generation Computers:
Period: (1990- till date)
Technology: Artificial Intelligence
ÿ Artificial Intelligence is a technique by which we make the computer to think and take
decisions in its own.
ÿ These computers are under research.
ÿ Artificial Intelligence can be achieved by means of problem solving, Game playing, and
Expert systems.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 6
2. Computer Hardware
Hardware:-
ÿ The physical components of a computer are known as hardware.
ÿ CPU , RAM , hard disk ,key board, mouse etc constitute the hardware.
ÿ It represents the physical and tangible components of a computer system i.e., the components
that can be seen and touched.
Input Unit:
Computers need to receive data and instructions in order to solve any problem.
ÿ The input unit consists of one or more input devices like keyboard, mouse, joystick etc.
ÿ Regardless of the type of the input device used in a computer system, all input devices
perform the following functions.
o Accept the data
o Convert data to computer understandable form.
o Supply converted data for further processing.
Key Board:
ÿ An important data entry device is the keyboard, which is a type writer like device.
ÿ Internally a keyboard contains a matrix of switches, [one switch per key] and a key board
controller.
ÿ Through pressing and Releasing of Switches, key board controller generates a scan code. This
scan code is sent to personal Computer [pc].
ÿ The PC has another controller which converts the received scan code into a specific character.
ÿ It includes functional keys, special keys[page up, page down, Home, Delete, Insert, End, Arrow
keys] and Toggle keys [ctrl, shift, caps].
Mouse:
ÿ The Mouse is a pointing device that fits under palm of a hand.
ÿ It controls movement of pointer called “mouse pointer” on the screen.
ÿ When a mouse moves on a flat surface, the cursor on the screen also moves in the direction of
mouse’s movement.
ÿ A mouse generally has two or three buttons and it may or may not have a wheel [scroller].
CPU:
ÿ CPU stands for “Central Processing Unit.”
ÿ CPU is like a computer Brain. It performs the following operations.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 7


o It performs all calculations.
o It takes all decisions.
o It controls all units of computer.
ÿ Control unit, Memory unit and Arithmetic logic unit of the computers are together known as
central processing unit.
Memory Unit:
ÿ Memory Unit of the computer holds data and instructions that we enter through the input
unit.
ÿ It is also used to preserve intermediate and final results before they are sent to the output unit.
ÿ It is used to preserve the data for later usage.
ÿ The various storage devices used for storage can be classified in to a categories namely
o Primary Memory
o Secondary Memory
ÿ Primary memory stores and provides information very fast but it loses the contents when we
switch off the computer.
ÿ Secondary memory stores the data permanently. The program that we want to run on the
computer is first transferred to the primary memory from secondary.
Control Unit:
ÿ The control unit controls all other units in the computer.
ÿ The control unit instructs the input unit where to store data after receiving it from the user.
ÿ It also controls the flow of data and instructions from the memory unit to “ALU”.
ÿ It controls the flow of results from ALU to output unit.
Arithmetic Logic Unit:
ÿ All calculations are performed in ALU.
ÿ It does comparisons and takes decisions.
ÿ It can perform Basic Arithmetic operations like addition, subtraction as well as logical
operations like less than greater than.
ÿ After performing calculations the result is stored in memory unit.
Output Unit:
ÿ The output unit of a computer provides information and results of an operation to the outside
world.
ÿ The output unit also converts Binary data to a form that uses can understand.
ÿ The commonly used to output devices are Monitors, Printers, and Plotters.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 8
Monitors:
ÿ Monitors (or) screen are the most common output form of a computer. It is also
called VDU {Visual Display Unit}.
ÿ It displays information in a similar way to that shown on television screen.
ÿ The picture on, monitor is made of 1000 of tiny colored data’s called “pixels”.
ÿ The 2 most common types of monitors are
o Cathode Ray Tube Monitors [CRT]
o Liquid Crystal Display Monitors [LCD]
CRT Monitors:
ÿ The CRT works in the same way as television. It contains an electron gun at the
back of glass tube.
ÿ This fails electrons on phosphorous coat screen, when electron strikes the
phosphorous screen. It glows to give the color.
LCD Monitors:

ÿ This is smaller and lighter than the CRT which makes them for use with portable
laptops and palmtops.
ÿ It is also called TFT display [Thin Film Transistors].
ÿ CRT monitors are big and require lot of power where as LCD’s use less power
and occupies less space.
Printers:
ÿ It is a hard copy output device. They can produce text and images on paper. They
can produce both color and black & white prints.
ÿ It can be divided in to two categories.
Impact printers:
ÿ In these printers, there is a mechanical contact between the print head and paper.
ÿ They are having low operating speed and can print on continuous stationary.
ÿ They are having low resolution i.e., print quality is poor. They are very slow and
very noisy.
ÿ The impact printers come in lot of varieties, important two types of printers are
o Dot-Matrix printer
o Drum printer

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 9


Dot-Matrix Printers:
ÿ It is the most popular serial printer i.e., prints one character at a time.
ÿ The head moves across the paper against an inked ribbon to form a pattern of dots
on the paper.
ÿ They are robust and can be used in harsh conditions such as in factories.
Memory Devices:
ÿ The memory unit is an essential component in any digital computer.
ÿ The programs, data and information are stored in memory unit.
ÿ The memory is broadly classified into two types, namely primary memory and secondary
memory.
Primary (or) Main Memory:
ÿ The memory that is must for running a computer system is primary memory.
ÿ The CPU has direct communication with primary memory.
ÿ The primary memory is classified in to two types.
RAM:
ÿ It stands for “Random Access Memory.”
ÿ All the programs that are running in the computer are accessed from the RAM only.
ÿ The information stored in RAM is accessed in “Random Fashion.” The access time is same
for each and every memory location.
ÿ RAM is volatile in nature because the contents of it will be lost when ever power supply is
interrupted.
ÿ There are 3 types of RAM memories. They are
SRAM:
ÿ Stands for “static RAM.”
ÿ It will store information as long as the power supply is on.
ÿ It consumes more power and is used in minimum memory requirement computers.
DRAM:
ÿ Stands for “Dynamic RAM.”
ÿ It will lose information even power supply is on.
ÿ It must have refreshment circuit to refresh the loosed information.
ÿ It is very cheaper and it consumes less power.
VRAM:
ÿ Stands for “Video RAM”.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 10
ÿ It is mostly used for video displaying cards.
ÿ It is twice faster than the SRAM & DRAM.
ROM:
ÿ Stands for “Read Only Memory.”
ÿ It is a non-volatile memory. I.e., the data stored on ROM is not erased when the power is
switched off.
ÿ This is held on chip inside the processor and is used to hold the data that can’t be changed by
the user.
ÿ Programs related to the operating system are stored in ROM chips when the computer is
manufactured.
ÿ There are three types of ROM.
PROM:
ÿ Stands for “Programmable ROM”.
ÿ These are oldest ROMS. These are in general use stored BIOS setting of the computer.
ÿ We can write permanent programs in to PROM.
EPROM:
ÿ Stands for “Erasable Programmable Read Only Memory.”
ÿ The contents of it can be erased by exposing EPROM to high intensity Ultra Violet light.
ÿ These are cheaper, reliable & widely available.
EEPROM:
ÿ Stands for “Electrically Erasable PROM.”
ÿ In case of EPROM, entire data can be erased but not single memory location, where as in
EEPROM we can able to erase entire data (or) single memory location.
ÿ By using electric Signals, data is erased. These are more advanced ROMs.
Secondary Memory:
ÿ They are also called “Auxiliary (or) External” memories.
ÿ They are used to store data permanently.
ÿ These are having high storage capacity and high processing speed. Then that of primary
memory. They are use expensive.
ÿ The following are commonly used storage devices.
Magnetic Tapes:
ÿ They look like a video cassette.
ÿ It consists of a tape and in which the data is stored with the help of read and write head.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 11
ÿ They are cheaper, and have capacity to store large data.
ÿ The data is accessed in a sequential order i.e., in order to access a particular location all its
previous locations should be accessed.
Magnetic Disks:
ÿ They are very similar to “Gram phone record” Disk. They are permanent storage media.
ÿ The devices are made of magnetic material and it provides direct access to the data.
ÿ There are two types of Magnetic Disks.
Hard Disk:
ÿ The Hard Disk memories store information in one (or) more circular plotters (or) disks which
are continuously spinning.
ÿ Information is recorded on the surface of rotating disks by magnetic heads as tiny magnetic
spots.
ÿ These are having high storage capacity and accessing of information is fast when compared
with flexible disks.
Flexible Disks:
ÿ The portable magnetic storage disks are called flexible disks.
ÿ These can be used to carry the data from one system to another.
ÿ The different flexible disks are
o Floppy Disk
o Zip Disk
Floppy Disk:
ÿ These are also called “Diskettes”.
ÿ They are one of the oldest types of portable storage devices.
ÿ They have a magnetic surface which allows the recording of data.
ÿ A standard floppy disk can store up to 1.44 MB of data.
Zip Disk:
ÿ The zip disks are very similar to floppy disks.
ÿ They are small in size and having more storage capacity than that of floppy disk.
ÿ The capacity is about 100 MB.
Optical Disks:
ÿ These are made up of glass and plastic fiber.
ÿ The data is stored on these disks by high intensity laser beams by using laser guns.
ÿ These are also portable storage devices and also very cheap.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 12
ÿ Some of the optical disks are
o Compact Disk - CD
o Digital Video Disk - DVD
CD:
The Compact Disks are optical media. These are relatively cheap and have storage capacity up to
700 MB. There are 3 main types of CD’s.
CD ROM:
Manufacturers use CD ROMS to record information. The user can’t use these for storing data. Even
user can’t modify, delete, and re-write the information on these disks.
CD – R:
Data can be recorded on these disks only once
CD-RW:
CD Re-writable is an erasable disk and we can write on it multiple times2Wsx\.
DVD:
That looks like CD, but has able to hold about 15 times much information than a CD. DVD also
comes in 3 varieties. They are
(i) DVD - ROM
(ii) DVD - R
(iii) DVD - RW
Cache Memory:
ÿ The word “Cache” is pronounced as “Cash”.
ÿ The Cache memory is the intermediate memory between the cpu and main memory.
ÿ This is the fastest memory which stores the frequent instructions needed by the system and
executes the instructions directly without communicating with the main memory.
ÿ Its access time is 15-20 Nano Seconds, While that of main memory is 80 Nano Seconds. It is
very expensive.
3. Computer Software
Introduction:
A computer system consists of hardware & software for its functioning.
Software:
ÿ It represents the set of programs that govern the operation of a computer system and make the
hardware to function.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 13


ÿ Software can be classified broadly into two categories, mainly
o System Software
o Application Software
System Software:
ÿ The Software that controls internal computer operations is called system software.
ÿ Eg: Some of the internal computer operations are reading data from input devices, transmitting
processed information to the output devices, converting data to computer understandable
format.
ÿ The system software can be further classified into two categories.
o Operating System
o Language Processor
Operating System: (OS)
ÿ An operating system is system software which acts as an interface between a user and hardware
i.e. all computer resources.
ÿ Operating system itself decides “how to do” “what to do” and “when to do” about a particular
operation.
ÿ The primary goal of an operating system is to make the computer system convenient to use and
secondary goal is to use computer hardware in an efficient manner.
ÿ An operating system is an important component of a computer system which controls all other
components of the computer system.
Language Processors:
ÿ As programmer prefer to write their programs in one of the High Level Languages {HLL}
because it is much easier to understand the code easily.
ÿ However, the computer doesn’t understand any language other than “Binary Language.” It
becomes necessary to process a HLL program me so as to make it understandable to the
computer.
ÿ The system program which performs the above job is called language processors.
ÿ Assembler, Interpreter and Compliers are some of the language processors.
Assembler:
ÿ The code written by the user in order to perform a task is called source code.
ÿ The source code can’t be understood by computer. Computer can understand only machine
language code i.e., 0’s & 1’s. The code understood by the computer is called object code.
ÿ The software which converts source code to object code is called “Translator”.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 14
ÿ In order to convert an Assembly level language code in to object code we use a translator called
“Assembler”.
ÿ Assembler: It is a Translator which converts Assembly level language code to Machine
language code.
Compiler or Interpreter
ÿ The code in a source file stored on the disk must be translated into machine language. This is
the job of the translator.
ÿ Compiler and interpreters are translators. Compiler compiles the entire program at once
where as the interpreter interprets the program line by line.
ÿ The translator reads the program and writes the resulting object module to a file that can
then be combined with other precompiled units to form the final program.
Application Software:
ÿ An Application Software is a set of programmers necessary to carry out operations for a
specified application.
ÿ These are the programmers written by programmers to enable computer perform specific task.
ÿ Application software can be further sub-divided in to 3 categories.
o Packages
o Utilities
o Business Software
Packages:
ÿ Packages are general purpose application software. This software’s has been written to do
almost every task that is commonly used in various organizations. Some major packages are
Word Processing System, Spread sheets, graphics, multimedia. . . . .

Utilities:
ÿ These are application programs that help the computer by performing housekeeping functions
like backup, scanning virus, disk de-fragmentation, etc.
ÿ These are helpful programs that ensure the smooth functioning of the computer.
Business Software:
ÿ This type of software is developed based on requirements of a particular business.
ÿ Examples are Inventory Management System, Railway Reservation System, and Hospital
Management System. . . . .

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 15


4. Algorithm:-
Algorithm is a very popular technique used to obtain solution for a given problem.
Definition: - An algorithm is defined as a finite set of steps that provide a chain of actions for
solving a problem.
Procedure for writing an algorithm:-
An Algorithm is a well organized and textual computational module that receives
one or more input values and provides one or more output values.
∑ These well defined steps are arranged in a sequence that processes given input into output.
∑ The steps of the algorithm are written using English like statements which are easy to
understand.
∑ This will enable the reader to translate each step into a program.
∑ Every step is known as instruction.
∑ An algorithm is set to be accurate only when it provides the exact required output.
∑ If the procedure is lengthy then sub divided the procedure into small parts as it make easy to
solve the problem.
Analyzing an Algorithm:-
When one writes an algorithm, it is essential to know how to analyses the algorithm.
∑ Analyzing the algorithm refers to calculating the resources such as computer memory,
processing time, logic gates and so on …..
∑ Time is most important resource because the program developed should be faster in
processing.
∑ The analysis can also be made by reading the algorithm for logical accuracy, tracing the
algorithm and checking with the data.
Categories of Algorithm
The steps in an algorithm can be divided into three categories, namely
ÿ Sequence
ÿ Selection and
ÿ Iteration
Sequence
ÿ The steps described in an algorithm are performed successively one by one without skipping any
step.
ÿ The sequence of steps defined in an algorithm should be simple and easy to understand.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 16


Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write him
Step 7: stop

Selection
ÿ We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
ÿ The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
ÿ The above syntax specifies that if the condition is true , statement-1 will be executed otherwise
statement-2 will be executed.
ÿ In case the operation is unsuccessful. Then sequence of algorithm should be changed/ corrected
in such a way that the system will re-execute until the operation is successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age
Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop
Iteration
ÿ In a program, sometimes it is very necessary to perform the same action for a number of times.
ÿ If the same statement is written repetitively, it will increase the program code.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 17
ÿ To avoid this problem, iteration mechanism is applied.
ÿ The statement written in an iteration block is executed for a given number of times based on
certain condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
5. FLOWCHART
Introduction:- flowchart is an alternative technique for solving a problem. Instead of descriptive
steps, we use pictorial representation for every step.
Definition:-
Flowchart is a diagrammatic or pictorial representation of various steps involved I the
Algorithm
∑ A complete flowchart enables us to organize the problem into a plan of actions i.e. it
specifies what comes first, second, third . . . .
∑ Flowchart also represents the flow of data.
∑ It is an easy way to solve the complex problems because it makes the reader to flow the
process quickly from the flowchart incited of going through text.
∑ A flowchart is a set of symbols that indicates various operations in a program.
∑ For every process there is a corresponding symbol in the flowchart.
∑ Once the algorithm is written, its pictorial representation can be done using flowchart
symbol.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 18


Some of the commonly used flowchart symbols are listed below.

Symbol Description
Start/Stop

Decision

Connector

Process

Input/output

Loop

Data Flow Direction Lines

Predefined Process

6. Software Development Method


SDLC includes series of steps to develop a project. It consists of a detailed plan describing how to
develop, maintain, replace and alter or enhance specific software. The life cycle defines a
methodology for improving the quality of software and the overall development process.
Analysis/Requirement Gathering
This step onwards the software development team works to carry on the project. The team holds
discussions with various stakeholders from problem domain and tries to bring out as much
information as possible on their requirements. The requirements are contemplated and segregated
into user requirements, system requirements and functional requirements. The requirements are
collected using a number of practices as given -

∑ studying the existing or obsolete system and software,


∑ conducting interviews of users and developers,

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 19


∑ referring to the database or

∑ Collecting answers from the questionnaires.

System Analysis
At this step the developers decide a roadmap of their plan and try to bring up the best software
model suitable for the project. System analysis includes Understanding of software product
limitations, learning system related problems or changes to be done in existing systems beforehand,
identifying and addressing the impact of project on organization and personnel etc. The project
team analyzes the scope of the project and plans the schedule and resources accordingly.

Software Design
Next step is to bring down whole knowledge of requirements and analysis on the desk and design
the software product. The inputs from users and information gathered in requirement gathering
phase are the inputs of this step. The output of this step comes in the form of two designs; logical
design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams,
data-flow diagrams and in some cases pseudo codes.

Coding
This step is also known as programming phase. The implementation of software design starts in
terms of writing program code in the suitable programming language and developing error-free
executable programs efficiently.

Testing
An estimate says that 50% of whole software development process should be tested. Errors may
ruin the software from critical level to its own removal. Software testing is done while coding by
the developers and thorough testing is conducted by testing experts at various levels of code such as
module testing, program testing, product testing, in-house testing and testing the product at user’s
end. Early discovery of errors and their remedy is the key to reliable software.

Integration
Software may need to be integrated with the libraries, databases and other program(s). This stage of
SDLC is involved in the integration of software with outer world entities.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 20


Implementation
This means installing the software on user machines. At times, software needs post-installation
configurations at user end. Software is tested for portability and adaptability and integration related
issues are solved during implementation.

Maintenance
This phase confirms the software operation in terms of more efficiency and less errors. If required,
the users are trained on, or aided with the documentation on how to operate the software and how to
keep the software operational. The software is maintained timely by updating the code according to
the changes taking place in user end environment or technology. This phase may face challenges
from hidden bugs and real-world unidentified problems.

7. Introduction to C:
ÿ ‘C’ is a Structured Programming Language
ÿ It is considered as a middle level language as it supports some of the features of low level
language also.
ÿ ‘C’ is a case sensitive language i.e., upper case letters and lower case letters are distinct.
ÿ It is well suitable for developing application software as well as system software.
ÿ It supports the concept of “Modular Programming”, which means that a larger task is divided in
to a number of sub tasks each subtask is referred to as a “module” or a “function”.
ÿ Due to this modular programming, it is easy to identify and rectifies the errors. Execution speed
also increases.
ÿ ‘C’ language is highly portable. i.e., a ‘C’ program written for one computer can be easily run in
another computer under certain conditions.
ÿ It supports data structures like arrays, pointers, structures and unions.
ÿ The power of ‘C’ is increased due to the support of a number of library (or) inbuilt functions.
ÿ ‘C’ has a special type of operators called “Bitwise” operators.
7.1 History of ‘C’:
Year Language Developer

1960 ALGOL-60 International Committee


1963 CPL Cambridge University
1967 BCPL Martin Richards [C.U]

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 21


1970 B Ken Thomsen [AT&T Bell Laboratories]
1972 C Dennis Ritchie [AT&T Bell Laboratories]
ÿ ‘C’ is a general purpose structured programming language.
ÿ ‘C’ was originally developed in ‘1972’ by “Dennis Ritchie” at “AT&T” Bell Laboratories.
It is an outgrowth of two earlier languages called “BCPL” {Basic Common Programming Language}
& “B” which were also developed at Bell laboratories

8. C-Tokens:
These are smallest individual units. They may represent a single character (or) a group of characters
which has a specific meaning.
ÿ The following are the ‘c’ tokens that can be recognized by “C compiler”.

C-Tokens

Identifiers Strings Keywords Constants Operators


1. Identifiers :
ÿ These are the names that are given to the various program elements such as variables, functions,
arrays, structures, etc.
ÿ These are user defined names.
Limitations:
ÿ It allows alphabets, digits and the special character underscore (_).
ÿ Both upper case & lower case letters are permitted.
ÿ Upper case & lower case aren’t interchangeable
ÿ An identifier name should not start with a digit.
ÿ It can start with either an alphabet (or) underscore. [An identifier starting with underscore is
rarely done in practice].
ÿ Keywords (or) reserved words should not used as identifiers.
Eg: area, Max_Price ,_total -Valid Identifiers
Min area, ‘a’, “college” –not valid Identifiers.
ÿ Identifiers can be arbitrarily long but some c-compilers recognize only the first eight characters.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 22


Key words:
ÿ These are also called “reserved words”.
ÿ They have standard and pre-defined meaning in ‘c’. These keywords can be used only for their
intended purpose. They can’t used as programmer defined identifiers.
ÿ ‘C’ language supports nearly 37 key words.

auto Double int Struct


Break Else long Switch
Case Enum register Typedef
Char Extern return Union
Const Float short unsigned
Continue For signed Void
Default go to size of Volatile
Do If static While

8.1 Data Types


ÿ It specifies the type of the data, the size of data and about the range of data.
ÿ ‘C’ supports a several different types of data types.

Data Types

Primary data type User defined data type Derived data type Empty data type

Integer Type def Arrays Void

Functions
Charater Enum

Structures
Float

Pointers
Double
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 23
Primary
Data Type Size (in bytes) Range
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed 2 -32768 to 32767
short 2 -32768 to 32767
unsigned short 2 0 to 65535
signed short 2 -32768 to 32767
long 4 -2147483648 to
2147483647
unsigned long 4 0 to 4294967295
signed long 4 -2147483648 to
2147483647
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
float 4 3.4E -38 to 3.4E +38
double 8 1.7E -308 to 1.7E +308
long double 10 34E -4932 to 34E +4932
Note:
ÿ Float is a single precision value. {After decimal 7 digits has been considered}
ÿ Double is a double precision value. {After decimal 14 digits has been considered}
ÿ In-Built data Types are supported by ‘C’ compiler by default.
1. Character (Denoted as "char" in C programming language)
Description: A character denotes any alphabet, digit or special symbol used to represent in
formation and it is used to store a single character.
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.
2. Integer (Denoted as "int" in C programming language)
Description: Integer type is used to store positive and negative integer.
Storage space: 2 bytes.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 24
Format: %d
Range of values: -327687 to +32767.
3. Float point (Denoted as "float" in C programming language)
Description: It is used to store real number, with single precision floating point number (precision of
6 digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.
4. Double (Denoted as "double" in C programming language)
Description: It stores real numbers with double precision. The use of double doesn't guarantee to
double the number of significant digits in our result, but it improves the accuracy of the
arithmetic and reduces the accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.
void:
ÿ It is a special data type used for
o To specify that a function doesn’t returns any value.
o To specify a function takes no arguments.
o To create generic pointers.
Eg: 1. void print (void)
2. void *ptr
Constants:
ÿ These are fixed values that will not change during the execution of program.
Integer Constant:
An integer constant is an integer valued numbers.
Rules for Constructing Integer Constant:
ÿ It shouldn’t have a decimal point.
ÿ An integer constant must have at least one digit.
ÿ Commas, Blank spaces, special characters can’t be included with in the constants.
ÿ The constant can be preceded by a minus sign if desired.
ÿ The range of integer constants is -32,768 to 32,767

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 25


Types of Integer Constants:
ÿ Integer Constants can be written in 3 different number systems, namely
o Decimal {Base = 10}
o Octal {Base = 8}
o Hexa Decimal {Base = 16}
Decimal Numbers:
ÿ A Decimal integer constant can consists of any combinations of digits taken from the set 0-9.
ÿ If the constant contains 2 (or) more digits, the first digit must be something other than zero.
Eg: 0,1,723,32156.
Octal Constants:
ÿ An Octal integer constant can consist of any combination of digits taken from the set 0-7.
ÿ The first digit must be zero in order to identify the constant as an octal number.
Eg: 0,01,0723.
Hexa Decimal Numbers:
ÿ A Hexa Decimal integer constant must begin with either 0x, (or) 0x.
ÿ It can be consists of the digits taken from the set 0-9, and a-f {either upper case (or) lower
case}.
ÿ The letters a-f, represent the quantities 10-15 respectively.
Eg: 0x, 0x, 0x7.
Unsigned & Long Integer Constants:
ÿ An Unsigned integer constant can be identified by appending the letter ‘u’. {either upper or
lower case}
ÿ Long interval constants can be identified by appending the letter ‘L’ {either upper or lower
case} to the end of the constant.
ÿ An unsigned long interval constant can be specified by appending the letters UL {either upper
case (or) lower case} to the end of the constants.
ÿ Note that ‘u’ must precede the ‘L’.
Eg: 234U – Unsigned Decimal Constant
0427UL – Unsigned Long Octal Constant
0X72FL – Long Hexa Decimal Constant
Floating Point Constants:
ÿ A floating point constant is a decimal number that contains a decimal point.
Rules:
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 26
ÿ Commas and Blank spaces can’t be included.
ÿ It can contain of either decimal point (or) Exponent.
ÿ The constant can be preceded by minus sign it desired.
Eg: 0, 1., 12.3.
Scientific Notation:
ÿ When we want to represent very large values (or) very small values, instead of representing the
value of sequence of digits we can represent a floating point constant value in a scientific
notation as follows.
Mantissa E (or) e exponent.
Eg: 1.2E + 3 => 1.2 * (10^3)
ÿ Note that if no sign is represented after ‘E’ it will be treated as positive.
ÿ Floating point constants are identified by appending the letter F {either upper case (or) lower
case} to the end of the constants.
Eg: 3E5F = 300000F.

Character Constants:
ÿ A character constant is a single character enclosed in single quotation marks. The Max length of
character constant is “one”. The single character can be either alphabet (or) Digit (or) a special
symbol.
ÿ Eg: ‘a’, ‘1’, ‘?’.
Note: Most computers make use of the “ASCII” {American Standard Code for Information
Interchange”}, character set, in which each individual character is numerically encoded.
ÿ ASCII code is a 7 bit code. ASCII values ranges from 0-127.
Escape Sequences:
ÿ The Escape Sequence characters are used to denote non-graphic characters and other special
characters for a specific operation.
ÿ Some of the Escape Sequence characters are listed.
Escape Sequences Character Meaning
\a Alert a bell character
\n New line {line feed}
\t Horizontal Tab
\b Back Space
\r Carriage return
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 27
String Constants:
ÿ A String Constant consists of any number of consecutive characters enclosed in double
quotation marks.
Eg: “ved”, “college”, “ “.
Variable:
ÿ A variable is an identifier that is used to represent a single data item.
ÿ The data may be numerical quantity (or) a character constant.
ÿ The data item must be assigned a value to the variable at some point in the program. Then data
item can be accessed by referring to the variable name
ÿ In other words, a variable is an identifier which changes its value during the execution of the
program.
Rules for Constructing a Variable:
ÿ A variable name is a combination of alphabets, digits and underscore.
ÿ Other than the underscore no special characters is allowed.
ÿ The first character in the variable name must be an alphabet.
ÿ The variable name should not be of keyword.
10. Operators
ÿ An operator is a symbol that informs to the computer to perform a particular task.
ÿ The data items that operators act upon are called “operands”.
ÿ If the operator requires only one operant then it is called “unary operator”. If it requires two
then it is called “Binary Operator”.
ÿ ‘C’ language supports a different set of operators which are listed below.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Assignment Operators
o Increment / Decrement Operators
o Bit wise Operators
o Unary Operators
o Conditional Operators
o Special Operators

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 28


Arithmetic Operators:
ÿ Arithmetic operators are basic and common operations performed using and computer language.
ÿ There are five arithmetic Operators available in ‘C’. They are

Operator Purpose Examples


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modular Division a%b

Relational Operators:
ÿ Relational Operators are used to perform comparison between two values.
ÿ These operators’ returns true (1) if the comparison condition is true otherwise false (0).
ÿ The operators used for comparison in ‘C’ are listed below.
perator Description or Action
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

Eg: 35<5 false (0)


10<=10 true (1)
45>5 true (1)
11>=5 true (1)
35= = 10 false (0)
35! =10 true (1)
(10+5)= = (5*3) true (1)
Eg: Write a program to use various relational operators and display their return values?
#include<stdio.h>
#include<conio.h>
void main()
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 29
{
clrscr();
printf("\condition\t:Return values\n");
printf("\n10!=10\t\t:%5d",10!=10);
printf("\n10==10\t\t:%5d",10==10);
printf("\n10>=10\t\t:%5d",10>=10);
printf("\n10<=100\t\t:%5d",10<=100);
printf("\n10!=9\t\t:%5d",10!=9);
getch();
}
Logical Operator:
ÿ When we want to take a decision basing on 2 (or) more conditions then we will use logical
operators.
ÿ There are three logical operators available in ‘C’

Operator purpose
&& Logical AND
|| Logical OR
! Logical NOT

Logical and: (&&)


ÿ Logical And results in true if both the conditions are true otherwise the result is false.
Truth Table:
A B A&B
T T T
T F F
F T F
F F F
Logical Or: (||)
ÿ Logical Or results in true if either of the conditions is true.
ÿ The result is false if all the conditions are false.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 30


Truth Table:
A B A||B
T T T
T F T
F T T
F F F
Logical not: (!)
ÿ If the condition is true then the result is false and if the condition is false the result is true.
Truth Table:
A !A
T F
F T
Examples:
8>6&&6<10 true (1)
9>4||7<3 true (1)
8! =8 false (0)
10! =9 true (1)

¸ Write an example program using logical operators?

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("condition : Return values\n");
printf("\n9>5&&8<10:%5d",9>5&&8<10);
printf("\n10<9&&3>7:%5d",10<9&&3>7);
printf("\n9>6||6<2 :%5d",9>5||8<3);
printf("\n8!=8 :%5d",8!=8);
printf("\n9!=10 :%5d",9!=10);
getch();
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 31
Assignment Operators:
ÿ This operator is used to assign a constant value (or) the result of an expression to a variable.
ÿ In this operation Right hand side expression is evaluated first and then the result is assigned to
left hand side variable.
Operator Meaning
= Assign Right Hand value to LHS value
+= Value of LHS add to value of RHS and assign it back to the variable in
LHS
Eg: a+=2=> a = a+2
-= Value of RHS variable will be subtracted from the value of LHS and
assign it back to the variable in LHS.
Eg: a-=2 => a = a-2
*= Value of LHS variable will be multiplied to the value of RHS and
Assign it back to the variable in LHS.
Eg: a*=2 => a=a*2
/= Value of LHS variable will be divided by the value of RHS and
Assign it back to the variable in LHS.
Eg: a/=2 => a=a/2
%= The Remainder will be stored back to the LHS after integer, division
Is carried out between the LHS variable and RHS variable.
Eg: a%=2 => a=a%2
>>= Right shift and assign the value to the LHS.
Eg: a>> =2 => a=a>>2.
<<= Left shift and assign the value to the LHS.
Eg: a<<=2 => a=a<<2.
&= Bit wise AND operation and assign the value to the LHS.
Eg: a&=b => a=a&b.
|= Bit wise OR operation and assign the value to LHS.
Eg: a|=b => a=a | b
~= Bit wise complement and assign the value to LHS.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 32


Increment/Decrement Operator {++/- -}
ÿ Increment operator increases the value by ‘1’ where as decrement operator decreases the value
by ‘1’.
ÿ This operator can be used in two forms namely Prefix and Postfix.
ÿ In case of Prefix notation the operator precedes the operant {++a}.
ÿ In case of Postfix notation the operator is followed by operand {a++}.
ÿ In Prefix notation increment operation will be given the highest priority i.e., first the value is
incremented by ‘1’ and other operations are performed later.
ÿ In Postfix notation, increment operator will be given the least priority i.e., the increment
operation is performed at last after all operations are performed.
ÿ The above points are applicable to the decrement operator also.
Eg: 1) a=5 2) a=5
c= ++a c=a++
c=6,a=6 c=5, a=6.
Explanation:
ÿ In above expression-1, c= ++a two operations namely assignment and increment are involved.
Since the operator ++ is used as prefix, first we perform incrimination i.e., a=a+1 and then this
value is assigned to ‘C’.
ÿ In the expression-2, c= a++ two operations namely assignment and increment are involved.
Since the operator ++ is used as postfix, first we assign the value of ‘a’ to ‘c’. i.e., c=a => a=5
and then the value of ‘a’ is incremented i.e., a=a+1=6
Bitwise Operators:
ÿ Bitwise operators are one of the salient features of ‘C’ language.
ÿ These are specially designed to manipulate the data at Bit level.
ÿ The Bitwise operators are not applicable for float (or) Double data type.
ÿ The following are the some of the Bit wise operators available in ‘C’ language.
Operator Meaning
& Bitwise Logical AND
| Bitwise Logical OR
^ Bitwise Logical XOR
<< Left Shift
>> Right Shift

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 33


Bitwise AND: (&)
ÿ To generate a ‘1’ bit in the result, Bitwise AND need a ‘1’ in both the numbers.
ÿ Bitwise AND operator is called “MASK” operator.
Eg: a=28, b=17
a =11100
b =10001
a&b =10000
a&b =16
Bitwise OR: (|)
ÿ The Bitwise OR result is ‘1’ if at least one of the numbers is ‘1’.
Eg: a=28,b=17
a= 11100
b= 10001
a|b =11101 => a|b = 29
Bitwise Exclusive OR: (^)
ÿ It is similar to task Bitwise OR and the result ‘1’ is produced if 1 is present in either but not
both.
Eg: a=28, b=17
a= 11100
b= 10001
a^b=01101 => a^b =13
Bitwise 1’s complement: (~)
ÿ The complement operator switches all the Bits in a binary pattern i.e., all 0’s becomes 1’s and
all 1’s becomes 0’s.
Eg: i) Bitwise complement of 12 is -13
ii) Bitwise complement of 0 is -1.
Shift Operations:
ÿ The shift operations take binary patterns and shift the bits to the left (or) right.
ÿ Keeping the same number of bits by dropping the shifted bits at the end and filling in with 0’s at
other end.
ÿ C-language provides 2 types of shift operators namely left and right shift.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 34
Left Shift: {<<}
ÿ This operator is used for left shifting .
Eg: a=00011100
a<<1 = 00111000
a<<2 = 01110000 => a<<2 =112
Right Shift: {>>}
ÿ This operator used for right shifting.
Eg: a = 00011100
a>>1 = 00001110
a>>2 = 00000111 => a>>2 = 7
Conditional Operator: (? :)
ÿ ‘C’ includes a very special type of operator called conditional operator.
ÿ It is also called “ternary” operator since it requires three expressions. It acts like a short hand
version of if-else construction.
ÿ Syntax: exp1? exp2: exp3
ÿ In exp1 is true then exp2 is evaluated otherwise exp3 will be evaluated.
Eg: a>b? a=b

Special Operators:
ÿ In addition to the above operators ‘C’ language supports some special operators like comma
operator, parenthesis for grouping expression, membership operators.

C supports some special operators of interest such as comma operator, sizeof operator.

Comma Operator:
This operator is used to link the related expression together the expression is
separated by the, operator.

e.g.: a=(x=6,y=7,x+y);
This expression first assigns 6 to x and 7 to y then assigns (6+7) to a.

Size of Operator:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 35


The size of operator returns a number of bytes the operand occupies in memory. The
operand may be a variable, a constant or a data type qualifier. It is a compile time operator.
Syntax: sizeof(operand)
e.g.: y=sizeof(int); here value of y will be 2bytes
z=sizeof(a);her value of z depends on data type of a

Member operator:
These are used to access member of structures and unions.
e.g.:
var member 1;
When var is a structure variable.
var ‡member 2;
When var is pointer to structure variable.

Precedence and Associativity


ÿ Every operator has a precedence value. An expression containing more than one operator is
known as a complex expression.
ÿ Complex expressions are executed according to precedence of operators.
ÿ Associativity specifies the order in which the operators are evaluated with the same precedence
in a complex expression.
ÿ Associativity is of two ways i.e., left-to-right and right-to-left.
ÿ Left-to-right associativity evaluates an expression stating from left and moving towards right.
ÿ Right-to-left associativity proceeds from right to left.
The precedence and associativity of various operators in C are as shown in the following table

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 36


Operators Operation Associativity Precedence
() Function call
[] Array expression or square bracket
-> Structure Operator Left to right 1st
. Structure Operator
+ Unary plus
_ Unary minus
++ Increment
-- Decrement
! Not operator Right to left 2nd
~ One’s complement
* Pointer operator
& Address operator
Sizeof Size of an object
Type Type cast
* Multiplication
Left to right
/ Division 3rd
% Modular division
+ Addition Left to right 4th
- Subtraction
<< Left shift Left to right 5th
>> Right shift
< Less than
<= Less than or equal to 6th
Left to Right
> Greater than
>= Greater than or equal to
== Equality 7th
Left to right
!= Inequality
& Bitwise AND Left to right 8th
^ Bitwise XOR Left to right 9th

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 37


| Bitwise OR Left to right 10th
&& Logical AND Left to right 11th
|| Logical OR Left to right 12th
?: Conditional Operator Right to Left 13th
=, *=, -=, &=, += Assignment Operators Right to Left
14th
^=, |=, <<=, >>=
, Comma Operator Left to right 15th

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 38


UNIT – II

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 39


UNIT - II
Selections Statements – Iteration Statements – Jump Statements- Expression Statements – Block
Statements.
Single Dimensional Arrays – Generating a Pointer to an Array – Passing Single Dimension Arrays to
Functions – Strings – Two Dimensional Arrays – Indexing Pointers – Array Initialization – Variable
Length Arrays
CONTROL STRUCTURES / STATEMENTS
∑ A program is nothing but the execution of sequence of one or more instructions.
∑ Quite often, it is desirable to alter the sequence of the statements in the program depending
upon certain circumstances. (i.e., 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.
∑ This involves a kind of decision making to see whether a particular condition has occurred or
not and direct the computer to execute certain statements accordingly.
∑ Based on application, it is necessary / essential
(i) To alter the flow of a program
(ii) Test the logical conditions
(iii) Control the flow of execution as per the selection these conditions can be placed in the
program using decision-making statements.
“C” SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS .
1. Decision making statements
1) Simple if Statement
2) if – else Statement
3) Nested if-else statement
4) else – if Ladder
5) switch statement
2. Loop control statements
1) for Loop
2) while Loop
3) do-while Loop

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 40


3. Unconditional control statements
1) goto Statement
2) break Statement
3) continue Statement
4) return statement

1. Decision Making Statements:


These statements change the flow of execution depending on a given logical condition.
Used to execute or skip some set of instructions based on given condition.
1)Simple “if” statement:
“if” statement is a powerful decision making statement, and is used to control the flow of
execution of statements.
Syntax:
if (Condition or test expression)
{
Statement;
}
Rest of the program;
It is basically a “Two-way” decision statement (one for TRUE and other for FALSE)
∑ It has only one option.
∑ The statement as executed only when the condition is true.
∑ In case the condition is false the compiler skips the lines within the “if Block”.
∑ The condition is always enclosed within a pair of parenthesis i.e. ( ) ,
∑ The conditional statement should not terminated with Semi-colons (ie ;)
∑ The Statements following the “if”-statement are normally enclosed in Curly Braces {}.
∑ The Curly Braces indicates the scope of “if” statement. The default scope is one statement.
But it is good practice to use curly braces even with a single statement.
∑ The statement block may be a single statement or a group of statements.
∑ If the Test Expression / Conditions are TRUE, the Statement Block will be executed and
executes rest of the program.
∑ If the Test Expression / Condition are FALSE, the Statement Block will be skipped and rest
of the program executes next.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 41
Flow chart for “if” statement:

Entry

Condition False

True

If block

Rest of the program

(2) “if-else” Statement:


It is observed that the “if” statement executes only when the condition following if is
true. It does nothing when the condition is false.
In if-else either True-Block or False – Block will be executed and not both. The “else”
Statement cannot be used without “if”.
Syntax:
if ( Test Expression or Condition )
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 42


Flow chart:

Entry

Condition

True False

True Block Statement False Block Statement

Rest of the Program

(3) Nested “if–else” Statement:

Using of one if-else statement in another if-else statement is called as nested if-else
control statement.
When a series of decisions are involved, we may have to use more than one if-else
statement in nested form.

Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 43


else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement-4;
}
} /* end of outer if-else *
If Test Condition-1 is true then enter into outer if block, and it checks Test Condition2,if it is true
then Statement-1 executed if it is false then else block executed i.eStatement-2.
If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test
Condition-3 checks if it is true then Statement-3 executed, else Statement-4 executed.
Flowchart:

Entry
True False
Condition1

Condition2 Condition3

True False True False

True Block Code False Block Code True Block Code False Block Code

Rest of the program

(4) The “else – if” Ladder:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 44


This is another way of putting if‘s together when multiple decisions are involved. A
multipath decision is a chain of if‘s in which the statement associated with each else is an if.
Hence it forms a ladder called else–if ladder.
if else-if, statement is used to execute one code from multiple conditions.
Syntax:
if (Test Condition -1)

{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
else
{
default statement;
}

Rest of the Program Statements-X;


∑ The above construction is known as else if ladders.
∑ The conditions are evaluated from top to bottom.
∑ As soon as a true condition is found, the statement associated with it is executed and
∑ The control is transferred to the Rest of the Program Statement–X (skipping rest of the
ladder).
∑ When all the “n” conditions become false, then the final else containing the default statement
will be executed.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 45


(5) The “switch-case” Statement:
Switch is another conditional control statement used to select one option from several options
based on given expression value; this is an alternative to the if-else-if ladder.
∑ The switch statement causes a particular group of statements to be chosen from several
available groups.
∑ The selection is based upon the current value of an expression which is included with in the
switch statement.
∑ The switch statement is a multi-way branch statement.
∑ In a program if there is a possibility to make a choice from a number of options, this
structured selected is useful.
∑ The switch statement requires only one argument of int or char data type, which is checked
with number of case options.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 46


∑ The switch statement evaluates expression and then looks for its value among the case
constants.
∑ If the value matches with case constant, then that particular case statement is executed.
∑ If no one case constant not matched then default is executed.
∑ Here switch, case and default are reserved words or keywords.
∑ Every case statement terminates with colon “:”.
∑ In switch each case block should end with break statement, i.e.

Syntax:
Switch (variable or expression)
{
Case Constantvalue-1: Block -1;
(Or)
Statement-1;
break;
Case Constantvalue-2: Block -2;
(Or)
Statement-2;
break;
Case Constant value-n: Block -n;
(Or)
Statement-n;
break;
default: default – block;
}

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 47


Flowchart:

2. Loop control statements:


Loop: A loop is defined as a block of statements which are repeatedly executed for certain number
of times.
In other words it iterates a code or group of code many times.
Why use loops in c language: Suppose you want to execute some code/s 10 times. You can perform
it by writing that code/s only one time and repeat the execution 10 times using loop. For
example: Suppose that you have to print table of 2 then you need to write 10 lines of code, by
using loop statements you can do it by 2 or 3 lines of code only.
1)for Loop:
The for loop works well where the number of iterations of the loop is known before the
loop is entered. The head of the loop consists of three parts separated by semicolons.
∑ The first is run before the loop is entered. This is usually the initialization of the loop
variable.
∑ The second is a test, the loop is exits when this returns false.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 48


∑ The third is a statement to be run every time the loop body is completed. This is usually an
increment of the loop counter.
∑ The 3 actions are
“Initialize expression”, “Test Condition expression” and “updation expression” ”
The expressions are separated by Semi-Colons (;).
Syntax:
for (initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
(i)The initialization sets a loop to an initial value. This statement is executed only once.
(ii) The test condition is a relational expression that determines the number of iterations desired or it
determines when to exit from the loop.
∑ For loop continues to execute as long as conditional test is satisfied.
∑ When the condition becomes false the control of the program exits from the body of for loop
and executes next statements after the body of the loop.

(iii) The updation (increment or decrement operations) decides how to make changes in the loop.
∑ The body of the loop may contain either a single statement or multiple statements.
Flowchart:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 49


Nested “for” loop:
We can also use loop within loops. i.e. one for statement within another for statement is allowed
in C. In nested for loops one or more for statements are included in the body of the loop.
* ANSI C allows up to 15 levels of nesting. Some compilers permit even more.
Syntax:
for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
(2) The “while” loop:
∑ The while is an entry-controlled loop statement.
∑ The test condition is evaluated and if the condition is true, then the body of the loop is
executed.
∑ The execution process is repeated until the test condition becomes false and the control is
transferred out of the loop.
∑ On exit, the program continues with the statement immediately after the body of the loop.
∑ The body of the loop may have one or more statements.
∑ The braces are needed only if the body contains two or more statements.
∑ It’s a good practice to use braces even if the body has only one statement.
∑ The simplest of all the looping structures in C is.
Syntax:
Initialization Expression;
while ( Test Condition)
{
Body of the loop
Updation Expression
}

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 50


Flowchart:

(3) The “do-while“ loop:


To execute a part of program or code several times, we can use do-while loop of C
language. The code given between the do and while block will be executed until condition is
true.
∑ The do-while is an exit-controlled loop statement. Because, in do-while, the condition is
checked at the end of the loop.
∑ The do-while loop will execute at least one time even if the condition is false initially.
∑ The do-while loop executes until the condition becomes false.

Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 51


Flowchart:

3. Unconditional Control Statements

(1) The “break” Statement:


A break statement terminates the execution of the loop and the control is transferred to the statement
immediately following the loop. i.e., the break statement is used to terminate loops or to exit
from a switch.
∑ It can be used within for, while, do-while, or switch statement.
∑ The break statement is written simply as break;
∑ In case of inner loops, it terminates the control of inner loop only.
Syntax:
Jump-statement;
break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
(2)The “continue” Statement:
The continue statement is used to bypass the remainder of the current pass through a loop.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 52


∑ The loop does not terminate when a continue statement is encountered. Instead, the
remaining loop statements are skipped and the computation proceeds directly to the next pass
through the loop.
∑ The continue statement can be included within a while, do-while, for statement.
∑ It is simply written as “continue”.
∑ The continue statement tells the compiler “Skip the following Statements and continue with
the next Iteration”.
∑ In “while” and “do” loops continue causes the control to go directly to the test –condition and
then to continue the iteration process.
∑ In the case of “for” loop, the updation section of the loop is executed before test-condition, is
evaluated.
Syntax:
Jump-statement;
Continue;
The jump statement can be while, do while and for loop.

(3) The “goto” Statement:

∑ C supports the “goto” statement to branch unconditionally from one point to another in the
program.
∑ Although it may not be essential to use the “goto” statement in a highly structured language
like “C”, there may be occasions when the use of goto is necessary.
∑ The goto requires a label in order to identify the place where the branch is to be made.
∑ A label is any valid variable name and must be followed by a colon (: ).
∑ The label is placed immediately before the statement where the control is to be transferred.
∑ The label can be anywhere in the program either before or after the goto label statement.
Syntax:
goto label;
.............
.............
.............
label:
statement;

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 53


In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code below it.

goto label; label:


------------- Statement;
------------- ------------
------------- ------------
------------- ------------
label: ------------
Statement; goto label;

Forward Jump Backward Jump

4. Arrays
The fundamental data types, namely char int, float, and double are used to store only one
value at any given time. Hence these fundamental data types can handle limited amounts of data.
In some cases we need to handle large volume of data in terms of reading, processing and
printing. To process such large amounts of data, we need a powerful data type that would
facilitate efficient storing, accessing and manipulation of data items. For example: If the user
wants to store marks of 100 students. This can be done by creating 100 variables individually
but, this process is rather tedious and impracticable. This type of problem can be handled in C
programming using arrays.
Array:

C Array is a collection of variables belongings to the same data type. You can store group of
data of same data type in an array.
(Or)
An array is collection of homogeneous elements in a single variable.
∑ Array might be belonging to any of the data types
∑ Array size must be a constant value.
∑ Always, adjacent memory locations are used to store array elements in memory.
∑ Individual values are called as elements.
∑ It allocates sequential memory locations.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 54


Types of Arrays:

We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
∑ One – dimensional arrays
∑ Two – dimensional arrays
∑ Multidimensional arrays

4.1 One – Dimensional Array:


A list of items can be given one variable name using only one subscript and such a
variable is called a single – subscripted variable or a one – dimensional array.
Declaration of One-Dimensional Arrays:
Like any other variables, arrays must be declared before they are used.
The general form of array declaration is
Syntax:

<data type> <array name>[sizeofarray];

∑ The data type specifies the type of element that will be contained in the array, such as int,
float, or char.
∑ The size indicates the maximum number of elements that can be stored inside the array.
For example:
int age[5];

Here, the name of array is age. The size of array is 5, i.e., there are 5 items (elements) of
array age. All elements in an array are of the same type (int, in this case).
Array elements:
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program.
For example: int age [5];

age [0] age[1] age[2] age[3] age[4]

Array Elements

Note that, the first element is numbered 0 and so on.


Here, the size of array age is 5 times the size of int because there are 5 elements.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 55


Suppose, the starting address of age [0] is 2120d and the size of int be 2 bytes. Then, the next
address (address of a [1]) will be 2122d, address of a [2] will be 2124d and so on.
Initialization of one-dimensional array:
After an array is declared, its elements must be initialized. Otherwise they will contain
“garbage”. We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.

The general form of initialization of array is

Syntax:
datatype array_name[size] = { list of values };

The values in the list are separated by commas.

You can initialize array in C either one by one or using a single statement as follows:

int age[5]={2,6,34,5,1};

It is not necessary to define the size of arrays during initialization.

int age[]={2,6,34,5,1};

In this case, the compiler determines the size of array by calculating the number of elements of an
array.

Following is an example to assign a single element of the array:

int age[2]=34;
int age[3]=5;

age[0] age[1] age[2] age[3] age[4]


2 6 34 5 1

Initialization of one dimensional array

Two Dimensional Arrays:


There could be situations where a table of values will have to be stored.
Consider a student table with marks in 3 subjects.

Student Mathematics Physics Chemistry


Student # 1 89 77 84
Student # 2 98 89 80
Student # 3 75 70 80
Student # 4 60 75 80
Student # 5 84 80 75

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 56


∑ The above table contains a total of 15 values.
∑ We can think this table as a matrix consisting of 5 rows & 3 columns.
∑ Each row represents marks of student # 1 in all (different) subjects.
∑ Each column represents the subject wise marks of all students.
∑ In mathematics we represent a particular value in a matrix by using two subscripts such as
Vij. Here V denotes the entire matrix Vij refers to the value in “ i ”th row and “ j ”th column.
Example:
In the above table V23 refers to the value “80”.
∑ C allows us to define such tables of items by using two-dimensional arrays.

Definition:
A list of items can be given one variable name using two subscripts and such a variable is called
a two–sub scripted variable or a two – dimensional array.
Two – Dimensional arrays can be declared as.
Syntax:
<datatype> <variable-name>[row-size][column-size];

The above table can be defined in “C” as


int V[5][3];

Representation of a two Dimensional array in memory:

Column-0 column-1 column-2

[0][0] [0][1] [0][2]

Row-0 89 77 84

[1][0] [1][1] [1][2]

Row-1 98 89 80

[2][0] [2][1] [2][2]

Row-2 75 70 80

[3][0] [3][1] [3][2]

Row-3 60 75 80

[4][0] [4][1] [4][2]

Row-4 84 80 75

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 57


Initializing Two- Dimensional Arrays:

∑ Like the one-dimensional arrays, two-dimensional arrays may be initialized by following


their declaration with a list of initial values enclosed in braces.
int table[2] [3] = {0,0,0,1,1,1};

∑ This initializes the elements of first row to zero and the second row to one.
∑ This initialization is done row by row.
∑ The above statement can be equivalently written as
int table[2][3] ={{0,0,0},{1,1,1}};

∑ we can also initialize a two-dimensional array in the form of a matrix as shown.

int table[2][3] = {
{0,0,0},
{1,1,1}
};
∑ Commas are required after each brace that closes of a row, except in case of last row.
∑ If the values are missing in an initialize, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, 1 1 0
{2} 2 0 0
};

Multi – Dimensional Array:


A list of items can be given one variable name using more than two subscripts and such a
variable is called Multi-dimensional array.
Three Dimensional Arrays:
The Three dimensional array can be declared as
Syntax:
<datatype> <array_name>[sizeofno.oftwoDimArray] [sizeofrow] [sizeofcolumn];
Initializing Three- Dimensional Arrays:
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
int table[2][2][3] = {0,0,0,1,1,1,6,6,6,7,7,7};
∑ This initializes the elements of first two dimensional(matrix) first row to zero’s and the
second row to one’s and second matrix elements are first row to six’s and the second row to
seven’s.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 58


∑ This initialization is done row by row.
∑ The above statement can be equivalently written as
int table[2][3] = {{{0,0,0},{1,1,1}},{{0,0,0},{1,1,1}}}

∑ We can also initialize a two – dimensional array in the form of a matrix as shown.

int table[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}

};

5. Strings
String is a collection of characters positioned sequentially one after the other, used to represent
names of items, persons, cities, countries and etc. To handle strings there is no direct datatype in c,
instead we have to access them as a normal array of characters. Which is terminated by a null
character ‘\0’, thus a null-terminated string contains the characters that comprise the string followed
by a null. This null character indicates the end of the string.
Strings are always enclosed by double quotes, whereas, character is enclosed by single quotes in
C.
If we declare char arr[20]; means ‘arr’ is an array name with the maximum capacity of 20
characters, it can hold a string with a maximum length of 19 characters and 1 byte for null
character.
Example for C string:

char string[20] = { ‘w’ , ’e’ , ‘l’ , ‘c’ , ‘o’ , ‘m’ , ‘e’ ,’-’ , ‘t’ , ‘o’ ,’-’, ’c’ , ‘r’ , ‘e’ , ‘c’ , ‘\0’}; (or)
char string[20] = “welcome-to-crec ”; (or)
char string [] = “welcome-to-crec ”;
Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of
memory space is allocated for holding the string value.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during execution of the program.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 59


Accessing individual character in a string is just as accessing elements in the array. The index of the
character should be specified as array subscript.
For example: char c[]=”crec”;
The expression ‘c[0]’ accesses the first character ‘c’
‘c[1]’ accesses the second character ‘r’
‘c[2]’ accesses the third character ‘e’,……….
Similarly remaining elements are accessed.

String I/O functions:

The following are the input and output functions of strings in c


Input functions: scanf(), gets()
Output functions: printf(), puts()
The scanf() and printf() are generic i/o functions that they support all built-in data types such as
int, float, long, double, strings,..etc. But gets() and puts() are specialized to scan and print only string
data. There is a little difference between scanf() and gets(), while reading string from keyboard, the
scanf() accepts character by character from keyboard until either a new line (‘\n’) or blank space is
found, which ever comes earlier. Whereas “gets()” accepts until a newline is found. That is it accepts
white spaces & tab also, these input functions append a null character at end of string, the formatted
string %s is used in printf() and scanf().for example:

Scanning string with “scanf()” Scanning string with “gets()”


void main() void main()
{ {
char a[20]; char a[20];
printf(“enter a string:”); printf(“enter a string:”);
scanf(“%s”, a); //scanf(“%s”, &a[0]); gets(a);
printf(“\n output=%s”, a); printf(“\n output=%s”, a);
} }
Input: Jack and Jill // scanf treats as 3 strings Input: Jack and Jill // gets() treats as single string
Output: Jack Output: Jack an Jill
The scanf() function consider the jack and Jill as 3 strings, whereas gets() considers as
single string. In case to scan total string using scanf(), then it should be scanf(“%s%s%s”, a,b,c);
here a,b,c are three arrays
The printf() and puts() is work in similar way. All I/O functions take first byte address
(base address of array) as argument and prints the given string using pointer.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 60


String Handling Functions In C

1) strlen( ) Function: strlen( ) function is used to find the length of a character string.

Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
∑ This will return the length of the string 9 which is assigned to an integer variable n.
∑ Note that the null character “\0‟ available at the end of a string is not counted.
2) strcpy( ) Function: strcpy( ) function copies contents of one string into another string. Syntax
for strcpy function is given below.

Syntax: char * strcpy (char * destination, const char * source);


Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t bcopied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20
characters from source string will be copied into destination string and remaining 10 characters
won’t be copied and will be truncated.

Ex : char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.

3) strcat( ) Function: strcat( ) function in C language concatenates two given strings. It


concatenates source string at the end of destination string. Syntax for strcat( ) function is given
below.
Syntax:
char * strcat ( char * destination, const char * source );

Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 61


∑ As you know, each string in C is ended up with null character (‘\0′).
∑ In strcat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created
after strcat( ) operation.
∑ Strncat() function: strncat( ) function in C language concatenates (appends) portion of one
string at the end of another string.
Syntax:
char * strncat ( char * destination, const char * source, size_t num );

Example:

strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.

As you know, each string in C is ended up with null character (‘\0′).

In strncat( ) operation, null character of destination string is overwritten by source string’s


first character and null character is added at the end of new destination string which is created
after strncat( ) operation.
4) strcmp( ) Function: strcmp( ) function in C compares two given strings and returns zero if
they are same. If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value.
Syntax:
int strcmp ( const char * str1, const char * str2 );

strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.

Example:
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the first
mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer variable as
follows:
int n;
n = strcmp(city, town);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 62
5) strcmpi() function: strcmpi( ) function in C is same as strcmp() function. But, strcmpi( )
function is not case sensitive. i.e., “A” and “a” are treated as same characters. Whereas, strcmp()
function treats “A” and “a” as different characters.
∑ strcmpi() function is non standard function which may not available in standard library.
∑ Both functions compare two given strings and returns zero if they are same.
∑ If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
Syntax:
int strcmpi ( const char * str1, const char * str2 );

Example:
m=strcmpi(“ DELHI ”, “ delhi ”);  m = 0.

6) strlwr() function: strlwr() function converts a given string into lowercase.

Syntax:
char *strlwr(char *string);

strlwr( ) function is non standard function which may not available in standard library in C.
7) strupr() function: strupr( ) function converts a given string into uppercase.

Syntax:
char *strupr(char *string);

strupr( ) function is non standard function which may not available in standard library in C.

8) strrev() function: strrev( ) function reverses a given string in C language.


Syntax:
char *strrev(char *string);
strrev( ) function is non standard function which may not available in standard library in C.

This function reverses all the characters on a given string except null character in the last index.

9) strchr() function: strchr( ) function returns pointer to the first occurrence of the character in a
given string.
Syntax:
char *strchr(const char *str, int character);

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 63


10) strstr() function: strstr( ) function returns pointer to the first occurrence of the string in a given
string.
Syntax:
char *strstr(const char *str1, const char *str2);

11) atoi() function: It converts string-value to numeric-value and it converts a numeric-string value
to equivalent integer-value.

Syntax:
int atoi(string);

6. Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by
the compiler.

Suppose we declare an array arr,

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

Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.

arr is equal to &arr[0] // by default

We can declare a pointer of type int to point to the array arr.

int *p;

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 64


p = arr;

or p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to another.

NOTE : You cannot decrement a pointer once incremented. p-- won't work.

Pointer to Array

As studied above, we can use a pointer to point to an Array, and then we can use that pointer to
access the array. Lets have an example,

int i;

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

int *p = a; // same as int*p = &a[0]

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

printf("%d", *p);

p++;

In the above program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 65


Pointer to Multidimensional Array

A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an
array. As we know now, name of the array gives its base address. In a[i][j], a will give the base
address of this array, even a+0+0 will also give the base address, that is the address
of a[0][0] element.

Here is the generalized form for using pointer with multidimensional arrays.

*(*(ptr + i) + j)

is same as

a[i][j]

Pointer and Character strings

Pointer can also be used to create strings. Pointer variables of char type are treated as string.

char *str = "Hello";

This creates a string and stores its address in the pointer variable str. The pointer str now points to
the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 66


char *str;

str = "hello"; //thi is Legal

The content of the string can be printed using printf() and puts().

printf("%s", str);

puts(str);

Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use
indirection operator *.

Array of Pointers

We can also have array of pointers. Pointers are very helpful in handling character array with rows
of varying length.

char *name[3]={

"Adam",

"chris",

"Deniel"

};

//Now see same array without using pointer

char name[3][20]= {

"Adam",

"chris",

"Deniel"

};

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 67


K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 68
UNIT – III

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 69


UNIT - III
Pointer Variables – Pointer Operators - Pointer Expressions – Pointers And Arrays – Multiple
Indirection – Initializing Pointers – Pointers to Functions – C‟s Dynamic Allocation Functions –
Problems with Pointers.
Understanding the scope of Functions – Scope Rules – Type Qualifiers – Storage Class Specifiers-
Functions Arguments –The Return Statement.
1. Pointers
Pointer is a special kind of variable used to store address of memory location through which
indirect memory accessing can be performed.
When variables are declared memory is allocated to each variable. C provides data
manipulation with addresses of variables therefore execution time is reduced. Such concept is
possible with special data type called pointer. A pointer is a variable which holds the address of
another variable or identifier this allows indirect access of data.
We know that memory is a collection of bits, in which eight-bits constitute one byte.
Each byte has its own unique location number called its “address”. To store this address we need
a special kind of variable called “pointer variable”.
To work with pointers we have two unary operators
1. Reference operator(&)
2. De-reference operator(*)

The ‘&’ and ‘*’ operators work together for referencing and de-referencing.

Reference operator (&):

This referencing operator is also called address operator, which gives the address of a
variable, in which location the variable is resided in the memory.

Syntax: &variable-name;
k  variable name
For example: int k=10; 10  value

2020 2021  assumed address

Printf(“\n The address of k=%u”, &k);


Printf(“\n The value of k=%d”, k);

Output: The address of k=2020


The value of k=10

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 70


∑ Here the expression ‘&k’ gives the address of ‘k’ in which it is stored, the format string %u
or %p is used to print address.
∑ Here the expression ‘&k’ is pronounced as “address of k”, the space for ‘k’ at run time may
be allocated anywhere in the RAM, and to get the address of ‘k’, reference operator is used.
∑ The address of a variable may not be a fixed location like 2020 above, and is randomly given
by the computer.

De-reference operator (*):

This operator is used to get the value at a given address. For example,*(2020)‡ 10;
The value at address 2020 is 10, this is k’s value
The action of ‘de-referencing operator’ is just contrary to the action of referencing
operator, this is also called ‘indirection operator’ as it changes the direction of control from
location to another location within the program’s memory to access the required data,
Syntax: *addressable _expression;

For example: printf (“\n the value of k=%d”,*&k); //output=10

*&k‡*2020‡10
*&k‡ k ‡10

The reference operator (&) gives the address of ‘k’, whereas de-reference operator (*)
gives value in that address, so finally it is ‘k’ value.
1.1 Declaration:

To differentiate ordinary variables from pointer variable, the pointer variable should
proceed by called “value at address operator”. It returns the value stored at particular address. It
is also called an indirection operator (symbol *).
Pointer variables must be declared with its type in the program as ordinary variables.
Without declaration of a pointer variable we cannot use in the program.
A variable can be declared as a pointer variable and it points to starting byte address of
any data type.
Syntax:
data type *pointer variable;

The declaration tells the compiler 3 things about variable p

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 71


a) The asterisk (*) tells that variable p is a pointer variable
b) P needs a memory location
c) P points to a variable of type data type.
Example: int * p, v;
float *x;

In the first declaration v is a variable of type integer and p is a pointer variable. v stores value, p
stores address
In the 2nd declaration x is a pointer variable of floating point data type.

Pointer variables are initialized by p=&v, it indicates p holds the starting address of integer
variable v.
int v=20,*p;

p=&v; /*address of v stored in p*/ v p


20 1000

Let us assume that address of v is 1000.


This address is stored in p. Now p holds address of v, now *p gives the value stored at the
address pointer by p i.e. *p=20.
IMPORTANT POINTS:

1. A pointer variable can be assigned to another pointer variable, if both are pointing to the same
data type.
2. A pointer variable can be assigned a NULL value.
3. A pointer variable cannot be multiplied or divided by a constant.
Example: p*3 or p/3 where p is a pointer variable

4. C allows us to add integers to or subtract integers from pointers.

Example: p1+4, p2-2, p2-p1

If both p1, p2 are pointers to same way then p2-p1 gives the number of elements between p1, p2

5. Pointer variable can be incremented or decremented p++ & p- -

The values of a variable can be released in to way

1. By using variable name


2. By using adders.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 72


1.1 Pointer and functions:

∑ Pointers can be passed as argument to a function definition.


∑ Passing pointers to a function is called call by reference.
∑ In call by reference whatever changes are made in formal arguments of the function
definition will affect the actual arguments in calling function.
∑ In call by reference the actual arguments must be pointers or references or addresses.
∑ Pointer arguments are use full in functions, because they allow accessing the original data in
the calling program.

Program1: The following program is an example of pointer and functions

# include < stdio.h>


void swap (int *, int *);

main ( )
{
int a=10, b=20;
swap(&a, &b); /* a,b are actual parameters */
printf (“a= %d \t b=%d ”, a ,b);
}
void swap (int *x , int *y) /* x, y are formal parameters */
{
int t;
t = *x;
*x=*y;
*y=t;
}

Output:
a=20 b= 10

Program2:The following program is an example of pointer to functions.

# include < stdio.h>


# include < conio.h>
void copy (char *, char *);
main ( )
{
char a[20], b[20];
printf (“ Enter string a:”);
gets(a);
printf (“ Enter string b:”);
gets(b);
printf (“ Before copy “ );
printf (“ a=%s and b=%s ”, a , b);
copy(a ,b);
printf (“After copy “);
printf (“ a=%s and b=%s”, a , b);
}

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 73


void copy (char *x, char *y)
{
int i=0;
while ((X[i]=Y[i]) != “\0‟)
i++;
}

Output:
Enter string a: computer
Enter string b: science
Before copy
a=computer and b= science
After copy
a=science and b=science

1.3 Pointer and arrays:

Pointer can be used with array for efficient programming. The name of an array itself
indicates the stating address of an array or address of first element of an array.
That means array name is the pointer to starting address or first elements of the array. If
A is an array then address of first element can be expressed as &A[0] or A. The Compiler
defines array name as a constant pointer to the first element.
Pointers and arrays are closely related, the array expressions can be taken as pointer
expressions, for example x[i] can be written as *(x+i)

Example: &x [0]‡&*(x+0)‡x therefore x‡&x[0];

Hence, the expression “array name” without any index gives the address of first element which is
called base-address of array.
Assuming that the base address of arr is 1000 and each integer requires two byte, the five elements
will be stored as follows

Element arr [0] arr [1] arr [2] arr [3] arr [4]

Address 1000 1002 1004 1006 1008

Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e. 1000.
arr is equal to &arr[0] // by default

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 74


We can declare a pointer of type int to point to the array arr.

int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to
another.

NOTE: You cannot decrement a pointer once incremented.

Program: The following program is an example of pointer arrays.

#include<stdio.h>
#include< conio.h>
void disp (int *, int);
main( )
{
int i, a[10],n;
printf (“ enter the size of an array:”);
scanf (“%d”, &n);
printf (“ enter the array elements:”);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
disp (a,n);
printf(“ array elements after sorting ” );
for(i=0;i<n;i++)
printf (“%d”, a[i]);
}
void disp(int a[ ], int n)
{
int i,j, temp;
for (i=0; i<n; i++)
for (j=0; j<n; j++)
{
if (a[j] > a[i])
{
temp = a[ j ];
a[ j ] = a[ i ];
a[ i ] = temp;
}
}
}

Output:
Enter the size of an array: 5
Enter the array elements: 20 30 10 50 40
Array elements after sorting: 10 20 30 40 50

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 75


1.3 Pointer and Character array:

Pointer can also be used to create strings. Pointer variables of char type are treated as
string. Pointers are very useful in accessing character arrays. The character strings can be
assigned with a character pointer.
Example:
char array[ ] = “Love India”; //array version
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now
points to the first character of the string "Hello". Another important thing to note that string
created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not
need to use indirection operator *.
Program: The following program is an example of pointer and character array.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = “\0”)
{
printf (“ %c “, *p);
p++;
}
}

Output:
Love India

1.4 Pointer Arithmetic:

An integer operand can be used with a pointer to move it to a point / refer to some other
address in the memory.
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is
always 2 bytes. But when we perform any arithmetic function like increment on a pointer,
changes occur as per the size of their primitive data type.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 76


Consider an int type ptr as follows

65494
int * mptr ; mptr

Assume that it is allotted the memory address 65494 increment value by 1 as follows.

mptr ++; or ++ mptr;


mptr = mptr +1; or mptr + =1 ;

++ and -- operators are used to increment, decrement a ptr and commonly used to move the ptr to
next location. Now the pointer will refer to the next location in the memory with address 65496.

C language automatically adds the size of int type (2 bytes) to move the ptr to next memory location.
mptr = mtpr + 1
= 65494 + 1 * sizeof (int)
= 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the -
resultant address is dependent on the size of data type of ptr.

The step in which the ptr is increased or reduced is called scale factor. Scale factor is nothing but
the size of data type used in a computer.
We know that, the size of
float = 4
char = 1
double = 8 and so on

Example:
float *xp; (assume its address = 63498)
xp = xp + 5;

Will more the ptr to the address 63518

 63498 + 5 * size of (float)


 63498 + 5*4
 63498+20
 63518
Rules for pointer operation:
The following rules apply when performing operations on pointer variables

 A pointer variable can be assigned to address of another variable.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 77


 A pointer variable can be assigned the values of other pointer variables.
 A pointer variable can be initialized with NULL or 0 values.
 A pointer variable can be prefixed or post fixed with increment and decrement operator.
 An integer value may be added or subtracted from a pointer variable.
 When two pointers points to the same array, one pointer variable can be subtracted from
another.
 When two pointers points to the objects of same data types, they can be compared using
relational
 A pointer variable cannot be multiple by a constant.
 Two pointer variables cannot be added.
 A value cannot be assigned to an arbitrary address.

2.Memory allocation systems


The C language supports two kinds of memory allocation through the variables in C
programs:
1. Static allocation
2. Dynamic allocation

2.1 Static allocation:


If size or count of variables is known at coding time then static allocation is the good
choice, the static system is managed by the compiler by adding necessary instructions in the
program for allocation/de-allocation of memory for variables. So programmer need not bother
how variables are created and destroyed in the program.
Static allocation is what happens when you declare a static or global variable. Each static
or global variable defines one block of space, of a fixed size. The space is allocated once, when
your program is started (part of the exec operation), and is never freed.

2.2 Dynamic allocation:


In many real systems, the size of memory and objects are not known and cannot be determined
until runtime. Here dynamic system is the alternative to the programmer. Dynamic allocation
refers to the allocation of such memory during program execution. Here programmer needs to
allocate & de-allocate the memory with the help of pointers.
This dynamic memory allocation system provides us to create, expand, reduce, or even destroy
the memory at runtime. This feature is very much useful for efficient memory management
especially while handling huge collection of data using “data structures” for example lists,
stacks, trees, graphs.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 78
To work with this feature, C provides the following built-in functions:
1. malloc()
2. calloc()
3. realloc()
4. free()

1.malloc():
The name malloc stands for "memory allocation". It allocates memory of required size
and returns the address of starting byte (base address). In this allocation raw memory, we can
store any type of data such as int, long, float, double, char, etc. So malloc() returns an address
which has no type. That is, it returns ‘void*’ type address called generic address. Unfortunately,
if memory is not available then malloc() or other functions returns NULL value.
Syntax: void* malloc(int num)
Example: pointer=malloc(no of bytes to be allocated);
P=malloc(10);
In the above example, the function malloc() allocates 10 bytes of memory in the RAM and
returns the starting byte address, which is then assigned to ‘p’. Suppose if we are going to store
array of integers then the pointer should be ‘int*’ type. malloc() returns just address which has
no type, that is it returns ‘void*’ type address. So it should be type casted as per our pointer
type.(All malloc(), calloc(), and realloc() functions return-type is void* type)
Example: int *p;
p= (int*)malloc(5*sizeof(int)); //Allocating memory for 5 integers
Accessing dynamic memory:
Accessing this memory is same as accessing elements in the array through pointer.
*(p+0)‡p[0] accesses first location
*(p+1)‡p[1] accesses second location
*(p+2)‡p[2] accesses third location
*(p+ i)‡p[i] accesses i+1th location

2.calloc():
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.

The calloc function allocates space for an array of items and it is also like malloc(), but after
allocation of memory, it clears the garbage values by filling zeros in all bytes in the memory.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 79
Syntax: pointer=calloc(int num, int size);
It takes two arguments, first one is number of items to be allocated and second one is size of
the item.
Example: float *p;
p=(float*)calloc(5,sizeof(float)); //allocating memory for 5 float numbers

Difference between malloc() and calloc() functions in C:

S.no malloc() calloc()


1 It al-locates only single block of requested It allocates multiple blocks of requested
memory memory
2 int *ptr, ptr = malloc( 20 * sizeof(int) );For the int *ptr; Ptr = calloc( 20, 20 * sizeof(int)
above, 20*4 bytes of memory only );For the above, 20 blocks of memory
allocated in one block. will be created and each contains 20*4
Total = 80 bytes bytes of memory.
Total = 1600 bytes
3 malloc () doesn’t initializes the allocated calloc () initializes the allocated memory to
memory. It contains garbage values zero
4 type cast must be done since this function Same as malloc () function int *ptr; ptr =
returns void pointer int *ptr; ptr = (int*)calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20 );

3.realloc():
The name realloc() stands for “reallocation”. If the previously allocated memory is
insufficient or more than sufficient. Then, you can change memory size previously allocated using
realloc().
It is used to resize (reduce or expand) the memory which is already allocated using
“malloc()” or “calloc()” or “realloc()”. It takes base address of previously allocated memory and
new size which is currently required.
While expanding the memory size using “realloc()”, if the required amount of memory is not
available at the consecutive locations, then allocates memory at another available location, and
copies the existing contents to the newly allocated memory area and then releases the old memory.
If the memory is not available, then it returns null.

Syntax: ptr=realloc(ptr, new size);

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 80


4.free():
It is used to release the memory which is no longer required by the program. This
memory must not be static(int a[10]). This must be a dynamic memory which is allocated by
malloc() or other functions. It takes the base address of memory as an argument and frees.
Syntax: void free(void *ptr);
If a null pointer is passed as argument, no action occurs. And this function does not return
any value.
3. FUNCTIONS
ÿ C allows programmers to define their own functions for carrying out various individual tasks.
The use of programmer defined functions allows a large program to be broken down into a number
of smaller self contained components.
ÿ Many programs require that a particular group of instruction may be accessed repeatedly,
from several different places within the program.
ÿ The repeated instructions can be placed within a single function.
ÿ The use of a function avoids the need for redundant (repeated) programming of the same
instructions.
ÿ Such programs are easier to write or easier to debug.
Def: a function is self contained program segment that carries out some specific well defined task.
ÿ Execution of the program will always begin by carryingout the instructions in main. If a
program contains multiple functions their definitions may appear in any order though they must be
independent of one another.
ÿ The same function ca be accessed from several different places within a program.
ÿ Once the function has carried out its intended action the control will e returned to the point
from which the function was accessed.
ÿ The user is always free to define its own functions and then use it such functions are called
user defined functions.

Function prototype
The programmer defined function has always precede main. The general for of a function prototype
is
Datatype fun-name(type1 arg1, type2 arg2, type3 arg3 . . . . . . . . . . . type-n arg-n)

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 81


Where datatype represent the type of the item that is returned by the function.
Fun-name represent the function name.
Type1 ,type2, type3. . . .. . . .. . type-n represent the data type of the arguments arg1,arg2,arg3,. . . . . .
argn. The arguments name with in the function are dummy.
Why should we use a function?
a) By using function, it becomes easy to write program and keep trace of what they are doing.
b) Length of the program can be reduced by using function.
c) Debugging is easier.
d) It facilitates top – down modular programming.
e) Using functions avoids rewriting the some code over and over.
Classification’ of functions:
‘C’ functions can be classified into two categories.

Library functions:
They are predefined in the standard library of ‘c’. We need to include the library functions
such as sin(x), cos(x), pow(x), sqrt(n) etc. The code of these functions is not available to the user. So
they can not modify these functions.
User defined functions:
These functions are used need to be developed by the user at the time of program writing.
Functions break large computing tasks into smaller ones, which help in the modular development of
big program.
There are three steps involved in creating and using of User Defined functions.
1. Declaring of function prototype.
2. Defining a function.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 82


3. Calling a function.
Top – down design and structure charts:
In top down design, a problem is divided into a main module and its related and its related
modules.
Each module is in turn divided into sub modules until the resulting module intrinsic; that is until they
are implicitly understood without further division.
Def:
The process of sub dividing a program in to manageable parts known as “Top- Down
design”.
¸ Top down design is usually done using visual representation of the modules known as a
“Structure chart”.

Structure chart
¸ The main module is known as a calling module because it has sub modules.
¸ Each of the sub modules is known as a called module.
¸ But because module 1, 2 &3 also have sub modules they are also called modules, they are
both called and calling modules.
¸ The technique used to pass data to a function is known as “parametric passing”.

User defined functions:


These functions allow user to define their own function according to the
requirement of program. Any ‘c’ function is defined in the following formats.
Syntax:
return_type func-name(datatype arg1,datatype arg2 ,………..datatype argn)

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 83


{
Local variables;
Executable_stmt 1;
Executable_stmt 2;
----------------
-----------------
return(expression);
}
e.g:
int sum(int a,int b)
{
int s;
s=a+b;
return(s);
}
Func- name:
Each function is recognized by its name. In the given examples ‘sum’ is a function name. It
follows of an identifier.
Arguments:
The arguments in function are always variables. They can be declared in two ways as shown
in format and format 2.
Return statement:
It can be written in two ways depending on the requirements.
return (expression);
Or
return;

return (expression):
This statement returns the value of expression to be called function.
E.g: return (a, b)
return (a);
return:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 84


This specifies returns control to calling function but not return any value. There can be any
number of return statements in the program but each statement can return only one value.
¸ If no value is returned to the calling function then the return type is declared as void.
Function call:
The statement which is used to call a function is called as “function call”.
Function definition:
Actual code of a function is known as “function declaration”.
Function declaration:
All identities in ‘c’ need to be declared before they are used .This is true for
functions as well as variables, for function the declaration needs to be before the first can of the
function.
e.g:
void main()
{
Void greet ();
greet ();
}
void greet ( )
{
printf(“Happy New Year”);
}
Arguments used in function:
Depending on the location of argument in functions they are categorized as actual parameter
and formal parameter.
Actual Parameters:
The parameters which are passed in function call are known as actual parameters. They are
defined in calling function and they can be expressions, constants or variables.
Formal parameters:
The parameters which are used in function defined are called formal functional
parameters.
¸ Formal parameters can only be variables. They can not be expressions or constants.
¸ The value of actual parameters is passed to formal parameters.
Void main( )
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 85
{
Statements;
function (a1,a2,………..an);
Statements;
}
function (f1,f2,…….fn)
Statements;
{
Statements;
}
Types of functions:
Depending on the return value and arguments passed as functions can be classified into 4
categories.
Functions without arguments and with out return values:
These are the functions in which no parameters are passed from calling function to called
function and values are returned from called function to calling function.
#include<stdio.h>
void sum( );
void main()
{
sum( );
getch();
}
void sum()
{
int a=10,b=20,c;
c=a+b;
printf("Sum of 2 numbers is %d",c);
}
Function with arguments and with out return values:
These are the functions in which arguments are passed from called function to calling
function.
#include<stdio.h>
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 86
void sum(int x,int y);
void main()
{
int a=10,b=20;
sum(a,b);
getch();
}
void sum(int x,int y)
{
int z;
z=x+y;
printf("sum of 2 numbers is %d",z);
}
Function with out arguments and with return values:
In this no arguments are passed from called function to calling function but values are
returned from called function to calling function.
#include<stdio.h>
int sum();
void main()
{
int z;
clrscr();
z=sum();
printf("sum of 2 numbers is %d",z);
getch();
}

int sum()
{
int a=10,b=20,c;
c=a+b;
return(c);
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 87
Functions with arguments and with return values:
These are the functions in which parameters are passed from calling function to called
function and the values are returned from called function to calling function.
#include<stdio.h>
int sum(int,int);
void main()
{
int a=10,b=20,c;
c=sum(a,b);
printf("sum of 2 no is %d",c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}
Parameter passing techniques:
There are two types of passing parameters to functions
1. Call by value
2. Call by reference
Call by values:
The process of passing the actual values of variables is known as “call by values”.
Call by reference:
The process of calling a function using pointers to pass the address of variables is
known as “call by reference”.

Storage classes are used to:


1. Economized the memory space consumed by the variables.
2. Im3edcdcprove the space of exclusion of the program.
Recursion

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 88


Recursion is a process by which a function calls itself repeatedly, until some specified condition has
been satisfied.
The process is used for repetitive computations in which each action is stated in terms of a previous
result.
In order to solve a problem recursively two conditions must be satisfied:
First the problem must be written in a recursive form,
And second the problem statement must include a stopping condition.
Example program
Finding the factorial of a number usin recursion
#include<stdio.h>
int factorial(int n);
void main()
{
int n;
printf(“enter n value\n”);
scanf(“%d”,&n);
printf(“n!= %d\n”,factorial(n));
getch();
}
int factorial(int n);
{
if(n<=1)
return(1);
else
return(n*factorial(n-1));
}

output
enter n value 5
n!=120.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 89


4.Storage Classes
ÿ To fully define a variable one needs to mention not only its type but also its storage class.
There are two types of locations where variables can be stored there are memory and CPU
registers.
Usage of Storage Classes:
It gives us information about the following things.
ÿ Where the variables would be stored.
ÿ What would be the default initial value?
ÿ What is the scope of the variable i.e., availability of the variable
ÿ What is the life-time of a variable i.e. ,the time up to which the value persists in the variable
ÿ There are 4 storage classes available namely.
o Automatic variable
o Register variable
o Static variable
o External variable

Automatic variable:
ÿ These are declared within which they are used. They are also referred as internal (or) local
variables.
ÿ These variables are created when a function is called, and destroyed automatically when a
function is excited.
ÿ Automatic variables are given only temporary memory space.
ÿ Local variables are given the storage class auto by default. The keyword auto is used to
declare automatic variables.
ÿ The Automatic variables have two distinct advantages.
Advantages:
ÿ The memory space is used economically since it is used only as long as it is needed.
ÿ There local scope prevent from affecting other functions due to inadvertent changes.
Example program for automatic variable
#include<stdio.h>
#include<conio.h>
void main()
{
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 90
auto int x,i;
for(i=0;i<=3;i++)
{
x=1;
x++;
printf(“the value of x in iteration%d is : %d”,i,x);
}
getch();
}
Output:
The value of x in iteration1 is :2
The value of x in iteration2 is :2
The value of x in iteration3 is :2
Register variable:
ÿ A register storage class is the same as the auto class with only one difference.
ÿ These variables are stored in CPU registers and gets default initial as “garbage value”. Any
variable which is stored in the CPU registers can be accessed faster than the one which is stored
in memory.
ÿ This is done for effciency
ÿ If a variable is used at many places it is better to declare its storage class as register.
ÿ A good example for frequently used variables in looping counter.
main ( )
{
register int i;
for (i=1; i<=10; i++)
printf(“%d”,i);
}
ÿ Here, even though we have declared the storage class of ‘i’ as register, we are not sure that
the value of ‘i’ would be stored in a CPU register. Because the number of CPU registers is
limited {14 for micro computer} and these are busy in doing some other task. In those situations
it treats them as auto.
ÿ There are some restrictions on register variables. We can’t use register storage class for all
types of variab les. Since, CPU registers are 16 bit registers. They can’t hold float (or) double
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 91
963*.values which require 4 & 8 bytes respectively. Even though we use register for float and
double we don’t get any error because they treat as auto.
Static variable:
ÿ As the name suggest that the value of the static variable persists until at the end of the
program i.e., the contents of the variable will be retained.
ÿ A variable can be declared as static by using the keyword “static”.
ÿ A static variable may be either an internal type (or) an external type depending upon the
place of declaration.
ÿ The scope of internal static variable extends up to the end of the function in which they are
defined.
ÿ The internal static variables are similar to automatic variables. The difference between them
is the static variables do not disappear when the function is no longer active. Their values are
persisting(can not be changed).
ÿ If the control comeback to the same function again the static variables have the same value.
Internal static variables can be used to retain values between function call.
ÿ A static variable is initialized only once and it takes default initial value as zero.
ÿ When the program is compiled it will never initialized again.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
clrscr();
for(i=1;i<=3;i++)
{
static x=1;
x++;
printf("the value of x in itration %d is:%d\n",i,x);
}
getch();
}
Output:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 92


STATIC VARIABLE WITH FILE SCOPE IS:
#include<stdio.h>
#include<conio.h>
void fun(void);
static int x=1;
void main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
x++;
printf("the value of x in main is:%d\n",x);
fun();
printf("the value of x in maj is : %d \n",x);
getch();
}
void fun(void)
{
x++;
prin/tf("the value of x in function is :%d \n ",x);
}
OUTPUT:

External variable:
ÿ Here the variable is both alive and active throughout the entire program. They are also known
as “Global variables”.
ÿ Unlike local variables, global variables can be accessed by any function in the program.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 93
ÿ These variables are defined by using the keyword “extern”.
Eg: main ()
{
extern int i=5;
printf(“%d”,i);
}
ÿ We can also define these variables without using keyword. At that time we declare variables
outside the function.
int x=20;
main()
{
int y;
printf(“%d”,x);
}
ÿ The default initial value of external variable is a “garbage” value.

Location of Default Scope Life Time


Storage Value
Automatic Memory Garbage Local within the function in which it
Value has been declared.
Register CPU Registers Garbage Local within the function in which it
Value has been declared.
Static Memory Zero Local the value persist till the end of
the program.
External Memory Garbage global Entire Program.
Value

5.Type qualifiers: The keywords which are used to modify the properties of a variable are called
type qualifiers.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 94


TYPES OF C TYPE QUALIFIERS:
There are two types of qualifiers available in C language. They are,
1. const
2. volatile
1. CONST KEYWORD:
∑ Constants are also like normal variables. But, only difference is, their values can’t be modified
by the program once they are defined.
∑ They refer to fixed values. They are also called as literals.
∑ They may be belonging to any of the data type.
∑ Syntax:
const data_type variable_name; (or) const data_type *variable_name;
∑ Please refer C – Constants topic in this tutorial for more details on const keyword.
2. VOLATILE KEYWORD:
∑ When a variable is defined as volatile, the program may not change the value of the variable
explicitly.
∑ But, these variable values might keep on changing without any explicit assignment by the
program. These types of qualifiers are called volatile.
∑ For example, if global variable’s address is passed to clock routine of the operating system to
store the system time, the value in this address keep on changing without any assignment by the
program. These variables are named as volatile variable.
∑ Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 95


UNIT-IV

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 96


UNIT - IV
Command line arguments – Recursion – Function Prototypes – Declaring Variable Length Parameter
Lists
Structures – Arrays of Structures – Passing Structures to Functions – Structure Pointers – Arrays and
Structures within Structures – Unions – Bit Fields – Enumerations – typedef

1. Command Line Arguments


Just like other functions, main() can also receive the arguments and return a value.
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments.
We can execute a program (executable file) from operating system’s command prompt by just
typing the program name as shown below
C:\tc\bin\> sum.exe //here “.exe” is optional
(Suppose if our program is “sum.c” then its compiled version will be “sum.exe”)
When a program is run, the operating system loads exe file into memory and invokes the startup
function i.e. main(). Here, we can assume the OS is the caller of main() function. Therefore, the
arguments can be passed to the main() function by specifying a list of values at the command
line as shown below.
C:\tc\bin\> sum 10 20 30
Unlike other functions, the arguments to main() are passed in a different manner. They are
passed as string constants. That means, even if we give integer values, they passed as string. In
this case, the arguments passed as “sum”, “10”, “20”, “30”.(passed as array of addresses to the
main())
But main() receives two arguments, the fist argument is integer, which specifies the count of
arguments including file name. The second argument is an array of addresses containing strings.
Thus main() function should be defined as
void main(int argc, char *argv[])
{
-----------
-----------
}
argc – Number of arguments in the command line including program name

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 97


argv[ ] – holds addresses of all string constants that are passed to the program.
The input arguments should be separated by space or tab, but not with comma …etc.
Program1: The program receives integer numbers from command line and display the sum of
them
#include<stdio.h>
main(int count, char *argv[])
{
int sum=0,i=0;
for(i=1;i<count; i++)
sum=sum+atoi(a[i]); // atoi() function converts numeric string to integer value
printf(“\n sum of numbers=%d”, sum);
}

Output:
C:\tc\bin\>sum 10 20 30 40
Sum of numbers=100

Program2:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf(“Arguments passed through command line “ \ “not equal to 5”);
return 1;
}
printf(“\n Program name : %s \n”, argv[0]);
printf(“1st arg : %s \n”, argv[1]);
printf(“2nd arg : %s \n”, argv[2]);
printf(“3rd arg : %s \n”, argv[3]);
printf(“4th arg : %s \n”, argv[4]);
printf(“5th arg : %s \n”, argv[5]);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 98
return 0;
}
Output:
Program name: test
1st arg: this
2nd arg: is
3rd arg: a
4th arg: program
5th arg: (null)
2. Structures
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
In real life we need to have different data types for ex: To maintain employee
information. We should have information such as name, age, qualification, salary etc. here to
maintain the information of employee dissimilar data types required. Name & qualification are
char data type, age is integer, and salary is float. You can create this information separately but,
better approach will be collection of this information under single name because all these
information are related to person.
Structure is a collection of heterogeneous type of data i.e. different types of data. The
various individual components, in a structure can be accessed and processed separately. A
structure is a collection of variables referenced under a name, providing a convenient means of
keeping related information. A structure declaration forms a template that may be used to create
structure objects.
Difference between C variable, C array and C structure:
∑ A normal C variable can hold only one data of one data type at a time.
∑ An array can hold group of data of same data type.
∑ A structure can hold group of data of different data types
∑ Data types can be int, char, float, double and long double etc.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 99


Datatype C variable C array C structure
Syntax Example Syntax Example Syntax Example
int int a a = 20 int a[3] a[0] = 10 struct student a = 10
a[1] = 20 { b=“Hello”
a[2] = 30 int a;
a[3] = ‘\0’ char b[10];
}
char char b b=’Z’ char b[10] b=”Hello”

Features of Structures:
To copy elements of one array to another array of same data type elements are copied one by
one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the
contents of all structure elements of different data types to another structure var of its type using
assignment (=) operator. It is possible because structure elements are stored in successive
memory locations.
Nesting of structures is also possible.
Defining a structure:
‘struct’ keyword is used to define a structure, struct define a new data type which is a
collection of different type of data.
Syntax:
struct structure_name
{
//Statements
};

Example:
struct Book
{
char name[15];
float price;
int pages;
};

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 100


Here the struct Book declares a structure to hold the details of book which consists of three data
fields, namely name, price and pages. These fields are called structure elements or members. Each
member can have different data type, like in this case, name is of char type and price is of float type
etc. Book is the name of the structure and is called structure tag.
Structure Initialization:
Like any other data type, structure variable can also be initialized at compile time.
Example:
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Accessing members of a structure:
There are two types of operators used for accessing members of a structure.
∑ Member operator (.)
∑ Structure pointer operator (‡)

Any member of a structure can be accessed as:


Syntax:
structure_variable_name.member_name

Suppose, if we want to access age for variable p1. Then, it can be accessed as:
P1.age;
Eg. Write a program to display student details
#include<stdio.h>
#include<conio.h>

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 101


void main()
{
struct student
{
char name[30];
char course[40];
int age;
int year;
};
struct student s= {"yuva","cse",20,2010};
printf(" %s %s %d %d \n",s.name,s.course,s.age,s.year);
getch();
}
Output:
Yuva cse 20 2010

2.1 Pointer to a structure:


It is also possible to create structure pointers. We can also create a pointer, pointing to structure
elements.
For this we require “‡” operator.
The arrow operator (‡) introduced in second version of C language, it is a shortcut operator to
access members of a structure through pointer.
If user-defined type is “struct student”, then its pointer type is “struct student*”
For example: struct student *p; // p is a pointer variable to structure
P=&s1; //making pointer ‘p’ to s1

P S1
100 BGS 45 78 47
p p‡name p‡marks1 p‡marks2 p‡marks3

The expression “(*p).id” is equal to “p‡id”


The expression “(*p).name” accesses the “name” in s1.
“(*p).name” is equal to “p‡name”

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 102


Program: The following program is an example of pointer to a structure.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1; //Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

strcpy( Book1.title, "C Programming");


strcpy( Book1.author, "vinay");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "naveen");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

printBook( &Book1 );
printBook( &Book2 );
return 0;
}

void printBook( struct Books *book )


{
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 103
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
Output:
Book title: C Programming
Book author: vinay
Book subject: C Programming Tutorial
Book book_id: 6495407
Book title: Telecom Billing
Book author: naveen
Book subject: Telecom Billing Tutorial
Book book_id: 6495700
2.2 Array of structures:-
A structure is simple to define if there are only one or two element, but in case there are too
many objects needed for a structure, for ex. A structure designed to show the data of each student of
the class, and then in that case, the way will be introduced. A structure declaration using array to
define object is given below.
Example: struct student
{
char name [15];
int roll no;
char gender;
};
student data[50];
Initializing array of structures:-
It is to be noted that only static or external variable can be initialized.
Example: struct employee
{
int enum;
char gender;
int sal;
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 104
};
employee data [3] = { {146, ‘m’, 1000}, {200, ‘f’, 5000}, {250, ‘m’, 10000}};
If incase, the structure of object or any element of struct are not initialized, the compiler will
automatically assigned zero to the fields of that particular record.
Example:
employee data [3] = { { 146,’m’} ,{ 200, ‘f’ },{250 ,’m’}};
Compiler will assign:-
data [0].sal=0; data [1].sal=0; data [2].sal=0;
Program: The program to initialize the array of structure members & display
#include<stdio.h>
void main ()
{
int i;
struct student
{
long int rollno;
char gender;
float height;
float weight;
};
struct student data [3] = { {121,’m’,5.7,59.8},{122,’f’,6.0,65.2},{123,’m’, 6.0, 7.5} };
clrscr ();
printf (“the initialized contents are:\n”);
for ( i=0; i< =2; i++)
{
printf (“%d/n ** Record is \n “, data [i].rollno);
printf (“%c\n“, data [i] .gender);
printf (“%f\n”, data [i].height);
printf (“%f\n”, data [i]. weight);
}
}
Output:
The initialized contents are:
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 105
121
** Record is m
5.700000
59.799999
122
** Record is f
6.00000
65.19997
123
** Record is m
6.000000
7.500000
2.4 Passing Structures To Functions
ÿ There are several different ways to pass structure-type information to or from a function.
Structure members can be transferred individually, or entire structures can be transferred.
ÿ Individual structure members can be passed to a function as arguments in the call and a
single structure member can be returned via return statement.
ÿ To do that each structure member is treated the same as an ordinary single valued variable.
Write a program to pass structure elements to function print () and print the elements.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct boy
{
char name[25];
int age;
int wt;
};
void main()
{
struct boy b1={"siva",29,72};
print (b1);
}
print (struct boy b)
{
clrscr();
printf("\n %s %d %d", b.name,b.age,b.wt);
getch();
}
Output:

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 106


siva 29 72

Write a program to pass address of structure variable to a user defined and display the
contents.

#include<stdio.h>
#include<conio.h>
struct book
{
char name[23];
char author[25];
int pages;
};
void main()
{
struct book b1={"java","james",998};
show(&b1);
}
show(struct book *b2)
{
clrscr();
printf(" \n %s by %s of %d pages",b2->name,b2->author,b2->pages);
getch();
}
Output:
Java by James of 998 pages

2.4 Self Referential Structures


It is sometimes desirable to include within a structure one member that is a pointer to the parent
structure type.
This can be expressed as
Struct tag
{
Member 1;
Member 2;
…………………………….
Struct tag *name;
};
ÿ Where name refers to the name of a pointer variable thus, the structure of type tag will
contain a member that points to another structure of type tag. Such structures are known as
self referential structure .
ÿ Self referential structures are very useful in applications that involve linked data structures,
such as lists, and trees.
ÿ The basic idea of a linked data structure is that each component within the structure includes
a pointer indicating where the next component can be found. In addition individual
components can easily be added or deleted again by altering the pointers.
Example
struct list
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 107
{
char item[40];
struct list *next;
};
ÿ This is structure of type list. The structure contains two members, a 40 element character
array, called item and a pointer to a structure of the same type(i.e., a pointer to a structure of
type list), called next.
ÿ Therefore this is a self-referential structure.
ÿ The following example illustrates a linked list containing three components. Each component
consists of two data items. A string and a pointer that references the next component within
the list.
ÿ The first component contains the string red,
ÿ The second contains green and the third contains blue.
ÿ The beginning of the list is indicated by a separate pointer which is labeled start. Also the end
of the list is indicated by a special pointer, called NULL.

red green Blue NULL

Eg:#include<stdio.h>
void main()
{
struct node
{
int data;
struct node *link;
};
struct node *a,*b,*c;
a->data=10;
b->data=20;
c->data=30;
a->link=b->link=c->link=null;
printf(“a=%d b=%d c=%d”,a->data,b->data,c->data);
getch();
}
A program to declare a self referential structure using dynamic allocation to display the
content of structure
#include<stdio.h>
void main()
{
struct node
{
int data;
struct node *next;
};
struct node *ptr;

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 108


printf(“enter any integer value:\n”);
scanf(“%d”,&ptr->data);
ptr->next=null;
printf(“%d\n”,ptr->data);
}

3.UNIONS :
ÿ Union is a variable, which is similar to the structure. It contains member of members like
structure but it holds only one object at a time.
ÿ In the structure each member has its own memory location, where as members of union have
same memory location.
ÿ It can accommodate one member at a time in asingle area of storage.
ÿ Union also contains members of type int, float, long, array, pointers,etc..
ÿ It allocates fixed specific bytes of memory for access of data types irrespective of any data
type.
ÿ The union requires bytes that are equal to the number of bytes for target members.
Eg.
ÿ The union contains char, integer, long integer then the number of bytes reserved in the
memory for the union is 4 bytes.
ÿ The difference union and structure is in terms of storage. When we used unions the compiler
allocates a piece of storage that is large enough to hold.
ÿ When union is defined C reserves enough room to store the largest data object in the
construct.
ÿ Union is declared by using union key word.
Syntax:
union union-name
{
member1;
member2;
……..2
member n;
};
union union-variable;
eg:
union result

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 109


{
int marks;
float avg;
char grade;
};
union result a;
here float data type contain highest memory space. That is 4 bytes is allocated to union result. To
access union members
a.marks;
a.avg;
a.grade;
example
program to find size of union and no.of byes reserved for it.
void main()
{
union result
{
int marks;
char grade;
};
struct std
{
char name[20];
int age;
char sex;
union result pr;
};
struct std data;
clrscr();
printf(“a size of union %d \n”,sizeof(data.pr));
printf(“size of structure %d ”,sizeof(data));
getch();
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 110
A program to demonstrate pointer to union
union res
{
int no;
char *ch;
float f;
};
void main()
{
res data;
res *ptr;
ptr=&data;
data.no=10;
printf(“union value is now %d”,ptr->no);
data.ch=’A’;
printf(“union value is now %d”,ptr->ch);
data.f=2.5;
printf(“union value is now %d”,ptr->f);
}
A program to use structure within union display contents of structure elements.
void main()
{
strcut x
{
float f;
char p[2];
};
union z
{
struct x set;
};
union z st;
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 111
st.set.f=5.5;
st.set.p[0]=65;
st.set.p[1]=66;
printf(“%f”,st.set.f);
printf(“%c”,st.set.p[0]);
printf(“%c”,st.set/p[1]);
getch();
Structure \ Unions

struct Emp union Emp


{ {
char x; //size 1 byte char x;
float y; //size 4 byte float y;
}e; }e;
Memory sharing

x y x&y

e(structure variable) e(union variable)


5 bytes 4 bytes Allocate storage
Equals to largest one

Differences between union and structure:


S.no C Structure C Union
1 Union allocates one common storage space for all
Structure allocates storage space for all its members. Union finds that which of its member
its members separately. needs high storage space over other members and
allocates that much space
2 Structure occupies higher memory
Union occupies lower memory space over structure.
space.
3 We can access all members of
We can access only one member of union at a time.
structure at a time.
4 Structure example: Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
For above structure, memory allocation will be
5 like below. For above union, only 8 bytes of memory will be allocated
int mark – 2 bytes since double data type will occupy maximum space of
char name[6] – 6 bytes memory over other data types.
double average – 8 bytes Total memory allocation = 8 Bytes
Total memory allocation = 2+6+8 = 16 Bytes

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 112


UNIT-V

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 113


UNIT - V
Reading and Writing Characters – Reading and Writing Strings – Formatted Console I/O – Printf -
Scanf – Standard C Vs Unix File I/O – Streams and Files – File System Basics – Fread and Fwrite –
Fseek and Random Access I/O – Fprintf ( ) and Fscanf( ) – The Standard Streams – The
Preprocessor Directives #define and #include.
1. File handling in c
A file is a place on disk where group of related data are stored. C supports a number of
functions that have the ability to perform basic file operations, which include:
∑ Creating a new file
∑ Opening a file
∑ Reading data from a file
∑ Writing data to a file
∑ Closing the file

Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to
keep large volume of data, it is time consuming to enter the entire data. But, if file is created, this
information can be accessed using few commands.
Working with file:
While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program.
Syntax: FILE *ptr;

C provides a number of functions that helps to perform basic file operations; all these
functions are available in stdio library.

Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 114


fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning point

Opening a file:
C communicates with files using a new data type called a file pointer. This type is
defined within stdio.h, and written as FILE *. A file pointer called output_file is declared in a
statement like
Syntax: FILE *output_file;
If we want to store data in a file into the secondary memory, we must specify certain things aboutthe
file to the operating system. They include the filename, data structure…
The general format of the function used for opening a file is
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the
file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 115


wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode

Return value:
C open function returns NULL in case of failure, and returns a FILE Stream Pointer on success
Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen(“fileName.txt”, “w”);
return 0;
}
∑ The above example will create file called fileName.txt
∑ The “w” means that the file is being opened for writing, and if the file does not exist then
new file will be created.

Closing a file:
∑ fclose() function is used to releases the memory stream, opened by fopen().
∑ The fclose() function is used to close an already opened file.
∑ A file must be closed as soon as all operations on it have been completed. This would close
the file associated with the file pointer.
∑ The input output library supports the function to close a file; it is in the following format.
Syntax:
int fclose( FILE * stream );

Return value:

Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 116


Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen(“fileName.txt” ,”w”);
fclose(fp);
return 0;
}

Reading a character from a file and writing a character into a file (getc() and putc() functions):
The getc and putc functions are analogous to getchar and putchar functions and handle one character
at a time. The putc function writes the character contained in character variable c to the file
associated with the pointer fp1. ex putc(c, fpl); similarly getc function is used to read a character
from a file that has been open in read mode. c=getc(fp2).

Program: The following program is an example to read a character from a file and to write a
character into a file
#include<stdio.h>
main()
{
FILE *fl;
char c;
printf(“Data input”);
fl =fopen(“Input.txt”, “w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc( c, fl); //write a character to input
fclose(fl); //close the file input
printf(‘Data output”);
fl =fopen(‘INPUT.txt” ,”r”); //Reopen the file input
while((c=getc(fl ))!=EOF)
printf(“%c”, c );
fclose(fl );

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 117


}

Reading a integer from a file and writing a integer into a file ( getw() and putw() functions):
These are integer-oriented functions. They are similar to getc and putc functions and are used to
read and write integer values. These functions would be useful when we deal with only integer data.
The general forms of getw and putw are: putw(integer, fp ); getw(fp);
putw() Example:

#include<stdio.h>
main()
{
FILE *fp;
fp=fopen(“file1.txt”,”w”);
putw(97,fp);
fclose(fp);
}
getw() example:

#include<stdio.h>
main()
{
FILE *fp;
int ch;
fp=fopen(“file1.txt”,”r”);
ch=getw(fp);
printf(“%d”, ch);
fclose(fp);
}

fscanf() and fprintf() functions:


The fprintf and fscanf functions are identical to printf and scanf functions except that they work
on files. The first argument of these functions is a file pointer which specifies the file to be used.
The general form of fprintf is
fprintf(fp, "controlstring", list);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 118
Where fp is a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
fprintf(fl ,”%s%d%f”,name,age,7 .5);
Here, name is an array variable of type char and age is an int variable the general format of
fscanf is
fscanf(fp, "controlstring" ,list);
This statement would cause the reading of items in the control string.
Program: The following program is an example of fscanf() and fprintf()
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

main()
{
struct emp e;
FILE *p,*q;
p = fopen(“one.txt”, “a”);
q = fopen(“one.txt”, “r”);

printf(“Enter Name and Age”);


scanf(“%s %d”, e.name, &e.age);
fprintf(p,{“%s %d”, e.name, e.age);
fclose(p);
do
{
fscanf(q,”%s %d”, e.name, e.age);
printf(“%s %d”, e.name, e.age);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 119
}
while(!eof(q));
getch();
}
Output:
Enter Name and Age: sai 24
Sai 24

fgets() and fputs() functions:


fgets() function reads string from a file pointed by file pointer. It also copies the string to a memory
location referred by an array.
fputs() function is useful when we want to write a string into the opened file .
Program: The following program is an example of fgets() and fputs()
#include<stdio.h>
main()
{
FILE *fp;
char file[12],text[50];
int i=0;
fp = fopen(“line.txt” ,”w”);
printf(“enter text here “);
scanf(“%s”, text);
fputs(text, fp );
fclose(fp);
fp = fopen(“line.txt”, “r”);
if(fgets(text,50,fp )!=NULL)
while(text[i]!='\0')
{
putchar(text[i]);
i++;
}
fclose(fp );
getch();

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 120


}

Output:
Enter text: Welcome
Welcome

ftell():
Functions ftell() and fseek() are important in a program performing file manipulations.
Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or
a positive integer indicating the byte offset from the beginning of an open file. A return value of
-1 indicates an error. Prototype of this function is as shown below:
long int ftell(FILE *fp);

fseek():
This function positions the next I/O operation on an open stream to a new position
relative to the current position.
int fseek(FILE *fp, long int offset, int origin);
Here fp is the file pointer of the stream on which I/O operations are carried on; offset is
the number of bytes to skip over. The offset can be either positive or negative, denting forward
or backward movement in the file. Origin is the position in the stream to which the offset is
applied; this can be one of the following constants:
SEEK_SET: offset is relative to beginning of the file
SEEK_CUR: offset is relative to the current position in the file
SEEK_END: offset is relative to end of the file
Program: The following program is an example of ftell() and fseek().
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen(“fileName.txt” ,”r”);
fseek( fp,21 ,SEEK_SET);
ch=fgetc(fp);
while(!feof(fp ))
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 121
{
printf(“%c” ,ch);
printf(“%d”, ftell(fp ));
ch= getc(fp );
}
rewind(fp );
while(!feof(fp))
{
printf(“%c” ,ch);
printf(“%d” ,ftell(fp));
ch= fgetc(fp);
}
fclose(fp );
}
Output: 0H1e2l3l4o5 6I7n8dgi10a11
SAMPLE PROJECT 1:
PROJECT NAME: EMPLOYEE RECORD SYSTEMS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h> ///for windows related functions (not important)
#include <string.h>

/** List of Global Variable */


COORD coord = {0,0}; /// top-left corner of window

/**
function : gotoxy
@param input: x and y coordinates
@param output: moves the cursor in specified position of console
*/
void gotoxy(int x, int y)
{
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 122
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

/** Main function started */


int main()
{
FILE *fp, *ft; /// file pointers
char another, choice;

/** structure that represent a employee */


struct emp
{
char name[40]; ///name of employee
int age; /// age of employee
float bs; /// basic salary of employee
};

struct emp e; /// structure variable creation

char empname[40]; /// string to store name of the employee

long int recsize; /// size of each record of employee

fp = fopen("EMP.DAT", "rb+");
if(fp == NULL)
{
fp = fopen("EMP.DAT", "wb+");
if(fp == NULL)
{
printf("Cannot open file");
exit(1);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 123
}
}

/// sizeof each record i.e. size of structure variable e


recsize = sizeof(e);

/// infinite loop continues until the break statement encounter


while(1)
{
system("cls"); ///clear the console window
gotoxy(30,10); /// move the cursor to position 30, 10 from top-left corner
printf("1. Add Record");
gotoxy(30,12);
printf("2. List Records");
gotoxy(30,14);
printf("3. Modify Records");
gotoxy(30,16);
printf("4. Delete Records");
gotoxy(30,18);
printf("5. Exit");
gotoxy(30,20);
printf("Your Choice: ");

fflush(stdin); /// flush the input buffer


choice = getche(); /// get the input from keyboard
switch(choice)
{
case '1':
system("cls");
fseek(fp,0,SEEK_END);
another = 'y';
while(another == 'y')
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 124
{
printf("\n Enter name: ");
scanf("%s", e.name);
printf("\n Enter age: ");
scanf("%d", & e.age);
printf("\n Enter basic salary: ");
scanf("%f", &e.bs);

fwrite(&e,recsize,1,fp);

printf("\n Add another record(y/n) ");


fflush(stdin);
another = getche();
}
break;
case '2':
system("cls");
rewind(fp); ///this moves file cursor to start of the file
while(fread(&e,recsize,1,fp)==1) per fetch
{
printf("\n %s %d %.2f",e.name,e.age,e.bs);
}
getch();
break;

case '3':
system("cls");
another = 'y';

while(another == 'y')
{
printf("Enter the employee name to modify: ");
scanf("%s", empname);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 125
rewind(fp);
while(fread(&e,recsize,1,fp)==1)
{
if(strcmp(e.name, empname) == 0)
{
printf("\n Enter new name, age and salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fseek(fp,-recsize, SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
}
printf("\n Modify another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
{
printf("\n Enter name of employee to delete: ");
scanf("%s", empname);
ft = fopen("Temp.dat", "wb");
rewind(fp);
while(fread(&e,recsize,1,fp) == 1)
{
if(strcmp(e.name, empname) != 0)
{
fwrite(&e,recsize,1,ft);
}
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 126
fclose(fp);
fclose(ft);
remove("EMP.DAT");
rename("Temp.dat", "EMP.DAT"); /// rename the temp file to original file name
fp = fopen("EMP.DAT", "rb+");
printf("Delete another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '5':
fclose(fp); /// close the file
exit(0); /// exit from the program
}
}
return 0;
}

OUTPUT:
1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 1
Enter name: sai
Enter age: 24
Enter salary: 15000.00
Add another record(y/n): n

1. Add Record
2. List Records
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 127
3. Modify Records
4. Delete Records
5. Exit
Your choice: 2
sai 24 15000.00

1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 3
Enter the employee name to modify: sai
Enter new name, age, salary: sai 25 16000.00
Modify another record(y/n): n

1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 4
Enter name of employee to delete: sai
Delete another record(y/n): n

1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 5

K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 128

Potrebbero piacerti anche